max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
582 | <filename>bean/src/main/java/com/easy/bean/SpringLifeCycleAware.java
package com.easy.bean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class SpringLifeCycleAware implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
log.info("SpringLifeCycleAware 开始");
}
}
| 213 |
348 | {"nom":"Montcenis","circ":"5ème circonscription","dpt":"Saône-et-Loire","inscrits":1765,"abs":1026,"votants":739,"blancs":52,"nuls":27,"exp":660,"res":[{"nuance":"LR","nom":"<NAME>","voix":337},{"nuance":"REM","nom":"<NAME>","voix":323}]} | 98 |
5,169 | {
"name": "BLAlert",
"version": "1.0",
"summary": "Show custom alerts with a neat animation as found in Tweetbot 4.",
"description": "Beautiful animated alerts inspired by Tweetbot 4",
"homepage": "https://github.com/B-Lach/Alert",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/B-Lach/Alert.git",
"tag": "1.0"
},
"platforms": {
"ios": "9.0"
},
"source_files": "BLAlert/Classes/**/*",
"pushed_with_swift_version": "3.0"
}
| 231 |
356 | <gh_stars>100-1000
#include "shader.h"
#include <candle.h>
#include "components/light.h"
#include "components/node.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <utils/str.h>
#include <utils/shaders_default.h>
static char default_vs[1024] = "";
static char default_vs_end[] =
"\n"
" gl_Position = pos;\n"
"}\n";
static char default_gs[1024];
static const char default_gs_end[] = "";
static void checkShaderError(GLuint shader, const char *name, const char *code);
static char *string_preprocess(const char *src, uint32_t len, const char *filename,
bool_t defines, bool_t has_gshader, bool_t has_skin);
struct source
{
size_t len;
char filename[32];
char *src;
};
static char *shader_preprocess(struct source source, bool_t defines,
bool_t has_gshader, bool_t has_skin);
vs_t g_vs[64];
uint32_t g_vs_num = 0;
fs_t g_fs[64];
uint32_t g_fs_num = 0;
static struct source *g_sources = NULL;
static uint32_t g_sources_num = 0;
/* TODO Shader sources should be a resource like any other */
/* void *shader_loader_glsl(const char *bytes, size_t bytes_num, const char *name, */
/* uint32_t ext) */
/* { */
/* printf("name %s\n", name); */
/* shader_add_source(name, bytes, bytes_num); */
/* return output; */
/* } */
void shaders_reg()
{
/* TODO Shader sources should be a resource like any other */
/* sauces_loader(ref("glsl"), shader_loader_glsl); */
shaders_candle();
strcat(default_vs,
"#include \"candle:uniforms.glsl\"\n"
#ifdef MESH4
"layout (location = 0) in vec4 P;\n"
#else
"layout (location = 0) in vec3 P;\n"
#endif
"layout (location = 1) in vec3 N;\n"
"layout (location = 2) in vec2 UV;\n"
"layout (location = 3) in vec3 TG;\n"
"layout (location = 4) in vec2 ID;\n"
"layout (location = 5) in vec3 COL;\n"
"layout (location = 6) in vec4 BID;\n"
"layout (location = 7) in vec4 WEI;\n"
"layout (location = 8) in mat4 M;\n"
);
strcat(default_vs,
"layout (location = 12) in vec4 PROPS;\n"
/* PROPS.x = material PROPS.y = NOTHING PROPS.zw = id */
#ifdef MESH4
"layout (location = 13) in float ANG4;\n"
#endif
"flat out uvec2 $id;\n"
"flat out uint $matid;\n"
"flat out vec2 $object_id;\n"
"flat out uvec2 $poly_id;\n"
"flat out vec3 $obj_pos;\n"
"flat out mat4 $model;\n"
"out vec4 $poly_color;\n"
"out vec3 $vertex_position;\n"
"out vec3 $vertex_world_position;\n"
"out vec2 $texcoord;\n"
);
strcat(default_vs,
"out vec3 $vertex_normal;\n"
"out vec3 $vertex_tangent;\n"
"void main()\n"
"{\n"
" vec4 pos = vec4(P.xyz, 1.0);\n"
" $obj_pos = (M * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n"
" $model = M;\n"
" $poly_color = vec4(COL, 1.0);\n"
" $matid = uint(PROPS.x);\n"
" $poly_id = uvec2(ID);\n"
" $id = uvec2(PROPS.zw);\n"
" $texcoord = UV;\n"
" $vertex_position = pos.xyz;\n"
);
strcat(default_gs,
"#version 420\n"
"#extension GL_EXT_geometry_shader : enable\n"
"#extension GL_OES_geometry_shader : enable\n"
"layout(points) in;\n"
"layout(triangle_strip, max_vertices = 15) out;\n"
"#include \"candle:uniforms.glsl\"\n"
);
strcat(default_gs,
"flat in uvec2 $id[1];\n"
"flat in uint $matid[1];\n"
"flat in vec2 $object_id[1];\n"
"flat in uvec2 $poly_id[1];\n"
"flat in vec3 $obj_pos[1];\n"
"flat in mat4 $model[1];\n"
"in vec4 $poly_color[1];\n"
"in vec3 $vertex_position[1];\n"
"in vec3 $vertex_world_position[1];\n"
"in vec2 $texcoord[1];\n"
"in vec3 $vertex_normal[1];\n"
"in vec3 $vertex_tangent[1];\n"
);
strcat(default_gs,
"flat out uvec2 id;\n"
"flat out uint matid;\n"
"flat out vec2 object_id;\n"
"flat out uvec2 poly_id;\n"
"flat out vec3 obj_pos;\n"
"flat out mat4 model;\n"
"out vec4 poly_color;\n"
"out vec3 vertex_position;\n"
"out vec3 vertex_world_position;\n"
"out vec2 texcoord;\n"
"out vec3 vertex_normal;\n"
"out vec3 vertex_tangent;\n"
);
}
vertex_modifier_t vertex_modifier_new(const char *code)
{
vertex_modifier_t self;
self.type = 0;
self.code = str_dup(code);
self.header = false;
return self;
}
vertex_modifier_t vertex_header_new(const char *code)
{
vertex_modifier_t self;
self.type = 0;
self.header = true;
self.code = str_dup(code);
return self;
}
vertex_modifier_t geometry_modifier_new(const char *code)
{
vertex_modifier_t self;
self.type = 1;
self.code = str_dup(code);
self.header = false;
return self;
}
uint32_t vs_new_loader(vs_t *self)
{
if(self->vmodifier_num)
{
unsigned int i;
char *code = str_new(64);
char *ncode;
for(i = 0; i < self->vmodifier_num; i++)
{
str_cat(&code, self->vmodifiers[i].code);
}
ncode = string_preprocess(code, str_len(code), "vmodifier", true,
self->gmodifier_num > 0, self->has_skin);
self->vprogram = glCreateShader(GL_VERTEX_SHADER); glerr();
glShaderSource(self->vprogram, 1, (const GLchar**)&ncode, NULL);
glCompileShader(self->vprogram); glerr();
checkShaderError(self->vprogram, self->name, ncode);
str_free(code);
free(ncode);
}
if(self->gmodifier_num)
{
unsigned int i;
char *code = str_new(64);
char *ncode;
for(i = 0; i < self->gmodifier_num; i++)
{
str_cat(&code, self->gmodifiers[i].code);
}
ncode = string_preprocess(code, str_len(code), "gmodifier", false,
true, self->has_skin);
/* { */
/* const char *line = ncode; */
/* uint32_t line_num = 1u; */
/* while (true) */
/* { */
/* char *next_line = strchr(line, '\n'); */
/* if (next_line) */
/* { */
/* printf("%d %.*s\n", line_num, (int)(next_line - line), line); */
/* line = next_line+1; */
/* } */
/* else */
/* { */
/* printf("%d %s\n", line_num, line); */
/* break; */
/* } */
/* line_num++; */
/* } */
/* } */
self->gprogram = glCreateShader(GL_GEOMETRY_SHADER); glerr();
glShaderSource(self->gprogram, 1, (const GLchar**)&ncode, NULL);
glCompileShader(self->gprogram); glerr();
checkShaderError(self->gprogram, self->name, ncode);
str_free(code);
free(ncode);
}
self->ready = 1;
return 1;
}
vs_t *vs_new(const char *name, bool_t has_skin, uint32_t num_modifiers, ...)
{
va_list va;
uint32_t i = g_vs_num++;
vs_t *self = &g_vs[i];
uint32_t num_headers = 0;
self->index = i;
strcpy(self->name, name);
self->has_skin = has_skin;
self->ready = 0;
self->vmodifier_num = 1;
self->gmodifier_num = 0;
va_start(va, num_modifiers);
for(i = 0; i < num_modifiers; i++)
{
vertex_modifier_t vst = va_arg(va, vertex_modifier_t);
if(vst.header)
{
self->vmodifiers[0] = vst;
self->vmodifier_num++;
num_headers++;
}
else if(vst.type == 1)
{
/* Skip over the first geometry modifier */
if(self->gmodifier_num == 0) self->gmodifier_num = 1;
self->gmodifiers[self->gmodifier_num++] = vst;
}
else
{
self->vmodifiers[self->vmodifier_num++] = vst;
}
}
va_end(va);
self->vmodifiers[num_headers] = vertex_modifier_new(default_vs);
if(self->gmodifier_num > 0)
{
self->gmodifiers[0] = geometry_modifier_new(default_gs);
self->gmodifiers[self->gmodifier_num++] = geometry_modifier_new(default_gs_end);
}
self->vmodifiers[self->vmodifier_num++] = vertex_modifier_new(default_vs_end);
loader_push(g_candle->loader, (loader_cb)vs_new_loader, self, NULL);
return self;
}
void shader_add_source(const char *name, char data[], uint32_t len)
{
uint32_t i;
bool_t found = false;
for (i = 0; i < g_sources_num; i++)
{
if(!strcmp(name, g_sources[i].filename))
{
found = true;
break;
}
}
if (!found)
{
i = g_sources_num++;
g_sources = realloc(g_sources, (sizeof *g_sources) * g_sources_num);
}
else
{
free(g_sources[i].src);
}
g_sources[i].len = len + 1;
strcpy(g_sources[i].filename, name);
g_sources[i].src = malloc(len + 1);
memcpy(g_sources[i].src, data, len);
g_sources[i].src[len] = '\0';
}
static const struct source shader_source(const char *filename)
{
FILE *fp;
char *buffer = NULL;
#define prefix "resauces/shaders/"
char name[] = prefix "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
struct source res = {0};
size_t lsize;
uint32_t i;
for(i = 0; i < g_sources_num; i++)
{
if(!strcmp(filename, g_sources[i].filename))
{
return g_sources[i];
}
}
strncpy(name + (sizeof(prefix) - 1), filename, (sizeof(name) - (sizeof(prefix) - 1)) - 1);
fp = fopen(name, "rb");
if(!fp)
{
return res;
}
fseek(fp, 0L, SEEK_END);
lsize = ftell(fp);
rewind(fp);
buffer = calloc(1, lsize + 1);
if(fread(buffer, lsize, 1, fp) != 1)
{
fclose(fp);
free(buffer);
return res;
}
fclose(fp);
i = g_sources_num++;
g_sources = realloc(g_sources, (sizeof *g_sources) * g_sources_num);
g_sources[i].len = lsize;
strcpy(g_sources[i].filename, filename);
g_sources[i].src = str_dup(buffer);
return g_sources[i];
}
char *replace(char *buffer, long offset, long end_offset,
const char *str, size_t *lsize)
{
long command_size = end_offset - offset;
size_t inc_size = strlen(str);
long nsize = offset + inc_size + (*lsize) - command_size;
char *new_buffer = calloc(nsize + 1, 1);
memcpy(new_buffer, buffer, offset);
memcpy(new_buffer + offset, str, inc_size);
memcpy(new_buffer + offset + inc_size, buffer + end_offset,
(*lsize) - end_offset);
(*lsize) = nsize;
free(buffer);
return new_buffer;
}
static char *string_preprocess(const char *src, bool_t len, const char *filename,
bool_t defines, bool_t has_gshader,
bool_t has_skin)
{
size_t lsize = len;
const char *line;
#ifdef DEBUG
uint32_t include_lines[128];
uint32_t include_lines_num;
#endif
uint32_t line_num;
char *token = NULL;
uint32_t include_num = 0;
/* char defs[][64] = { "#version 420\n" */
const char version_str[] =
"#version 300 es\n";
const char skin_str[] =
"#define HAS_SKIN\n";
char defs[][64] = {
"#ifndef DEFINES\n"
, "#define DEFINES\n"
, "precision highp float;\n"
, "precision highp int;\n"
#ifdef MESH4
, "#define MESH4\n"
#endif
#ifdef __EMSCRIPTEN__
, "#define EMSCRIPTEN\n"
#endif
, "#define BUFFER uniform struct\n"
, "#endif\n"
};
uint32_t i;
char *buffer = NULL;
if(defines)
{
lsize += strlen(version_str);
if (has_skin)
{
lsize += strlen(skin_str);
}
for (i = 0; i < sizeof(defs)/sizeof(*defs); i++)
{
lsize += strlen(defs[i]);
}
}
buffer = malloc(lsize + 9);
buffer[0] = '\0';
if(defines)
{
strcat(buffer, version_str);
if (has_skin)
{
strcat(buffer, skin_str);
}
for (i = 0; i < sizeof(defs)/sizeof(*defs); i++)
{
strcat(buffer, defs[i]);
}
}
strcat(buffer, src);
line = src;
line_num = 1u;
#ifdef DEBUG
include_lines_num = 0u;
#endif
while(line)
{
#ifdef DEBUG
if (!strncmp(line, "#include", strlen("#include")))
{
include_lines[include_lines_num++] = line_num;
}
#endif
line_num++;
line = strchr(line, '\n');
if (line) line++;
}
while((token = strstr(buffer, "#include")))
{
struct source inc;
long offset = token - buffer;
char include_name[512];
char *start = strchr(token, '"') + 1;
char *end = strchr(start, '"');
long end_offset = end - buffer + 1;
char *include;
char *include_buffer;
memcpy(include_name, start, end - start);
include_name[end - start] = '\0';
inc = shader_source(include_name);
if(!inc.src) break;
include = str_new(64);
include_buffer = shader_preprocess(inc, false, has_gshader, false);
#ifdef DEBUG
str_catf(&include, "#line 1 \"%s\"\n", include_name);
#endif
str_cat(&include, include_buffer);
free(include_buffer);
#ifdef DEBUG
str_catf(&include, "\n#line %d \"%s\"\n", include_lines[include_num],
filename);
#endif
buffer = replace(buffer, offset, end_offset, include, &lsize);
str_free(include);
include_num++;
}
while((token = strstr(buffer, "$")))
{
long offset = token - buffer;
long end_offset = offset + 1;
buffer = replace(buffer, offset, end_offset,
has_gshader ? "_G_" : "", &lsize);
}
return buffer;
}
static char *shader_preprocess(struct source source, bool_t defines,
bool_t has_gshader, bool_t has_skin)
{
if(!source.src) return NULL;
return string_preprocess(source.src, source.len, source.filename,
defines, has_gshader, has_skin);
}
static void checkShaderError(GLuint shader,
const char *name, const char *code)
{
GLint success = 0;
GLint bufflen;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &bufflen);
if (bufflen > 1)
{
GLchar log_string[2048];
glGetShaderInfoLog(shader, bufflen, 0, log_string);
printf("Log found for '%s':\n%s", name, log_string);
}
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success != GL_TRUE)
{
printf("%s\n", name);
exit(1);
}
}
static uint32_t shader_new_loader(shader_t *self)
{
GLint bufflen;
int32_t isLinked = 1;
int32_t count;
uint32_t i;
uint32_t fprogram = self->fs->program;
uint32_t vprogram = g_vs[self->index].vprogram;
uint32_t gprogram = g_vs[self->index].gprogram;
self->program = glCreateProgram(); glerr();
glAttachShader(self->program, vprogram); glerr();
glAttachShader(self->program, fprogram); glerr();
if(gprogram) /* not all programs need a geometry shader */
{
glAttachShader(self->program, g_vs[self->index].gprogram); glerr();
}
glLinkProgram(self->program); glerr();
/* #ifdef DEBUG */
glValidateProgram(self->program);
/* checkShaderError(self->program, self->fs->filename, NULL); */
glGetProgramiv(self->program, GL_INFO_LOG_LENGTH, &bufflen);
if (bufflen > 1)
{
GLchar log_string[2048];
glGetProgramInfoLog(self->program, bufflen, 0, log_string);
printf("Log found for '%s':\n%s\n", self->fs->filename, log_string);
}
glGetProgramiv(self->program, GL_LINK_STATUS, &isLinked);
/* #endif */
if (!isLinked)
{
printf("Failed to link %u %u %u\n", fprogram, vprogram, gprogram);
exit(1);
}
self->uniforms = kh_init(uniform);
/* GET UNNIFORM LOCATIONS */
glGetProgramiv(self->program, GL_ACTIVE_UNIFORMS, &count);
for (i = 0; i < count; i++)
{
khiter_t k;
uint32_t *uniform;
int32_t ret;
GLint size; /* size of the variable */
GLenum type; /* type of the variable (float, vec3 or mat4, etc) */
const GLsizei bufSize = 64; /* maximum name length */
GLchar name[64]; /* variable name in GLSL */
GLsizei length; /* name length */
glGetActiveUniform(self->program, i, bufSize, &length, &size, &type, name);
k = kh_put(uniform, self->uniforms, ref(name), &ret);
uniform = &kh_value(self->uniforms, k);
(*uniform) = glGetUniformLocation(self->program, name);
}
self->scene_ubi = glGetUniformBlockIndex(self->program, "scene_t");
self->renderer_ubi = glGetUniformBlockIndex(self->program, "renderer_t");
self->skin_ubi = glGetUniformBlockIndex(self->program, "skin_t");
self->cms_ubi = glGetUniformBlockIndex(self->program, "cms_t");
glerr();
self->ready = true;
return 1;
}
uint32_t shader_cached_uniform(shader_t *self, uint32_t ref)
{
khiter_t k = kh_get(uniform, self->uniforms, ref);
if (k == kh_end(self->uniforms))
{
return ~0;
}
return kh_value(self->uniforms, k);
}
static uint32_t fs_new_loader(fs_variation_t *self)
{
char buffer[256];
self->program = 0;
sprintf(buffer, "%s.glsl", self->filename);
self->code = shader_preprocess(shader_source(buffer), true, false, false);
if(!self->code)
{
printf("Fs has no code\n");
exit(1);
}
self->program = glCreateShader(GL_FRAGMENT_SHADER); glerr();
/* { */
/* const char *line = self->code; */
/* uint32_t line_num = 1u; */
/* while (true) */
/* { */
/* char *next_line = strchr(line, '\n'); */
/* if (next_line) */
/* { */
/* printf("%d %.*s\n", line_num, (int)(next_line - line), line); */
/* line = next_line+1; */
/* } */
/* else */
/* { */
/* printf("%d %s\n", line_num, line); */
/* break; */
/* } */
/* line_num++; */
/* } */
/* } */
glShaderSource(self->program, 1, (const GLchar**)&self->code, NULL); glerr();
glCompileShader(self->program); glerr();
checkShaderError(self->program, self->filename, self->code);
self->ready = 1;
return 1;
}
fs_t *fs_get(const char *filename)
{
uint32_t i;
for (i = 0; i < g_fs_num; i++)
{
if (!strcmp(filename, g_fs[i].filename)) return &g_fs[i];
}
return NULL;
}
void fs_update_variation(fs_t *self, uint32_t fs_variation)
{
uint32_t i;
fs_variation_t *var = &self->variations[fs_variation];
for (i = 0; i < 32; i++)
{
if (var->combinations[i])
{
shader_destroy(var->combinations[i]);
}
var->combinations[i] = NULL;
}
loader_push(g_candle->loader, (loader_cb)fs_new_loader, var, NULL);
}
void fs_push_variation(fs_t *self, const char *filename)
{
uint32_t i;
fs_variation_t *var = &self->variations[self->variations_num];
var->program = 0;
var->ready = 0;
self->variations_num++;
for (i = 0; i < 32; i++)
{
var->combinations[i] = NULL;
}
strcpy(var->filename, filename);
loader_push(g_candle->loader, (loader_cb)fs_new_loader, var, NULL);
}
fs_t *fs_new(const char *filename)
{
uint32_t i;
fs_t *self;
if(!filename) return NULL;
for (i = 0; i < g_fs_num; i++)
{
if (!strcmp(filename, g_fs[i].filename)) return &g_fs[i];
}
self = &g_fs[g_fs_num++];
self->variations_num = 0;
strcpy(self->filename, filename);
if ( strncmp(filename, "candle:gbuffer", strlen("candle:gbuffer"))
&& strncmp(filename, "candle:query_mips", strlen("candle:query_mips"))
&& strncmp(filename, "candle:select_map", strlen("candle:select_map"))
&& strncmp(filename, "candle:shadow_map", strlen("candle:shadow_map"))
&& strncmp(filename, "candle:caustics", strlen("candle:caustics")))
{
fs_push_variation(self, filename);
}
return self;
}
shader_t *shader_new(fs_t *fs, uint32_t fs_variation, vs_t *vs)
{
shader_t *self = calloc(1, sizeof *self);
self->fs = &fs->variations[fs_variation];
self->index = vs->index;
self->fs_variation = fs_variation;
self->has_skin = vs->has_skin;
self->ready = 0;
loader_push(g_candle->loader, (loader_cb)shader_new_loader, self, NULL);
return self;
}
void shader_bind(shader_t *self)
{
glUseProgram(self->program); glerr();
}
/* GLuint _shader_uniform(shader_t *self, const char *uniform, const char *member) */
/* { */
/* if(member) */
/* { */
/* char buffer[256]; */
/* snprintf(buffer, sizeof(buffer) - 1, "%s_%s", uniform, member); */
/* return glGetUniformLocation(self->program, buffer); glerr(); */
/* } */
/* return glGetUniformLocation(self->program, uniform); glerr(); */
/* } */
/* GLuint shader_uniform(shader_t *self, const char *uniform, const char *member) */
/* { */
/* if(member) */
/* { */
/* char buffer[256]; */
/* snprintf(buffer, sizeof(buffer) - 1, "%s.%s", uniform, member); */
/* return glGetUniformLocation(self->program, buffer); glerr(); */
/* } */
/* return glGetUniformLocation(self->program, uniform); glerr(); */
/* } */
void fs_destroy(fs_t *self)
{
uint32_t i, j;
for(i = 0; i < self->variations_num; i++)
{
for(j = 0; j < g_vs_num; j++)
{
shader_destroy(self->variations[i].combinations[j]);
}
glDeleteShader(self->variations[i].program); glerr();
}
}
void shader_destroy(shader_t *self)
{
uint32_t fprogram = self->fs->program;
uint32_t vprogram = g_vs[self->index].vprogram;
uint32_t gprogram = g_vs[self->index].gprogram;
if (fprogram)
{
glDetachShader(self->program, fprogram); glerr();
}
if (vprogram)
{
glDetachShader(self->program, vprogram); glerr();
}
if (gprogram)
{
glDetachShader(self->program, gprogram); glerr();
}
glDeleteProgram(self->program); glerr();
free(self);
}
| 8,727 |
593 | package org.ananas.runner.kernel.paginate;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Map;
import lombok.Data;
import org.ananas.runner.kernel.model.Dataframe;
import org.ananas.runner.kernel.model.Variable;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class PaginationBody {
public String type;
public String metadataId;
public Map<String, Object> config;
public Map<String, Variable> params;
public Dataframe dataframe;
}
| 154 |
9,516 | <reponame>ketyi/dgl
import dgl.multiprocessing as mp
import unittest, os
import pytest
import torch as th
import dgl
import backend as F
def start_unified_tensor_worker(dev_id, input, seq_idx, rand_idx, output_seq, output_rand):
device = th.device('cuda:'+str(dev_id))
th.cuda.set_device(device)
input_unified = dgl.contrib.UnifiedTensor(input, device=device)
output_seq.copy_(input_unified[seq_idx.to(device)].cpu())
output_rand.copy_(input_unified[rand_idx.to(device)].cpu())
@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
@unittest.skipIf(F.ctx().type == 'cpu', reason='gpu only test')
def test_unified_tensor():
test_row_size = 65536
test_col_size = 128
rand_test_size = 8192
input = th.rand((test_row_size, test_col_size))
input_unified = dgl.contrib.UnifiedTensor(input, device=th.device('cuda'))
seq_idx = th.arange(0, test_row_size)
assert th.all(th.eq(input[seq_idx], input_unified[seq_idx]))
seq_idx = seq_idx.to(th.device('cuda'))
assert th.all(th.eq(input[seq_idx].to(th.device('cuda')), input_unified[seq_idx]))
rand_idx = th.randint(0, test_row_size, (rand_test_size,))
assert th.all(th.eq(input[rand_idx], input_unified[rand_idx]))
rand_idx = rand_idx.to(th.device('cuda'))
assert th.all(th.eq(input[rand_idx].to(th.device('cuda')), input_unified[rand_idx]))
@unittest.skipIf(os.name == 'nt', reason='Do not support windows yet')
@unittest.skipIf(F.ctx().type == 'cpu', reason='gpu only test')
@pytest.mark.parametrize("num_workers", [1, 2])
def test_multi_gpu_unified_tensor(num_workers):
if F.ctx().type == 'cuda' and th.cuda.device_count() < num_workers:
pytest.skip("Not enough number of GPUs to do this test, skip multi-gpu test.")
test_row_size = 65536
test_col_size = 128
rand_test_size = 8192
input = th.rand((test_row_size, test_col_size)).share_memory_()
seq_idx = th.arange(0, test_row_size).share_memory_()
rand_idx = th.randint(0, test_row_size, (rand_test_size,)).share_memory_()
output_seq = []
output_rand = []
output_seq_cpu = input[seq_idx]
output_rand_cpu = input[rand_idx]
worker_list = []
ctx = mp.get_context('spawn')
for i in range(num_workers):
output_seq.append(th.zeros((test_row_size, test_col_size)).share_memory_())
output_rand.append(th.zeros((rand_test_size, test_col_size)).share_memory_())
p = ctx.Process(target=start_unified_tensor_worker,
args=(i, input, seq_idx, rand_idx, output_seq[i], output_rand[i],))
p.start()
worker_list.append(p)
for p in worker_list:
p.join()
for p in worker_list:
assert p.exitcode == 0
for i in range(num_workers):
assert th.all(th.eq(output_seq_cpu, output_seq[i]))
assert th.all(th.eq(output_rand_cpu, output_rand[i]))
if __name__ == '__main__':
test_unified_tensor()
test_multi_gpu_unified_tensor(1)
test_multi_gpu_unified_tensor(2)
| 1,314 |
575 | <filename>Sample Code/ObjcSampleCode/DJISdkDemo/Demo/Gimbal/GimbalActionsTableViewController.h
//
// GimbalActionsTableTableViewController.h
// DJISdkDemo
//
// Copyright © 2015 DJI. All rights reserved.
//
#import "DemoComponentActionTableViewController.h"
@interface GimbalActionsTableViewController : DemoComponentActionTableViewController
@end
| 112 |
1,031 | <gh_stars>1000+
"""
Copyright (c) 2020 Intel Corporation
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 cv2
import numpy as np
try:
from numpy.core.umath import clip
except ImportError:
from numpy import clip
from ..adapters import Adapter
from ..config import ConfigValidator, StringField, ConfigError, NumberField
from ..representation import PoseEstimationPrediction
from ..utils import contains_any, UnsupportedPackage
try:
from skimage.measure import block_reduce
except ImportError as import_error:
block_reduce = UnsupportedPackage('skimage.measure', import_error.msg)
class OpenPoseAdapter(Adapter):
__provider__ = 'human_pose_estimation_openpose'
prediction_types = (PoseEstimationPrediction, )
@classmethod
def parameters(cls):
parameters = super().parameters()
parameters.update({
'part_affinity_fields_out': StringField(
description="Name of output layer with keypoints pairwise relations (part affinity fields).",
optional=True
),
'keypoints_heatmap_out': StringField(
description="Name of output layer with keypoints heatmaps.", optional=True
),
'upscale_factor': NumberField(
description="Upscaling factor for output feature maps before postprocessing.",
value_type=float, min_value=1, default=1, optional=True
),
})
return parameters
@classmethod
def validate_config(cls, config, fetch_only=False, **kwargs):
return super().validate_config(
config, fetch_only=fetch_only, on_extra_argument=ConfigValidator.WARN_ON_EXTRA_ARGUMENT
)
def configure(self):
self.upscale_factor = self.get_value_from_config('upscale_factor')
self.part_affinity_fields = self.get_value_from_config('part_affinity_fields_out')
self.keypoints_heatmap = self.get_value_from_config('keypoints_heatmap_out')
self.concat_out = self.part_affinity_fields is None and self.keypoints_heatmap is None
if not self.concat_out:
contains_both = self.part_affinity_fields is not None and self.keypoints_heatmap is not None
if not contains_both:
raise ConfigError(
'human_pose_estimation adapter should contains both: keypoints_heatmap_out '
'and part_affinity_fields_out or not contain them at all (in single output model case)'
)
self._keypoints_heatmap_bias = self.keypoints_heatmap + '/add_'
self._part_affinity_fields_bias = self.part_affinity_fields + '/add_'
self.decoder = OpenPoseDecoder(num_joints=18, delta=0.5 if self.upscale_factor == 1 else 0.0)
if isinstance(block_reduce, UnsupportedPackage):
block_reduce.raise_error(self.__provider__)
self.nms = HeatmapNMS(kernel=2 * int(np.round(6 / 7 * self.upscale_factor)) + 1)
def process(self, raw, identifiers, frame_meta):
result = []
raw_outputs = self._extract_predictions(raw, frame_meta)
if not self.concat_out:
if not contains_any(raw_outputs, [self.part_affinity_fields, self._part_affinity_fields_bias]):
raise ConfigError('part affinity fields output not found')
if not contains_any(raw_outputs, [self.keypoints_heatmap, self._keypoints_heatmap_bias]):
raise ConfigError('keypoints heatmap output not found')
keypoints_heatmap = raw_outputs[
self.keypoints_heatmap if self.keypoints_heatmap in raw_outputs else self._keypoints_heatmap_bias
]
pafs = raw_outputs[
self.part_affinity_fields if self.part_affinity_fields in raw_outputs
else self._part_affinity_fields_bias
]
raw_output = zip(identifiers, keypoints_heatmap, pafs, frame_meta)
else:
concat_out = raw_outputs[self.output_blob]
keypoints_num = concat_out.shape[1] // 3
keypoints_heat_map = concat_out[:, :keypoints_num, :]
pafs = concat_out[:, keypoints_num:, :]
raw_output = zip(identifiers, keypoints_heat_map, pafs, frame_meta)
for identifier, heatmap, paf, meta in raw_output:
output_h, output_w = heatmap.shape[-2:]
if self.upscale_factor > 1:
self.decoder.delta = 0
heatmap = np.transpose(heatmap, (1, 2, 0))
heatmap = cv2.resize(heatmap, (0, 0), fx=self.upscale_factor, fy=self.upscale_factor,
interpolation=cv2.INTER_CUBIC)
heatmap = np.transpose(heatmap, (2, 0, 1))
paf = np.transpose(np.squeeze(paf), (1, 2, 0))
paf = cv2.resize(paf, (0, 0), fx=self.upscale_factor, fy=self.upscale_factor,
interpolation=cv2.INTER_CUBIC)
paf = np.transpose(paf, (2, 0, 1))
hmap = heatmap[None]
nms_hmap = self.nms(hmap)
poses, scores = self.decoder(hmap, nms_hmap, paf[None])
if len(scores) == 0:
result.append(PoseEstimationPrediction(
identifier,
np.empty((0, 17), dtype=float),
np.empty((0, 17), dtype=float),
np.empty((0, 17), dtype=float),
np.empty((0, ), dtype=float)
))
continue
poses = poses.astype(float)
scores = np.asarray(scores).astype(float)
scale_x = meta['scale_x']
scale_y = meta['scale_y']
input_h, input_w = next(iter(meta['input_shape'].values()))[-2:]
output_scale_x = input_w / output_w
output_scale_y = input_h / output_h
poses[:, :, 0] *= output_scale_x / self.upscale_factor / scale_x
poses[:, :, 1] *= output_scale_y / self.upscale_factor / scale_y
point_scores = poses[:, :, 2]
result.append(PoseEstimationPrediction(
identifier,
poses[:, :, 0],
poses[:, :, 1],
point_scores,
scores))
return result
class HeatmapNMS:
def __init__(self, kernel):
self.kernel = kernel
self.pad = (kernel - 1) // 2
def max_pool(self, x):
# Max pooling kernel x kernel with stride 1 x 1.
k = self.kernel
p = self.pad
pooled = np.zeros_like(x)
hmap = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)))
h, w = hmap.shape[-2:]
for i in range(k):
n = (h - i) // k * k
for j in range(k):
m = (w - j) // k * k
hmap_slice = hmap[..., i:i + n, j:j + m]
pooled[..., i::k, j::k] = block_reduce(hmap_slice, (1, 1, k, k), np.max)
return pooled
def __call__(self, heatmaps):
pooled = self.max_pool(heatmaps)
return heatmaps * (pooled == heatmaps).astype(heatmaps.dtype)
class OpenPoseDecoder:
BODY_PARTS_KPT_IDS = ((1, 2), (1, 5), (2, 3), (3, 4), (5, 6), (6, 7), (1, 8), (8, 9), (9, 10), (1, 11),
(11, 12), (12, 13), (1, 0), (0, 14), (14, 16), (0, 15), (15, 17), (2, 16), (5, 17))
BODY_PARTS_PAF_IDS = (12, 20, 14, 16, 22, 24, 0, 2, 4, 6, 8, 10, 28, 30, 34, 32, 36, 18, 26)
def __init__(self, num_joints=18, skeleton=BODY_PARTS_KPT_IDS, paf_indices=BODY_PARTS_PAF_IDS,
max_points=100, score_threshold=0.1, min_paf_alignment_score=0.05, delta=0.5):
self.num_joints = num_joints
self.skeleton = skeleton
self.paf_indices = paf_indices
self.max_points = max_points
self.score_threshold = score_threshold
self.min_paf_alignment_score = min_paf_alignment_score
self.delta = delta
self.points_per_limb = 10
self.grid = np.arange(self.points_per_limb, dtype=np.float32).reshape(1, -1, 1)
def __call__(self, heatmaps, nms_heatmaps, pafs):
batch_size, _, h, w = heatmaps.shape
assert batch_size == 1, 'Batch size of 1 only supported'
keypoints = self.extract_points(heatmaps, nms_heatmaps)
pafs = np.transpose(pafs, (0, 2, 3, 1))
if self.delta > 0:
for kpts in keypoints:
kpts[:, :2] += self.delta
clip(kpts[:, 0], 0, w - 1, out=kpts[:, 0])
clip(kpts[:, 1], 0, h - 1, out=kpts[:, 1])
pose_entries, keypoints = self.group_keypoints(keypoints, pafs, pose_entry_size=self.num_joints + 2)
poses, scores = self.convert_to_coco_format(pose_entries, keypoints)
if len(poses) > 0:
poses = np.asarray(poses, dtype=np.float32)
poses = poses.reshape((poses.shape[0], -1, 3))
else:
poses = np.empty((0, 17, 3), dtype=np.float32)
scores = np.empty(0, dtype=np.float32)
return poses, scores
def extract_points(self, heatmaps, nms_heatmaps):
batch_size, channels_num, h, w = heatmaps.shape
assert batch_size == 1, 'Batch size of 1 only supported'
assert channels_num >= self.num_joints
xs, ys, scores = self.top_k(nms_heatmaps)
masks = scores > self.score_threshold
all_keypoints = []
keypoint_id = 0
for k in range(self.num_joints):
# Filter low-score points.
mask = masks[0, k]
x = xs[0, k][mask].ravel()
y = ys[0, k][mask].ravel()
score = scores[0, k][mask].ravel()
n = len(x)
if n == 0:
all_keypoints.append(np.empty((0, 4), dtype=np.float32))
continue
# Apply quarter offset to improve localization accuracy.
x, y = self.refine(heatmaps[0, k], x, y)
clip(x, 0, w - 1, out=x)
clip(y, 0, h - 1, out=y)
# Pack resulting points.
keypoints = np.empty((n, 4), dtype=np.float32)
keypoints[:, 0] = x
keypoints[:, 1] = y
keypoints[:, 2] = score
keypoints[:, 3] = np.arange(keypoint_id, keypoint_id + n)
keypoint_id += n
all_keypoints.append(keypoints)
return all_keypoints
def top_k(self, heatmaps):
N, K, _, W = heatmaps.shape
heatmaps = heatmaps.reshape(N, K, -1)
# Get positions with top scores.
ind = heatmaps.argpartition(-self.max_points, axis=2)[:, :, -self.max_points:]
scores = np.take_along_axis(heatmaps, ind, axis=2)
# Keep top scores sorted.
subind = np.argsort(-scores, axis=2)
ind = np.take_along_axis(ind, subind, axis=2)
scores = np.take_along_axis(scores, subind, axis=2)
y, x = np.divmod(ind, W)
return x, y, scores
@staticmethod
def refine(heatmap, x, y):
h, w = heatmap.shape[-2:]
valid = np.logical_and(np.logical_and(x > 0, x < w - 1), np.logical_and(y > 0, y < h - 1))
xx = x[valid]
yy = y[valid]
dx = np.sign(heatmap[yy, xx + 1] - heatmap[yy, xx - 1], dtype=np.float32) * 0.25
dy = np.sign(heatmap[yy + 1, xx] - heatmap[yy - 1, xx], dtype=np.float32) * 0.25
x = x.astype(np.float32)
y = y.astype(np.float32)
x[valid] += dx
y[valid] += dy
return x, y
@staticmethod
def is_disjoint(pose_a, pose_b):
pose_a = pose_a[:-2]
pose_b = pose_b[:-2]
return np.all(np.logical_or.reduce((pose_a == pose_b, pose_a < 0, pose_b < 0)))
def update_poses(self, kpt_a_id, kpt_b_id, all_keypoints, connections, pose_entries, pose_entry_size):
for connection in connections:
pose_a_idx = -1
pose_b_idx = -1
for j, pose in enumerate(pose_entries):
if pose[kpt_a_id] == connection[0]:
pose_a_idx = j
if pose[kpt_b_id] == connection[1]:
pose_b_idx = j
if pose_a_idx < 0 and pose_b_idx < 0:
# Create new pose entry.
pose_entry = np.full(pose_entry_size, -1, dtype=np.float32)
pose_entry[kpt_a_id] = connection[0]
pose_entry[kpt_b_id] = connection[1]
pose_entry[-1] = 2
pose_entry[-2] = np.sum(all_keypoints[connection[0:2], 2]) + connection[2]
pose_entries.append(pose_entry)
elif pose_a_idx >= 0 and pose_b_idx >= 0 and pose_a_idx != pose_b_idx:
# Merge two poses are disjoint merge them, otherwise ignore connection.
pose_a = pose_entries[pose_a_idx]
pose_b = pose_entries[pose_b_idx]
if self.is_disjoint(pose_a, pose_b):
pose_a += pose_b
pose_a[:-2] += 1
pose_a[-2] += connection[2]
del pose_entries[pose_b_idx]
elif pose_a_idx >= 0 and pose_b_idx >= 0:
# Adjust score of a pose.
pose_entries[pose_a_idx][-2] += connection[2]
elif pose_a_idx >= 0:
# Add a new limb into pose.
pose = pose_entries[pose_a_idx]
if pose[kpt_b_id] < 0:
pose[-2] += all_keypoints[connection[1], 2]
pose[kpt_b_id] = connection[1]
pose[-2] += connection[2]
pose[-1] += 1
elif pose_b_idx >= 0:
# Add a new limb into pose.
pose = pose_entries[pose_b_idx]
if pose[kpt_a_id] < 0:
pose[-2] += all_keypoints[connection[0], 2]
pose[kpt_a_id] = connection[0]
pose[-2] += connection[2]
pose[-1] += 1
return pose_entries
@staticmethod
def connections_nms(a_idx, b_idx, affinity_scores):
# From all retrieved connections that share starting/ending keypoints leave only the top-scoring ones.
order = affinity_scores.argsort()[::-1]
affinity_scores = affinity_scores[order]
a_idx = a_idx[order]
b_idx = b_idx[order]
idx = []
has_kpt_a = set()
has_kpt_b = set()
for t, (i, j) in enumerate(zip(a_idx, b_idx)):
if i not in has_kpt_a and j not in has_kpt_b:
idx.append(t)
has_kpt_a.add(i)
has_kpt_b.add(j)
idx = np.asarray(idx, dtype=np.int32)
return a_idx[idx], b_idx[idx], affinity_scores[idx]
def group_keypoints(self, all_keypoints_by_type, pafs, pose_entry_size=20):
all_keypoints = np.concatenate(all_keypoints_by_type, axis=0)
pose_entries = []
# For every limb.
for part_id, paf_channel in enumerate(self.paf_indices):
kpt_a_id, kpt_b_id = self.skeleton[part_id]
kpts_a = all_keypoints_by_type[kpt_a_id]
kpts_b = all_keypoints_by_type[kpt_b_id]
n = len(kpts_a)
m = len(kpts_b)
if n == 0 or m == 0:
continue
# Get vectors between all pairs of keypoints, i.e. candidate limb vectors.
a = kpts_a[:, :2]
a = np.broadcast_to(a[None], (m, n, 2))
b = kpts_b[:, :2]
vec_raw = (b[:, None, :] - a).reshape(-1, 1, 2)
# Sample points along every candidate limb vector.
steps = (1 / (self.points_per_limb - 1) * vec_raw)
points = steps * self.grid + a.reshape(-1, 1, 2)
points = points.round().astype(dtype=np.int32)
x = points[..., 0].ravel()
y = points[..., 1].ravel()
# Compute affinity score between candidate limb vectors and part affinity field.
part_pafs = pafs[0, :, :, paf_channel:paf_channel + 2]
field = part_pafs[y, x].reshape(-1, self.points_per_limb, 2)
vec_norm = np.linalg.norm(vec_raw, ord=2, axis=-1, keepdims=True)
vec = vec_raw / (vec_norm + 1e-6)
affinity_scores = (field * vec).sum(-1).reshape(-1, self.points_per_limb)
valid_affinity_scores = affinity_scores > self.min_paf_alignment_score
valid_num = valid_affinity_scores.sum(1)
affinity_scores = (affinity_scores * valid_affinity_scores).sum(1) / (valid_num + 1e-6)
success_ratio = valid_num / self.points_per_limb
# Get a list of limbs according to the obtained affinity score.
valid_limbs = np.where(np.logical_and(affinity_scores > 0, success_ratio > 0.8))[0]
if len(valid_limbs) == 0:
continue
b_idx, a_idx = np.divmod(valid_limbs, n)
affinity_scores = affinity_scores[valid_limbs]
# Suppress incompatible connections.
a_idx, b_idx, affinity_scores = self.connections_nms(a_idx, b_idx, affinity_scores)
connections = list(zip(kpts_a[a_idx, 3].astype(np.int32),
kpts_b[b_idx, 3].astype(np.int32),
affinity_scores))
if len(connections) == 0:
continue
# Update poses with new connections.
pose_entries = self.update_poses(kpt_a_id, kpt_b_id, all_keypoints,
connections, pose_entries, pose_entry_size)
# Remove poses with not enough points.
pose_entries = np.asarray(pose_entries, dtype=np.float32).reshape(-1, pose_entry_size)
pose_entries = pose_entries[pose_entries[:, -1] >= 3]
return pose_entries, all_keypoints
@staticmethod
def convert_to_coco_format(pose_entries, all_keypoints):
num_joints = 17
coco_keypoints = []
scores = []
for pose in pose_entries:
if len(pose) == 0:
continue
keypoints = np.zeros(num_joints * 3)
reorder_map = [0, -1, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3]
person_score = pose[-2]
for keypoint_id, target_id in zip(pose[:-2], reorder_map):
if target_id < 0:
continue
cx, cy, score = 0, 0, 0 # keypoint not found
if keypoint_id != -1:
cx, cy, score = all_keypoints[int(keypoint_id), 0:3]
keypoints[target_id * 3 + 0] = cx
keypoints[target_id * 3 + 1] = cy
keypoints[target_id * 3 + 2] = score
coco_keypoints.append(keypoints)
scores.append(person_score * max(0, (pose[-1] - 1))) # -1 for 'neck'
return np.asarray(coco_keypoints), np.asarray(scores)
| 9,801 |
488 | <filename>tests/CompileTests/ElsaTestCases/d0075.cc<gh_stars>100-1000
struct A;
template<class T> struct B {};
template<class T> void foo (B<T> &);
template<class T> void foo (A*);
int main() {
B<A> s;
// this doubling is necessary to reproduce the bug
foo(s);
foo(s);
}
| 110 |
435 | {
"copyright_text": null,
"description": "Looking to deploy Python code on AWS Lambda? Getting started with serverless can be a bit daunting at times with creating the functions, configuring them, configuring api gateways and what not. In this talk you will learn about the magic of rapid serverless api development using AWS Chalice.",
"duration": 1574,
"language": "eng",
"recorded": "2019-09-14",
"related_urls": [
{
"label": "Conference schedule",
"url": "http://2019.pyconuk.org/schedule/"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/kDHu6oarH1Y/maxresdefault.jpg",
"title": "Rapid prototyping scalable Python services using AWS Chalice",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=kDHu6oarH1Y"
}
]
}
| 308 |
925 | #include "object.h"
#include <algorithm>
#include <iostream>
#include <memory>
#include <type_traits>
#include "arglist.h"
#include "attribute.h"
#include "entity.h"
#include "hook.h"
#include "utils.h"
using std::endl;
using std::function;
using std::make_shared;
using std::pair;
using std::shared_ptr;
using std::string;
using std::vector;
ChildEntry::ChildEntry(Object& owner, const string& name)
: owner_(owner)
, name_(name)
{
owner_.addChildDoc(name_, this);
}
pair<ArgList,string> Object::splitPath(const string &path) {
vector<string> splitpath = ArgList(path, OBJECT_PATH_SEPARATOR).toVector();
if (splitpath.empty()) {
return make_pair(splitpath, "");
}
string last = splitpath.back();
splitpath.pop_back();
return make_pair(splitpath, last);
}
void Object::wireAttributes(vector<Attribute*> attrs)
{
for (auto attr : attrs) {
attr->setOwner(this);
attribs_[attr->name()] = attr;
}
}
void Object::addAttribute(Attribute* attr) {
attr->setOwner(this);
attribs_[attr->name()] = attr;
}
void Object::removeAttribute(Attribute* attr) {
auto it = attribs_.find(attr->name());
if (it == attribs_.end()) {
return;
}
if (it->second != attr) {
return;
}
attribs_.erase(it);
}
void Object::ls(Output out)
{
string docString = doc();
if (!docString.empty()) {
// print doc string and ensure that there is an empty line
// afterwards
out << docString << "\n";
if ('\n' != *docString.rbegin()) {
out << "\n";
}
}
const auto& children = this->children();
out << children.size() << (children.size() == 1 ? " child" : " children")
<< (!children.empty() ? ":" : ".") << endl;
for (auto it : children) {
out << " " << it.first << "." << endl;
}
out << attribs_.size() << (attribs_.size() == 1 ? " attribute" : " attributes")
<< (!attribs_.empty() ? ":" : ".") << endl;
out << " .---- type\n"
<< " | .-- writable\n"
<< " | | .-- hookable\n"
<< " V V V" << endl;
for (auto it : attribs_) {
out << " " << it.second->typechar();
out << " " << (it.second->writable() ? "w" : "-");
out << " " << (it.second->hookable() ? "h" : "-");
out << " " << it.first;
if (it.second->type() == Type::STRING
|| it.second->type() == Type::REGEX )
{
out << " = \"" << it.second->str() << "\"" << endl;
} else {
out << " = " << it.second->str() << endl;
}
}
}
Attribute* Object::attribute(const string &name) {
auto it = attribs_.find(name);
if (it == attribs_.end()) {
return nullptr;
} else {
return it->second;
}
}
Object* Object::child(const string &name) {
auto it_dyn = childrenDynamic_.find(name);
if (it_dyn != childrenDynamic_.end()) {
return it_dyn->second();
}
auto it = children_.find(name);
if (it != children_.end()) {
return it->second;
} else {
return {};
};
}
Object* Object::child(Path path) {
std::ostringstream out;
OutputChannels channels("", out, out);
return child(path, channels);
}
Object* Object::child(Path path, Output output) {
Object* cur = this;
string cur_path = "";
while (!path.empty()) {
cur = cur->child(path.front());
if (!cur) {
output.perror() << "Object \"" << cur_path << "\""
<< " has no child named \"" << path.front()
<< "\"" << endl;
return nullptr;
}
cur_path += path.front();
cur_path += ".";
path.shift();
}
return cur;
}
void Object::notifyHooks(HookEvent event, const string& arg)
{
for (auto h : hooks_) {
if (h) {
switch (event) {
case HookEvent::CHILD_ADDED:
h->childAdded(this, arg);
break;
case HookEvent::CHILD_REMOVED:
h->childRemoved(this, arg);
break;
case HookEvent::ATTRIBUTE_CHANGED:
h->attributeChanged(this, arg);
break;
}
} // TODO: else throw
}
}
void Object::addDynamicChild(function<Object* ()> child, const string& name)
{
childrenDynamic_[name] = child;
}
void Object::addChild(Object* child, const string &name)
{
children_[name] = child;
notifyHooks(HookEvent::CHILD_ADDED, name);
}
void Object::removeChild(const string &child)
{
notifyHooks(HookEvent::CHILD_REMOVED, child);
children_.erase(child);
}
void Object::addChildDoc(const string& name, HasDocumentation* doc)
{
childrenDoc_[name] = doc;
}
const HasDocumentation* Object::childDoc(const string& child)
{
auto it = childrenDoc_.find(child);
if (it != childrenDoc_.end()) {
return it->second;
} else {
return nullptr;
}
}
void Object::addHook(Hook* hook)
{
hooks_.push_back(hook);
}
void Object::removeHook(Hook* hook)
{
//auto hook_locked = hook.lock();
//hooks_.erase(std::remove_if(
// hooks_.begin(),
// hooks_.end(),
// [hook_locked](weak_ptr<Hook> el) {
// return el.lock() == hook_locked;
// }), hooks_.end());
hooks_.erase(std::remove(
hooks_.begin(),
hooks_.end(),
hook), hooks_.end());
}
std::map<string, Object*> Object::children() {
// copy the map of 'static' children
auto allChildren = children_;
// and add the dynamic children
for (auto& it : childrenDynamic_) {
Object* obj = it.second();
if (obj) {
allChildren[it.first] = obj;
}
}
return allChildren;
}
class DirectoryTreeInterface : public TreeInterface {
public:
DirectoryTreeInterface(string label, Object* d) : lbl(label), dir(d) {
for (auto child : dir->children()) {
buf.push_back(child);
}
};
size_t childCount() override {
return buf.size();
};
shared_ptr<TreeInterface> nthChild(size_t idx) override {
return make_shared<DirectoryTreeInterface>(buf[idx].first, buf[idx].second);
};
void appendCaption(Output output) override {
if (!lbl.empty()) {
output << " " << lbl;
}
};
private:
string lbl;
vector<pair<string,Object*>> buf;
Object* dir;
};
void Object::printTree(Output output, string rootLabel) {
shared_ptr<TreeInterface> intface = make_shared<DirectoryTreeInterface>(rootLabel, this);
tree_print_to(intface, output);
}
Attribute* Object::deepAttribute(const string &path) {
std::ostringstream output;
OutputChannels channels("", output, output);
return deepAttribute(path, channels);
}
Attribute* Object::deepAttribute(const string &path, Output output) {
auto attr_path = splitPath(path);
auto attribute_owner = child(attr_path.first, output);
if (!attribute_owner) {
return nullptr;
}
Attribute* a = attribute_owner->attribute(attr_path.second);
if (!a) {
output.perror()
<< "Object \"" << attr_path.first.join()
<< "\" has no attribute \"" << attr_path.second
<< "\"."
<< endl;
return nullptr;
}
return a;
}
| 3,332 |
1,035 | <gh_stars>1000+
# coding: utf-8
"""
Penguin Statistics - REST APIs
Backend APIs for Arknights drop rate statistics website 'Penguin Statistics': https://penguin-stats.io/ # noqa: E501
OpenAPI spec version: 2.0.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class Item(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'add_time_point': 'int',
'existence': 'dict(str, Existence)',
'item_id': 'str',
'item_type': 'str',
'name': 'str',
'name_i18n': 'dict(str, str)',
'rarity': 'int',
'sort_id': 'int',
'sprite_coord': 'list[int]'
}
attribute_map = {
'add_time_point': 'addTimePoint',
'existence': 'existence',
'item_id': 'itemId',
'item_type': 'itemType',
'name': 'name',
'name_i18n': 'name_i18n',
'rarity': 'rarity',
'sort_id': 'sortId',
'sprite_coord': 'spriteCoord'
}
def __init__(self, add_time_point=None, existence=None, item_id=None, item_type=None, name=None, name_i18n=None, rarity=None, sort_id=None, sprite_coord=None): # noqa: E501
"""Item - a model defined in Swagger""" # noqa: E501
self._add_time_point = None
self._existence = None
self._item_id = None
self._item_type = None
self._name = None
self._name_i18n = None
self._rarity = None
self._sort_id = None
self._sprite_coord = None
self.discriminator = None
if add_time_point is not None:
self.add_time_point = add_time_point
if existence is not None:
self.existence = existence
if item_id is not None:
self.item_id = item_id
if item_type is not None:
self.item_type = item_type
if name is not None:
self.name = name
if name_i18n is not None:
self.name_i18n = name_i18n
if rarity is not None:
self.rarity = rarity
if sort_id is not None:
self.sort_id = sort_id
if sprite_coord is not None:
self.sprite_coord = sprite_coord
@property
def add_time_point(self):
"""Gets the add_time_point of this Item. # noqa: E501
:return: The add_time_point of this Item. # noqa: E501
:rtype: int
"""
return self._add_time_point
@add_time_point.setter
def add_time_point(self, add_time_point):
"""Sets the add_time_point of this Item.
:param add_time_point: The add_time_point of this Item. # noqa: E501
:type: int
"""
self._add_time_point = add_time_point
@property
def existence(self):
"""Gets the existence of this Item. # noqa: E501
The existence of the item in each server. # noqa: E501
:return: The existence of this Item. # noqa: E501
:rtype: dict(str, Existence)
"""
return self._existence
@existence.setter
def existence(self, existence):
"""Sets the existence of this Item.
The existence of the item in each server. # noqa: E501
:param existence: The existence of this Item. # noqa: E501
:type: dict(str, Existence)
"""
self._existence = existence
@property
def item_id(self):
"""Gets the item_id of this Item. # noqa: E501
:return: The item_id of this Item. # noqa: E501
:rtype: str
"""
return self._item_id
@item_id.setter
def item_id(self, item_id):
"""Sets the item_id of this Item.
:param item_id: The item_id of this Item. # noqa: E501
:type: str
"""
self._item_id = item_id
@property
def item_type(self):
"""Gets the item_type of this Item. # noqa: E501
:return: The item_type of this Item. # noqa: E501
:rtype: str
"""
return self._item_type
@item_type.setter
def item_type(self, item_type):
"""Sets the item_type of this Item.
:param item_type: The item_type of this Item. # noqa: E501
:type: str
"""
self._item_type = item_type
@property
def name(self):
"""Gets the name of this Item. # noqa: E501
:return: The name of this Item. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this Item.
:param name: The name of this Item. # noqa: E501
:type: str
"""
self._name = name
@property
def name_i18n(self):
"""Gets the name_i18n of this Item. # noqa: E501
:return: The name_i18n of this Item. # noqa: E501
:rtype: dict(str, str)
"""
return self._name_i18n
@name_i18n.setter
def name_i18n(self, name_i18n):
"""Sets the name_i18n of this Item.
:param name_i18n: The name_i18n of this Item. # noqa: E501
:type: dict(str, str)
"""
self._name_i18n = name_i18n
@property
def rarity(self):
"""Gets the rarity of this Item. # noqa: E501
:return: The rarity of this Item. # noqa: E501
:rtype: int
"""
return self._rarity
@rarity.setter
def rarity(self, rarity):
"""Sets the rarity of this Item.
:param rarity: The rarity of this Item. # noqa: E501
:type: int
"""
self._rarity = rarity
@property
def sort_id(self):
"""Gets the sort_id of this Item. # noqa: E501
:return: The sort_id of this Item. # noqa: E501
:rtype: int
"""
return self._sort_id
@sort_id.setter
def sort_id(self, sort_id):
"""Sets the sort_id of this Item.
:param sort_id: The sort_id of this Item. # noqa: E501
:type: int
"""
self._sort_id = sort_id
@property
def sprite_coord(self):
"""Gets the sprite_coord of this Item. # noqa: E501
The position in the sprite image. # noqa: E501
:return: The sprite_coord of this Item. # noqa: E501
:rtype: list[int]
"""
return self._sprite_coord
@sprite_coord.setter
def sprite_coord(self, sprite_coord):
"""Sets the sprite_coord of this Item.
The position in the sprite image. # noqa: E501
:param sprite_coord: The sprite_coord of this Item. # noqa: E501
:type: list[int]
"""
self._sprite_coord = sprite_coord
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Item, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Item):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 4,039 |
892 | <reponame>github/advisory-database
{
"schema_version": "1.2.0",
"id": "GHSA-jwp4-rhw6-7g6m",
"modified": "2022-05-13T01:52:43Z",
"published": "2022-05-13T01:52:43Z",
"aliases": [
"CVE-2018-5202"
],
"details": "SKCertService 2.5.5 and earlier contains a vulnerability that could allow remote attacker to execute arbitrary code. This vulnerability exists due to the way .dll files are loaded by SKCertService. It allows an attacker to load a .dll of the attacker's choosing that could execute arbitrary code without the user's knowledge.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-5202"
},
{
"type": "WEB",
"url": "https://www.boho.or.kr/krcert/secNoticeView.do?bulletin_writing_sequence=30119"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 460 |
2,539 | // Rar1Decoder.h
// According to unRAR license, this code may not be used to develop
// a program that creates RAR archives
#ifndef __COMPRESS_RAR1_DECODER_H
#define __COMPRESS_RAR1_DECODER_H
#include "../../Common/MyCom.h"
#include "../ICoder.h"
#include "../Common/InBuffer.h"
#include "BitmDecoder.h"
#include "HuffmanDecoder.h"
#include "LzOutWindow.h"
namespace NCompress {
namespace NRar1 {
const UInt32 kNumRepDists = 4;
class CDecoder :
public ICompressCoder,
public ICompressSetDecoderProperties2,
public CMyUnknownImp
{
CLzOutWindow m_OutWindowStream;
NBitm::CDecoder<CInBuffer> m_InBitStream;
UInt64 m_UnpackSize;
UInt32 LastDist;
UInt32 LastLength;
UInt32 m_RepDistPtr;
UInt32 m_RepDists[kNumRepDists];
bool _isSolid;
bool _solidAllowed;
bool StMode;
int FlagsCnt;
UInt32 FlagBuf, AvrPlc, AvrPlcB, AvrLn1, AvrLn2, AvrLn3;
unsigned Buf60, NumHuf, LCount;
UInt32 Nhfb, Nlzb, MaxDist3;
UInt32 ChSet[256], ChSetA[256], ChSetB[256], ChSetC[256];
UInt32 Place[256], PlaceA[256], PlaceB[256], PlaceC[256];
UInt32 NToPl[256], NToPlB[256], NToPlC[256];
UInt32 ReadBits(unsigned numBits);
HRESULT CopyBlock(UInt32 distance, UInt32 len);
UInt32 DecodeNum(const Byte *numTab);
HRESULT ShortLZ();
HRESULT LongLZ();
HRESULT HuffDecode();
void GetFlagsBuf();
void CorrHuff(UInt32 *CharSet, UInt32 *NumToPlace);
void OldUnpWriteBuf();
HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
public:
CDecoder();
MY_UNKNOWN_IMP1(ICompressSetDecoderProperties2)
STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
};
}}
#endif
| 765 |
348 | {"nom":"Proissans","circ":"4ème circonscription","dpt":"Dordogne","inscrits":831,"abs":394,"votants":437,"blancs":31,"nuls":17,"exp":389,"res":[{"nuance":"REM","nom":"<NAME>","voix":215},{"nuance":"FI","nom":"<NAME>","voix":174}]} | 91 |
5,964 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/html/forms/WeekInputType.h"
#include "core/HTMLNames.h"
#include "core/InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
#include "platform/DateComponents.h"
#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
namespace blink {
using namespace HTMLNames;
static const int weekDefaultStepBase = -259200000; // The first day of 1970-W01.
static const int weekDefaultStep = 1;
static const int weekStepScaleFactor = 604800000;
PassRefPtrWillBeRawPtr<InputType> WeekInputType::create(HTMLInputElement& element)
{
return adoptRefWillBeNoop(new WeekInputType(element));
}
void WeekInputType::countUsage()
{
countUsageIfVisible(UseCounter::InputTypeWeek);
}
const AtomicString& WeekInputType::formControlType() const
{
return InputTypeNames::week;
}
StepRange WeekInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (weekDefaultStep, weekDefaultStepBase, weekStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
return InputType::createStepRange(anyStepHandling, weekDefaultStepBase, Decimal::fromDouble(DateComponents::minimumWeek()), Decimal::fromDouble(DateComponents::maximumWeek()), stepDescription);
}
bool WeekInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
{
ASSERT(out);
unsigned end;
return out->parseWeek(string, 0, end) && end == string.length();
}
bool WeekInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
{
ASSERT(date);
return date->setMillisecondsSinceEpochForWeek(value);
}
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
String WeekInputType::formatDateTimeFieldsState(const DateTimeFieldsState& dateTimeFieldsState) const
{
if (!dateTimeFieldsState.hasYear() || !dateTimeFieldsState.hasWeekOfYear())
return emptyString();
return String::format("%04u-W%02u", dateTimeFieldsState.year(), dateTimeFieldsState.weekOfYear());
}
void WeekInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters& layoutParameters, const DateComponents&) const
{
layoutParameters.dateTimeFormat = locale().weekFormatInLDML();
layoutParameters.fallbackDateTimeFormat = "yyyy-'W'ww";
if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum))
layoutParameters.minimum = DateComponents();
if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum))
layoutParameters.maximum = DateComponents();
layoutParameters.placeholderForYear = "----";
}
bool WeekInputType::isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const
{
return hasYear && hasWeek;
}
#endif
} // namespace blink
| 1,366 |
368 | package ezvcard.io;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ezvcard.VCard;
import ezvcard.io.scribe.ScribeIndex;
import ezvcard.io.scribe.VCardPropertyScribe;
import ezvcard.parameter.AddressType;
import ezvcard.property.Address;
import ezvcard.property.Label;
import ezvcard.property.VCardProperty;
/*
Copyright (c) 2012-2021, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
/**
* Parses vCards from a data stream.
* @author <NAME>
*/
public abstract class StreamReader implements Closeable {
protected final List<ParseWarning> warnings = new ArrayList<ParseWarning>();
protected ScribeIndex index = new ScribeIndex();
protected ParseContext context;
/**
* Reads all vCards from the data stream.
* @return the vCards
* @throws IOException if there's a problem reading from the stream
*/
public List<VCard> readAll() throws IOException {
List<VCard> vcards = new ArrayList<VCard>();
VCard vcard;
while ((vcard = readNext()) != null) {
vcards.add(vcard);
}
return vcards;
}
/**
* Reads the next vCard from the data stream.
* @return the next vCard or null if there are no more
* @throws IOException if there's a problem reading from the stream
*/
public VCard readNext() throws IOException {
warnings.clear();
context = new ParseContext();
return _readNext();
}
/**
* Reads the next vCard from the data stream.
* @return the next vCard or null if there are no more
* @throws IOException if there's a problem reading from the stream
*/
protected abstract VCard _readNext() throws IOException;
/**
* Matches up a list of {@link Label} properties with their corresponding
* {@link Address} properties. If no match can be found, then the LABEL
* property itself is assigned to the vCard.
* @param vcard the vCard that the properties belong to
* @param labels the LABEL properties
*/
protected void assignLabels(VCard vcard, List<Label> labels) {
List<Address> adrs = vcard.getAddresses();
for (Label label : labels) {
boolean orphaned = true;
Set<AddressType> labelTypes = new HashSet<AddressType>(label.getTypes());
for (Address adr : adrs) {
if (adr.getLabel() != null) {
//a label has already been assigned to it
continue;
}
Set<AddressType> adrTypes = new HashSet<AddressType>(adr.getTypes());
if (adrTypes.equals(labelTypes)) {
adr.setLabel(label.getValue());
orphaned = false;
break;
}
}
if (orphaned) {
vcard.addOrphanedLabel(label);
}
}
}
/**
* <p>
* Registers a property scribe. This is the same as calling:
* </p>
* <p>
* {@code getScribeIndex().register(scribe)}
* </p>
* @param scribe the scribe to register
*/
public void registerScribe(VCardPropertyScribe<? extends VCardProperty> scribe) {
index.register(scribe);
}
/**
* Gets the scribe index.
* @return the scribe index
*/
public ScribeIndex getScribeIndex() {
return index;
}
/**
* Sets the scribe index.
* @param index the scribe index
*/
public void setScribeIndex(ScribeIndex index) {
this.index = index;
}
/**
* Gets the warnings from the last vCard that was unmarshalled. This list is
* reset every time a new vCard is read.
* @return the warnings or empty list if there were no warnings
*/
public List<ParseWarning> getWarnings() {
return new ArrayList<ParseWarning>(warnings);
}
}
| 1,566 |
615 | # 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.
from oslo_config import cfg
from keystone.conf import utils
included_previous_windows = cfg.IntOpt(
'included_previous_windows',
default=1,
min=0,
max=10,
help=utils.fmt("""
The number of previous windows to check when processing TOTP passcodes.
"""))
GROUP_NAME = __name__.split('.')[-1]
ALL_OPTS = [
included_previous_windows,
]
def register_opts(conf):
conf.register_opts(ALL_OPTS, group=GROUP_NAME)
def list_opts():
return {GROUP_NAME: ALL_OPTS}
| 337 |
5,169 | <gh_stars>1000+
{
"name": "ModelSynchro",
"version": "0.2.3",
"summary": "An automated way to generate network models.",
"description": "An automated way to generate network models from JSON and keep them up to date.",
"homepage": "https://github.com/jgsamudio/ModelSynchro",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/jgsamudio/ModelSynchro.git",
"tag": "0.2.3"
},
"preserve_paths": "ModelSynchro/Source/**/*",
"platforms": {
"osx": null,
"ios": null,
"tvos": null,
"watchos": null
}
}
| 264 |
2,757 | <gh_stars>1000+
/* LibTomCrypt, modular cryptographic library -- <NAME>
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt_private.h"
#ifdef LTC_CHACHA20POLY1305_MODE
/**
Process an entire GCM packet in one call.
@param key The secret key
@param keylen The length of the secret key
@param iv The initialization vector
@param ivlen The length of the initialization vector
@param aad The additional authentication data (header)
@param aadlen The length of the aad
@param in The plaintext
@param inlen The length of the plaintext (ciphertext length is the same)
@param out The ciphertext
@param tag [out] The MAC tag
@param taglen [in/out] The MAC tag length
@param direction Encrypt or Decrypt mode (CHACHA20POLY1305_ENCRYPT or CHACHA20POLY1305_DECRYPT)
@return CRYPT_OK on success
*/
int chacha20poly1305_memory(const unsigned char *key, unsigned long keylen,
const unsigned char *iv, unsigned long ivlen,
const unsigned char *aad, unsigned long aadlen,
const unsigned char *in, unsigned long inlen,
unsigned char *out,
unsigned char *tag, unsigned long *taglen,
int direction)
{
chacha20poly1305_state st;
int err;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(iv != NULL);
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(out != NULL);
LTC_ARGCHK(tag != NULL);
if ((err = chacha20poly1305_init(&st, key, keylen)) != CRYPT_OK) { goto LBL_ERR; }
if ((err = chacha20poly1305_setiv(&st, iv, ivlen)) != CRYPT_OK) { goto LBL_ERR; }
if (aad && aadlen > 0) {
if ((err = chacha20poly1305_add_aad(&st, aad, aadlen)) != CRYPT_OK) { goto LBL_ERR; }
}
if (direction == CHACHA20POLY1305_ENCRYPT) {
if ((err = chacha20poly1305_encrypt(&st, in, inlen, out)) != CRYPT_OK) { goto LBL_ERR; }
}
else if (direction == CHACHA20POLY1305_DECRYPT) {
if ((err = chacha20poly1305_decrypt(&st, in, inlen, out)) != CRYPT_OK) { goto LBL_ERR; }
}
else {
err = CRYPT_INVALID_ARG;
goto LBL_ERR;
}
err = chacha20poly1305_done(&st, tag, taglen);
LBL_ERR:
#ifdef LTC_CLEAN_STACK
zeromem(&st, sizeof(chacha20poly1305_state));
#endif
return err;
}
#endif
/* ref: HEAD -> develop */
/* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */
/* commit time: 2018-10-15 10:51:17 +0200 */
| 1,293 |
669 | // Copyright(c) 2019 - 2020, #Momo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include "RenderHelperObject.h"
namespace MxEngine
{
struct PointLightBaseData
{
Matrix4x4 Transform;
Vector3 Position;
float Radius;
Vector3 Color;
float AmbientIntensity;
constexpr static size_t Size = 16 + 3 + 1 + 3 + 1;
};
class PointLightInstancedObject : public RenderHelperObject
{
VertexBufferHandle instancedVBO;
public:
MxVector<PointLightBaseData> Instances;
PointLightInstancedObject() = default;
PointLightInstancedObject(size_t vertexOffset, size_t vertexCount, size_t indexOffset, size_t indexCount)
: RenderHelperObject(vertexOffset, vertexCount, indexOffset, indexCount, Factory<VertexArray>::Create())
{
this->instancedVBO = Factory<VertexBuffer>::Create(nullptr, 0, UsageType::STATIC_DRAW);
std::array vertexLayout = {
VertexAttribute::Entry<Vector3>(), // position
VertexAttribute::Entry<Vector2>(), // texture uv
VertexAttribute::Entry<Vector3>(), // normal
VertexAttribute::Entry<Vector3>(), // tangent
VertexAttribute::Entry<Vector3>(), // bitangent
};
std::array instanceLayout = {
VertexAttribute::Entry<Matrix4x4>(), // transform
VertexAttribute::Entry<Vector4>(), // position + radius
VertexAttribute::Entry<Vector4>(), // color + ambient
};
VAO->AddVertexLayout(*this->GetVBO(), vertexLayout, VertexAttributeInputRate::PER_VERTEX);
VAO->AddVertexLayout(*this->instancedVBO, instanceLayout, VertexAttributeInputRate::PER_INSTANCE);
this->VAO->LinkIndexBuffer(*this->GetIBO());
}
void SubmitToVBO() { instancedVBO->BufferDataWithResize((float*)this->Instances.data(), this->Instances.size() * PointLightBaseData::Size); }
};
} | 1,244 |
382 | <gh_stars>100-1000
/*
* Copyright (c) 2017. <NAME>
*
* 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 jahirfiquitiva.libs.fabsmenu;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
@SuppressWarnings("unused")
public class TitleFAB extends FloatingActionButton implements CoordinatorLayout.AttachedBehavior {
private static final int MAX_CHARACTERS_COUNT = 25;
/**
* Hide/show animations from FloatingActionButton
* https://goo.gl/e5DWfT
*/
private static final Interpolator FAST_OUT_LINEAR_IN_INTERPOLATOR =
new FastOutLinearInInterpolator();
private static final Interpolator LINEAR_OUT_SLOW_IN_INTERPOLATOR =
new LinearOutSlowInInterpolator();
private static final int SHOW_HIDE_ANIM_DURATION = 200;
private static final int ANIM_STATE_NONE = 0;
private static final int ANIM_STATE_HIDING = 1;
private static final int ANIM_STATE_SHOWING = 2;
private static final String TAG = TitleFAB.class.getSimpleName();
int mAnimState = ANIM_STATE_NONE;
private String title;
private boolean titleClickEnabled;
@ColorInt
private int titleBackgroundColor;
@ColorInt
private int titleTextColor;
private float titleCornerRadius;
private int titleTextPadding;
private View.OnClickListener clickListener;
public TitleFAB(Context context) {
this(context, null);
}
public TitleFAB(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public TitleFAB(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
@SuppressLint("PrivateResource")
void init(Context context, AttributeSet attributeSet) {
int fabSize = TitleFAB.SIZE_MINI;
TypedArray attr =
context.obtainStyledAttributes(attributeSet, R.styleable.TitleFAB, 0, 0);
try {
title = attr.getString(R.styleable.TitleFAB_fab_title);
titleClickEnabled = attr.getBoolean(R.styleable.TitleFAB_fab_enableTitleClick, true);
titleBackgroundColor = attr.getInt(R.styleable.TitleFAB_fab_title_backgroundColor,
ContextCompat
.getColor(context, android.R.color.white));
titleTextColor = attr.getInt(R.styleable.TitleFAB_fab_title_textColor,
ContextCompat.getColor(context, android.R.color.black));
titleCornerRadius =
attr.getDimensionPixelSize(R.styleable.TitleFAB_fab_title_cornerRadius, -1);
titleTextPadding =
attr.getDimensionPixelSize(R.styleable.TitleFAB_fab_title_textPadding,
(int) DimensionUtils.convertDpToPixel(8, context));
fabSize = attr.getInt(R.styleable.FloatingActionButton_fabSize, fabSize);
} catch (Exception e) {
Log.w(TAG, "Failure reading attributes", e);
} finally {
attr.recycle();
}
setOnClickListener(null);
setSize(fabSize);
}
@Override
public void setBackgroundColor(@ColorInt int color) {
super.setBackgroundTintList(ColorStateList.valueOf(color));
}
public OnClickListener getOnClickListener() {
return clickListener;
}
@Override
public void setOnClickListener(@Nullable OnClickListener l) {
this.clickListener = l;
setClickable(l != null);
super.setOnClickListener(l);
}
@Override
public void setClickable(boolean clickable) {
super.setClickable(clickable);
setFocusable(clickable);
View label = getLabelView();
if (label != null)
label.setOnClickListener(titleClickEnabled && clickable ? clickListener : null);
}
LabelView getLabelView() {
return (LabelView) getTag(R.id.fab_label);
}
public String getTitle() {
if (title == null) return null;
StringBuilder titleBuilder = new StringBuilder();
if (title.length() > MAX_CHARACTERS_COUNT) {
titleBuilder.append(title.substring(0, MAX_CHARACTERS_COUNT)).append("...");
} else {
titleBuilder.append(title);
}
return titleBuilder.toString();
}
public void setTitle(String title) {
this.title = title;
LabelView label = getLabelView();
if (label != null && label.getContent() != null) {
label.getContent().setText(title);
}
}
public boolean isTitleClickEnabled() {
return titleClickEnabled;
}
@SuppressWarnings("SameParameterValue")
public void setTitleClickEnabled(boolean titleClickEnabled) {
this.titleClickEnabled = titleClickEnabled;
LabelView label = getLabelView();
if (label != null) {
label.setClickable(titleClickEnabled);
}
}
public int getTitleBackgroundColor() {
return titleBackgroundColor;
}
public void setTitleBackgroundColor(@ColorInt int titleBackgroundColor) {
this.titleBackgroundColor = titleBackgroundColor;
LabelView label = getLabelView();
if (label != null) {
label.setBackgroundColor(titleBackgroundColor);
}
}
public int getTitleTextColor() {
return titleTextColor;
}
public void setTitleTextColor(@ColorInt int titleTextColor) {
this.titleTextColor = titleTextColor;
LabelView label = getLabelView();
if (label != null && label.getContent() != null) {
label.getContent().setTextColor(titleTextColor);
}
}
public float getTitleCornerRadius() {
return titleCornerRadius;
}
public void setTitleCornerRadius(float titleCornerRadius) {
this.titleCornerRadius = titleCornerRadius;
LabelView label = getLabelView();
if (label != null) {
label.setRadius(titleCornerRadius);
}
}
public int getTitleTextPadding() {
return titleTextPadding;
}
public void setTitleTextPadding(int titleTextPadding) {
this.titleTextPadding = titleTextPadding;
LabelView label = getLabelView();
if (label != null && label.getContent() != null) {
label.getContent().setPadding(titleTextPadding, titleTextPadding / 2, titleTextPadding,
titleTextPadding / 2);
}
}
boolean isOrWillBeShown() {
View label = getLabelView();
if (label == null) return false;
if (label.getVisibility() != View.VISIBLE) {
// If we not currently visible, return true if we're animating to be shown
return mAnimState == ANIM_STATE_SHOWING;
} else {
// Otherwise if we're visible, return true if we're not animating to be hidden
return mAnimState != ANIM_STATE_HIDING;
}
}
boolean isOrWillBeHidden() {
View label = getLabelView();
if (label == null) return true;
if (label.getVisibility() == View.VISIBLE) {
// If we currently visible, return true if we're animating to be hidden
return mAnimState == ANIM_STATE_HIDING;
} else {
// Otherwise if we're not visible, return true if we're not animating to be shown
return mAnimState != ANIM_STATE_SHOWING;
}
}
@Override
public void show() {
final View label = getLabelView();
if (label == null) {
super.show();
return;
}
if (isOrWillBeShown()) {
// We either are or will soon be visible, skip the call
return;
}
label.animate().cancel();
if (shouldAnimateVisibilityChange()) {
mAnimState = ANIM_STATE_SHOWING;
if (label.getVisibility() != View.VISIBLE) {
// If the view isn't visible currently, we'll animate it from a single pixel
label.setAlpha(0f);
label.setScaleY(0f);
label.setScaleX(0f);
}
label.animate()
.scaleX(1f)
.scaleY(1f)
.alpha(1f)
.setDuration(SHOW_HIDE_ANIM_DURATION)
.setInterpolator(LINEAR_OUT_SLOW_IN_INTERPOLATOR)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
TitleFAB.super.show();
label.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {
mAnimState = ANIM_STATE_NONE;
}
});
} else {
label.setVisibility(View.VISIBLE);
label.setAlpha(1f);
label.setScaleY(1f);
label.setScaleX(1f);
}
}
@Override
public void hide() {
final View label = getLabelView();
if (label == null) {
super.hide();
return;
}
if (isOrWillBeHidden()) {
// We either are or will soon be hidden, skip the call
return;
}
label.animate().cancel();
if (shouldAnimateVisibilityChange()) {
mAnimState = ANIM_STATE_HIDING;
label.animate()
.scaleX(0f)
.scaleY(0f)
.alpha(0f)
.setDuration(SHOW_HIDE_ANIM_DURATION)
.setInterpolator(FAST_OUT_LINEAR_IN_INTERPOLATOR)
.setListener(new AnimatorListenerAdapter() {
private boolean mCancelled;
@Override
public void onAnimationStart(Animator animation) {
TitleFAB.super.hide();
label.setVisibility(View.VISIBLE);
mCancelled = false;
}
@Override
public void onAnimationCancel(Animator animation) {
mCancelled = true;
}
@Override
public void onAnimationEnd(Animator animation) {
mAnimState = ANIM_STATE_NONE;
if (!mCancelled) {
label.setVisibility(View.GONE);
}
}
});
} else {
// If the view isn't laid out, or we're in the editor, don't run the animation
label.setVisibility(View.GONE);
}
}
private boolean shouldAnimateVisibilityChange() {
View label = getLabelView();
if (label != null) {
return ViewCompat.isLaidOut(this) && ViewCompat.isLaidOut(label) && !isInEditMode();
} else {
return ViewCompat.isLaidOut(this) && !isInEditMode();
}
}
@NonNull
@Override
public CoordinatorLayout.Behavior getBehavior() {
return new FABSnackbarBehavior();
}
} | 5,783 |
1,097 | <reponame>Schol-R-LEA/x16-emulator<filename>cpu/mnemonics.h
/* Generated by buildtables.py */
static const char *mnemonics[256] = {
// $0X
/* $00 */ "brk ",
/* $01 */ "ora ($%02x,x)",
/* $02 */ "nop ",
/* $03 */ "nop ",
/* $04 */ "tsb $%02x",
/* $05 */ "ora $%02x",
/* $06 */ "asl $%02x",
/* $07 */ "rmb0 $%02x",
/* $08 */ "php ",
/* $09 */ "ora #$%02x",
/* $0A */ "asl a",
/* $0B */ "nop ",
/* $0C */ "tsb $%04x",
/* $0D */ "ora $%04x",
/* $0E */ "asl $%04x",
/* $0F */ "bbr0 $%02x, $%04x",
// $1X
/* $10 */ "bpl $%02x",
/* $11 */ "ora ($%02x),y",
/* $12 */ "ora ($%02x)",
/* $13 */ "nop ",
/* $14 */ "trb $%02x",
/* $15 */ "ora $%02x,x",
/* $16 */ "asl $%02x,x",
/* $17 */ "rmb1 $%02x",
/* $18 */ "clc ",
/* $19 */ "ora $%04x,y",
/* $1A */ "inc a",
/* $1B */ "nop ",
/* $1C */ "trb $%04x",
/* $1D */ "ora $%04x,x",
/* $1E */ "asl $%04x,x",
/* $1F */ "bbr1 $%02x, $%04x",
// $2X
/* $20 */ "jsr $%04x",
/* $21 */ "and ($%02x,x)",
/* $22 */ "nop ",
/* $23 */ "nop ",
/* $24 */ "bit $%02x",
/* $25 */ "and $%02x",
/* $26 */ "rol $%02x",
/* $27 */ "rmb2 $%02x",
/* $28 */ "plp ",
/* $29 */ "and #$%02x",
/* $2A */ "rol a",
/* $2B */ "nop ",
/* $2C */ "bit $%04x",
/* $2D */ "and $%04x",
/* $2E */ "rol $%04x",
/* $2F */ "bbr2 $%02x, $%04x",
// $3X
/* $30 */ "bmi $%02x",
/* $31 */ "and ($%02x),y",
/* $32 */ "and ($%02x)",
/* $33 */ "nop ",
/* $34 */ "bit $%02x,x",
/* $35 */ "and $%02x,x",
/* $36 */ "rol $%02x,x",
/* $37 */ "rmb3 $%02x",
/* $38 */ "sec ",
/* $39 */ "and $%04x,y",
/* $3A */ "dec a",
/* $3B */ "nop ",
/* $3C */ "bit $%04x,x",
/* $3D */ "and $%04x,x",
/* $3E */ "rol $%04x,x",
/* $3F */ "bbr3 $%02x, $%04x",
// $4X
/* $40 */ "rti ",
/* $41 */ "eor ($%02x,x)",
/* $42 */ "nop ",
/* $43 */ "nop ",
/* $44 */ "nop ",
/* $45 */ "eor $%02x",
/* $46 */ "lsr $%02x",
/* $47 */ "rmb4 $%02x",
/* $48 */ "pha ",
/* $49 */ "eor #$%02x",
/* $4A */ "lsr a",
/* $4B */ "nop ",
/* $4C */ "jmp $%04x",
/* $4D */ "eor $%04x",
/* $4E */ "lsr $%04x",
/* $4F */ "bbr4 $%02x, $%04x",
// $5X
/* $50 */ "bvc $%02x",
/* $51 */ "eor ($%02x),y",
/* $52 */ "eor ($%02x)",
/* $53 */ "nop ",
/* $54 */ "nop ",
/* $55 */ "eor $%02x,x",
/* $56 */ "lsr $%02x,x",
/* $57 */ "rmb5 $%02x",
/* $58 */ "cli ",
/* $59 */ "eor $%04x,y",
/* $5A */ "phy ",
/* $5B */ "nop ",
/* $5C */ "nop ",
/* $5D */ "eor $%04x,x",
/* $5E */ "lsr $%04x,x",
/* $5F */ "bbr5 $%02x, $%04x",
// $6X
/* $60 */ "rts ",
/* $61 */ "adc ($%02x,x)",
/* $62 */ "nop ",
/* $63 */ "nop ",
/* $64 */ "stz $%02x",
/* $65 */ "adc $%02x",
/* $66 */ "ror $%02x",
/* $67 */ "rmb6 $%02x",
/* $68 */ "pla ",
/* $69 */ "adc #$%02x",
/* $6A */ "ror a",
/* $6B */ "nop ",
/* $6C */ "jmp ($%04x)",
/* $6D */ "adc $%04x",
/* $6E */ "ror $%04x",
/* $6F */ "bbr6 $%02x, $%04x",
// $7X
/* $70 */ "bvs $%02x",
/* $71 */ "adc ($%02x),y",
/* $72 */ "adc ($%02x)",
/* $73 */ "nop ",
/* $74 */ "stz $%02x,x",
/* $75 */ "adc $%02x,x",
/* $76 */ "ror $%02x,x",
/* $77 */ "rmb7 $%02x",
/* $78 */ "sei ",
/* $79 */ "adc $%04x,y",
/* $7A */ "ply ",
/* $7B */ "nop ",
/* $7C */ "jmp ($%04x,x)",
/* $7D */ "adc $%04x,x",
/* $7E */ "ror $%04x,x",
/* $7F */ "bbr7 $%02x, $%04x",
// $8X
/* $80 */ "bra $%02x",
/* $81 */ "sta ($%02x,x)",
/* $82 */ "nop ",
/* $83 */ "nop ",
/* $84 */ "sty $%02x",
/* $85 */ "sta $%02x",
/* $86 */ "stx $%02x",
/* $87 */ "smb0 $%02x",
/* $88 */ "dey ",
/* $89 */ "bit #$%02x",
/* $8A */ "txa ",
/* $8B */ "nop ",
/* $8C */ "sty $%04x",
/* $8D */ "sta $%04x",
/* $8E */ "stx $%04x",
/* $8F */ "bbs0 $%02x, $%04x",
// $9X
/* $90 */ "bcc $%02x",
/* $91 */ "sta ($%02x),y",
/* $92 */ "sta ($%02x)",
/* $93 */ "nop ",
/* $94 */ "sty $%02x,x",
/* $95 */ "sta $%02x,x",
/* $96 */ "stx $%02x,y",
/* $97 */ "smb1 $%02x",
/* $98 */ "tya ",
/* $99 */ "sta $%04x,y",
/* $9A */ "txs ",
/* $9B */ "nop ",
/* $9C */ "stz $%04x",
/* $9D */ "sta $%04x,x",
/* $9E */ "stz $%04x,x",
/* $9F */ "bbs1 $%02x, $%04x",
// $AX
/* $A0 */ "ldy #$%02x",
/* $A1 */ "lda ($%02x,x)",
/* $A2 */ "ldx #$%02x",
/* $A3 */ "nop ",
/* $A4 */ "ldy $%02x",
/* $A5 */ "lda $%02x",
/* $A6 */ "ldx $%02x",
/* $A7 */ "smb2 $%02x",
/* $A8 */ "tay ",
/* $A9 */ "lda #$%02x",
/* $AA */ "tax ",
/* $AB */ "nop ",
/* $AC */ "ldy $%04x",
/* $AD */ "lda $%04x",
/* $AE */ "ldx $%04x",
/* $AF */ "bbs2 $%02x, $%04x",
// $BX
/* $B0 */ "bcs $%02x",
/* $B1 */ "lda ($%02x),y",
/* $B2 */ "lda ($%02x)",
/* $B3 */ "nop ",
/* $B4 */ "ldy $%02x,x",
/* $B5 */ "lda $%02x,x",
/* $B6 */ "ldx $%02x,y",
/* $B7 */ "smb3 $%02x",
/* $B8 */ "clv ",
/* $B9 */ "lda $%04x,y",
/* $BA */ "tsx ",
/* $BB */ "nop ",
/* $BC */ "ldy $%04x,x",
/* $BD */ "lda $%04x,x",
/* $BE */ "ldx $%04x,y",
/* $BF */ "bbs3 $%02x, $%04x",
// $CX
/* $C0 */ "cpy #$%02x",
/* $C1 */ "cmp ($%02x,x)",
/* $C2 */ "nop ",
/* $C3 */ "nop ",
/* $C4 */ "cpy $%02x",
/* $C5 */ "cmp $%02x",
/* $C6 */ "dec $%02x",
/* $C7 */ "smb4 $%02x",
/* $C8 */ "iny ",
/* $C9 */ "cmp #$%02x",
/* $CA */ "dex ",
/* $CB */ "wai ",
/* $CC */ "cpy $%04x",
/* $CD */ "cmp $%04x",
/* $CE */ "dec $%04x",
/* $CF */ "bbs4 $%02x, $%04x",
// $DX
/* $D0 */ "bne $%02x",
/* $D1 */ "cmp ($%02x),y",
/* $D2 */ "cmp ($%02x)",
/* $D3 */ "nop ",
/* $D4 */ "nop ",
/* $D5 */ "cmp $%02x,x",
/* $D6 */ "dec $%02x,x",
/* $D7 */ "smb5 $%02x",
/* $D8 */ "cld ",
/* $D9 */ "cmp $%04x,y",
/* $DA */ "phx ",
/* $DB */ "dbg ",
/* $DC */ "nop ",
/* $DD */ "cmp $%04x,x",
/* $DE */ "dec $%04x,x",
/* $DF */ "bbs5 $%02x, $%04x",
// $EX
/* $E0 */ "cpx #$%02x",
/* $E1 */ "sbc ($%02x,x)",
/* $E2 */ "nop ",
/* $E3 */ "nop ",
/* $E4 */ "cpx $%02x",
/* $E5 */ "sbc $%02x",
/* $E6 */ "inc $%02x",
/* $E7 */ "smb6 $%02x",
/* $E8 */ "inx ",
/* $E9 */ "sbc #$%02x",
/* $EA */ "nop ",
/* $EB */ "nop ",
/* $EC */ "cpx $%04x",
/* $ED */ "sbc $%04x",
/* $EE */ "inc $%04x",
/* $EF */ "bbs6 $%02x, $%04x",
// $FX
/* $F0 */ "beq $%02x",
/* $F1 */ "sbc ($%02x),y",
/* $F2 */ "sbc ($%02x)",
/* $F3 */ "nop ",
/* $F4 */ "nop ",
/* $F5 */ "sbc $%02x,x",
/* $F6 */ "inc $%02x,x",
/* $F7 */ "smb7 $%02x",
/* $F8 */ "sed ",
/* $F9 */ "sbc $%04x,y",
/* $FA */ "plx ",
/* $FB */ "nop ",
/* $FC */ "nop ",
/* $FD */ "sbc $%04x,x",
/* $FE */ "inc $%04x,x",
/* $FF */ "bbs7 $%02x, $%04x"};
| 3,690 |
1,104 | <reponame>Zorghts/roll20-character-sheets<gh_stars>1000+
{
"html": "palladium_megaverse.html",
"css": "palladium_megaverse.css",
"authors": "<NAME>.",
"roll20userid": "492849",
"preview": "palladium_megaverse.jpg",
"instructions": "This is a basic Palladium Megaverse character sheet and was created out of sheer desperation by the good graces of <NAME>. for the benefit of Roll20's Palladium Magaverse players. This is a no-frills sheet and is essentially a place holder for character's information. Please feel free to update this sheet to make it all that it could be.",
"legacy": true
} | 186 |
1,350 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.peering.implementation;
import com.azure.core.util.Context;
import com.azure.resourcemanager.peering.fluent.models.PeeringServicePrefixInner;
import com.azure.resourcemanager.peering.models.LearnedType;
import com.azure.resourcemanager.peering.models.PeeringServicePrefix;
import com.azure.resourcemanager.peering.models.PeeringServicePrefixEvent;
import com.azure.resourcemanager.peering.models.PrefixValidationState;
import com.azure.resourcemanager.peering.models.ProvisioningState;
import java.util.Collections;
import java.util.List;
public final class PeeringServicePrefixImpl
implements PeeringServicePrefix, PeeringServicePrefix.Definition, PeeringServicePrefix.Update {
private PeeringServicePrefixInner innerObject;
private final com.azure.resourcemanager.peering.PeeringManager serviceManager;
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public String prefix() {
return this.innerModel().prefix();
}
public PrefixValidationState prefixValidationState() {
return this.innerModel().prefixValidationState();
}
public LearnedType learnedType() {
return this.innerModel().learnedType();
}
public String errorMessage() {
return this.innerModel().errorMessage();
}
public List<PeeringServicePrefixEvent> events() {
List<PeeringServicePrefixEvent> inner = this.innerModel().events();
if (inner != null) {
return Collections.unmodifiableList(inner);
} else {
return Collections.emptyList();
}
}
public String peeringServicePrefixKey() {
return this.innerModel().peeringServicePrefixKey();
}
public ProvisioningState provisioningState() {
return this.innerModel().provisioningState();
}
public PeeringServicePrefixInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.peering.PeeringManager manager() {
return this.serviceManager;
}
private String resourceGroupName;
private String peeringServiceName;
private String prefixName;
public PeeringServicePrefixImpl withExistingPeeringService(String resourceGroupName, String peeringServiceName) {
this.resourceGroupName = resourceGroupName;
this.peeringServiceName = peeringServiceName;
return this;
}
public PeeringServicePrefix create() {
this.innerObject =
serviceManager
.serviceClient()
.getPrefixes()
.createOrUpdateWithResponse(
resourceGroupName, peeringServiceName, prefixName, this.innerModel(), Context.NONE)
.getValue();
return this;
}
public PeeringServicePrefix create(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getPrefixes()
.createOrUpdateWithResponse(
resourceGroupName, peeringServiceName, prefixName, this.innerModel(), context)
.getValue();
return this;
}
PeeringServicePrefixImpl(String name, com.azure.resourcemanager.peering.PeeringManager serviceManager) {
this.innerObject = new PeeringServicePrefixInner();
this.serviceManager = serviceManager;
this.prefixName = name;
}
public PeeringServicePrefixImpl update() {
return this;
}
public PeeringServicePrefix apply() {
this.innerObject =
serviceManager
.serviceClient()
.getPrefixes()
.createOrUpdateWithResponse(
resourceGroupName, peeringServiceName, prefixName, this.innerModel(), Context.NONE)
.getValue();
return this;
}
public PeeringServicePrefix apply(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getPrefixes()
.createOrUpdateWithResponse(
resourceGroupName, peeringServiceName, prefixName, this.innerModel(), context)
.getValue();
return this;
}
PeeringServicePrefixImpl(
PeeringServicePrefixInner innerObject, com.azure.resourcemanager.peering.PeeringManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups");
this.peeringServiceName = Utils.getValueFromIdByName(innerObject.id(), "peeringServices");
this.prefixName = Utils.getValueFromIdByName(innerObject.id(), "prefixes");
}
public PeeringServicePrefix refresh() {
String localExpand = null;
this.innerObject =
serviceManager
.serviceClient()
.getPrefixes()
.getWithResponse(resourceGroupName, peeringServiceName, prefixName, localExpand, Context.NONE)
.getValue();
return this;
}
public PeeringServicePrefix refresh(Context context) {
String localExpand = null;
this.innerObject =
serviceManager
.serviceClient()
.getPrefixes()
.getWithResponse(resourceGroupName, peeringServiceName, prefixName, localExpand, context)
.getValue();
return this;
}
public PeeringServicePrefixImpl withPrefix(String prefix) {
this.innerModel().withPrefix(prefix);
return this;
}
public PeeringServicePrefixImpl withPeeringServicePrefixKey(String peeringServicePrefixKey) {
this.innerModel().withPeeringServicePrefixKey(peeringServicePrefixKey);
return this;
}
}
| 2,427 |
367 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SoftTargetCrossEntropy(nn.Module):
def __init__(self):
super(SoftTargetCrossEntropy, self).__init__()
def forward(self, x, target):
N_rep = x.shape[0]
N = target.shape[0]
if not N==N_rep:
target = target.repeat(N_rep//N,1)
loss = torch.sum(-target * F.log_softmax(x, dim=-1), dim=-1)
return loss.mean()
class TokenLabelSoftTargetCrossEntropy(nn.Module):
def __init__(self):
super(TokenLabelSoftTargetCrossEntropy, self).__init__()
def forward(self, x, target):
N_rep = x.shape[0]
N = target.shape[0]
if not N==N_rep:
target = target.repeat(N_rep//N,1)
if len(target.shape)==3 and target.shape[-1]==2:
ground_truth=target[:,:,0]
target = target[:,:,1]
loss = torch.sum(-target * F.log_softmax(x, dim=-1), dim=-1)
return loss.mean()
class TokenLabelCrossEntropy(nn.Module):
"""
Token labeling loss.
"""
def __init__(self, dense_weight=1.0, cls_weight = 1.0, mixup_active=True, classes = 1000, ground_truth = False):
"""
Constructor Token labeling loss.
"""
super(TokenLabelCrossEntropy, self).__init__()
self.CE = SoftTargetCrossEntropy()
self.dense_weight = dense_weight
self.mixup_active = mixup_active
self.classes = classes
self.cls_weight = cls_weight
self.ground_truth = ground_truth
assert dense_weight+cls_weight>0
def forward(self, x, target):
output, aux_output, bb = x
bbx1, bby1, bbx2, bby2 = bb
B,N,C = aux_output.shape
if len(target.shape)==2:
target_cls=target
target_aux = target.repeat(1,N).reshape(B*N,C)
else:
target_cls = target[:,:,1]
if self.ground_truth:
# use ground truth to help correct label.
# rely more on ground truth if target_cls is incorrect.
ground_truth = target[:,:,0]
ratio = (0.9 - 0.4 * (ground_truth.max(-1)[1] == target_cls.max(-1)[1])).unsqueeze(-1)
target_cls = target_cls * ratio + ground_truth * (1 - ratio)
target_aux = target[:,:,2:]
target_aux = target_aux.transpose(1,2).reshape(-1,C)
lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / N)
if lam<1:
target_cls = lam*target_cls + (1-lam)*target_cls.flip(0)
aux_output = aux_output.reshape(-1,C)
loss_cls = self.CE(output, target_cls)
loss_aux = self.CE(aux_output, target_aux)
return self.cls_weight*loss_cls+self.dense_weight* loss_aux
| 1,335 |
2,831 | <gh_stars>1000+
#!/usr/bin/python
# Copyright 2008 <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)
# Tests that properties conditioned on more than one other property work as
# expected.
import BoostBuild
###############################################################################
#
# test_multiple_conditions()
# --------------------------
#
###############################################################################
def test_multiple_conditions():
"""Basic tests for properties conditioned on multiple other properties."""
t = BoostBuild.Tester(["--user-config=", "--ignore-site-config",
"toolset=testToolset"], pass_toolset=False, use_test_config=False)
t.write("testToolset.jam", """\
import feature ;
feature.extend toolset : testToolset ;
rule init ( ) { }
""")
t.write("testToolset.py", """\
from b2.build import feature
feature.extend('toolset', ["testToolset"])
def init ( ): pass
""")
t.write("jamroot.jam", """\
import feature ;
import notfile ;
import toolset ;
feature.feature description : : free incidental ;
feature.feature aaa : 1 0 : incidental ;
feature.feature bbb : 1 0 : incidental ;
feature.feature ccc : 1 0 : incidental ;
rule buildRule ( name : targets ? : properties * )
{
for local description in [ feature.get-values description : $(properties) ]
{
ECHO "description:" /$(description)/ ;
}
}
notfile testTarget1 : @buildRule : :
<description>d
<aaa>0:<description>a0
<aaa>1:<description>a1
<aaa>0,<bbb>0:<description>a0-b0
<aaa>0,<bbb>1:<description>a0-b1
<aaa>1,<bbb>0:<description>a1-b0
<aaa>1,<bbb>1:<description>a1-b1
<aaa>0,<bbb>0,<ccc>0:<description>a0-b0-c0
<aaa>0,<bbb>0,<ccc>1:<description>a0-b0-c1
<aaa>0,<bbb>1,<ccc>1:<description>a0-b1-c1
<aaa>1,<bbb>0,<ccc>1:<description>a1-b0-c1
<aaa>1,<bbb>1,<ccc>0:<description>a1-b1-c0
<aaa>1,<bbb>1,<ccc>1:<description>a1-b1-c1 ;
""")
t.run_build_system(["aaa=1", "bbb=1", "ccc=1"])
t.expect_output_lines("description: /d/" )
t.expect_output_lines("description: /a0/" , False)
t.expect_output_lines("description: /a1/" )
t.expect_output_lines("description: /a0-b0/" , False)
t.expect_output_lines("description: /a0-b1/" , False)
t.expect_output_lines("description: /a1-b0/" , False)
t.expect_output_lines("description: /a1-b1/" )
t.expect_output_lines("description: /a0-b0-c0/", False)
t.expect_output_lines("description: /a0-b0-c1/", False)
t.expect_output_lines("description: /a0-b1-c1/", False)
t.expect_output_lines("description: /a1-b0-c1/", False)
t.expect_output_lines("description: /a1-b1-c0/", False)
t.expect_output_lines("description: /a1-b1-c1/" )
t.run_build_system(["aaa=0", "bbb=0", "ccc=1"])
t.expect_output_lines("description: /d/" )
t.expect_output_lines("description: /a0/" )
t.expect_output_lines("description: /a1/" , False)
t.expect_output_lines("description: /a0-b0/" )
t.expect_output_lines("description: /a0-b1/" , False)
t.expect_output_lines("description: /a1-b0/" , False)
t.expect_output_lines("description: /a1-b1/" , False)
t.expect_output_lines("description: /a0-b0-c0/", False)
t.expect_output_lines("description: /a0-b0-c1/" )
t.expect_output_lines("description: /a0-b1-c1/", False)
t.expect_output_lines("description: /a1-b0-c1/", False)
t.expect_output_lines("description: /a1-b1-c0/", False)
t.expect_output_lines("description: /a1-b1-c1/", False)
t.run_build_system(["aaa=0", "bbb=0", "ccc=0"])
t.expect_output_lines("description: /d/" )
t.expect_output_lines("description: /a0/" )
t.expect_output_lines("description: /a1/" , False)
t.expect_output_lines("description: /a0-b0/" )
t.expect_output_lines("description: /a0-b1/" , False)
t.expect_output_lines("description: /a1-b0/" , False)
t.expect_output_lines("description: /a1-b1/" , False)
t.expect_output_lines("description: /a0-b0-c0/" )
t.expect_output_lines("description: /a0-b0-c1/", False)
t.expect_output_lines("description: /a0-b1-c1/", False)
t.expect_output_lines("description: /a1-b0-c1/", False)
t.expect_output_lines("description: /a1-b1-c0/", False)
t.expect_output_lines("description: /a1-b1-c1/", False)
t.cleanup()
###############################################################################
#
# test_multiple_conditions_with_toolset_version()
# -----------------------------------------------
#
###############################################################################
def test_multiple_conditions_with_toolset_version():
"""
Regression tests for properties conditioned on the toolset version
subfeature and some additional properties.
"""
toolset = "testToolset" ;
t = BoostBuild.Tester(["--user-config=", "--ignore-site-config"],
pass_toolset=False, use_test_config=False)
t.write(toolset + ".jam", """\
import feature ;
feature.extend toolset : %(toolset)s ;
feature.subfeature toolset %(toolset)s : version : 0 1 ;
rule init ( version ? ) { }
""" % {"toolset": toolset})
t.write("testToolset.py", """\
from b2.build import feature
feature.extend('toolset', ["%(toolset)s"])
feature.subfeature('toolset', "%(toolset)s", "version", ['0','1'])
def init ( version ): pass
""" % {"toolset": toolset})
t.write("jamroot.jam", """\
import feature ;
import notfile ;
import toolset ;
toolset.using testToolset ;
feature.feature description : : free incidental ;
feature.feature aaa : 0 1 : incidental ;
feature.feature bbb : 0 1 : incidental ;
feature.feature ccc : 0 1 : incidental ;
rule buildRule ( name : targets ? : properties * )
{
local ttt = [ feature.get-values toolset : $(properties) ] ;
local vvv = [ feature.get-values toolset-testToolset:version : $(properties) ] ;
local aaa = [ feature.get-values aaa : $(properties) ] ;
local bbb = [ feature.get-values bbb : $(properties) ] ;
local ccc = [ feature.get-values ccc : $(properties) ] ;
ECHO "toolset:" /$(ttt)/ "version:" /$(vvv)/ "aaa/bbb/ccc:" /$(aaa)/$(bbb)/$(ccc)/ ;
for local description in [ feature.get-values description : $(properties) ]
{
ECHO "description:" /$(description)/ ;
}
}
notfile testTarget1 : @buildRule : :
<toolset>testToolset,<aaa>0:<description>t-a0
<toolset>testToolset,<aaa>1:<description>t-a1
<toolset>testToolset-0,<aaa>0:<description>t0-a0
<toolset>testToolset-0,<aaa>1:<description>t0-a1
<toolset>testToolset-1,<aaa>0:<description>t1-a0
<toolset>testToolset-1,<aaa>1:<description>t1-a1
<toolset>testToolset,<aaa>0,<bbb>0:<description>t-a0-b0
<toolset>testToolset,<aaa>0,<bbb>1:<description>t-a0-b1
<toolset>testToolset,<aaa>1,<bbb>0:<description>t-a1-b0
<toolset>testToolset,<aaa>1,<bbb>1:<description>t-a1-b1
<aaa>0,<toolset>testToolset,<bbb>0:<description>a0-t-b0
<aaa>0,<toolset>testToolset,<bbb>1:<description>a0-t-b1
<aaa>1,<toolset>testToolset,<bbb>0:<description>a1-t-b0
<aaa>1,<toolset>testToolset,<bbb>1:<description>a1-t-b1
<aaa>0,<bbb>0,<toolset>testToolset:<description>a0-b0-t
<aaa>0,<bbb>1,<toolset>testToolset:<description>a0-b1-t
<aaa>1,<bbb>0,<toolset>testToolset:<description>a1-b0-t
<aaa>1,<bbb>1,<toolset>testToolset:<description>a1-b1-t
<toolset>testToolset-0,<aaa>0,<bbb>0:<description>t0-a0-b0
<toolset>testToolset-0,<aaa>0,<bbb>1:<description>t0-a0-b1
<toolset>testToolset-0,<aaa>1,<bbb>0:<description>t0-a1-b0
<toolset>testToolset-0,<aaa>1,<bbb>1:<description>t0-a1-b1
<toolset>testToolset-1,<aaa>0,<bbb>0:<description>t1-a0-b0
<toolset>testToolset-1,<aaa>0,<bbb>1:<description>t1-a0-b1
<toolset>testToolset-1,<aaa>1,<bbb>0:<description>t1-a1-b0
<toolset>testToolset-1,<aaa>1,<bbb>1:<description>t1-a1-b1
<aaa>0,<toolset>testToolset-1,<bbb>0:<description>a0-t1-b0
<aaa>0,<toolset>testToolset-1,<bbb>1:<description>a0-t1-b1
<aaa>1,<toolset>testToolset-0,<bbb>0:<description>a1-t0-b0
<aaa>1,<toolset>testToolset-0,<bbb>1:<description>a1-t0-b1
<bbb>0,<aaa>1,<toolset>testToolset-0:<description>b0-a1-t0
<bbb>0,<aaa>0,<toolset>testToolset-1:<description>b0-a0-t1
<bbb>0,<aaa>1,<toolset>testToolset-1:<description>b0-a1-t1
<bbb>1,<aaa>0,<toolset>testToolset-1:<description>b1-a0-t1
<bbb>1,<aaa>1,<toolset>testToolset-0:<description>b1-a1-t0
<bbb>1,<aaa>1,<toolset>testToolset-1:<description>b1-a1-t1 ;
""")
t.run_build_system(["aaa=1", "bbb=1", "ccc=1", "toolset=%s-0" % toolset])
t.expect_output_lines("description: /t-a0/" , False)
t.expect_output_lines("description: /t-a1/" )
t.expect_output_lines("description: /t0-a0/" , False)
t.expect_output_lines("description: /t0-a1/" )
t.expect_output_lines("description: /t1-a0/" , False)
t.expect_output_lines("description: /t1-a1/" , False)
t.expect_output_lines("description: /t-a0-b0/" , False)
t.expect_output_lines("description: /t-a0-b1/" , False)
t.expect_output_lines("description: /t-a1-b0/" , False)
t.expect_output_lines("description: /t-a1-b1/" )
t.expect_output_lines("description: /a0-t-b0/" , False)
t.expect_output_lines("description: /a0-t-b1/" , False)
t.expect_output_lines("description: /a1-t-b0/" , False)
t.expect_output_lines("description: /a1-t-b1/" )
t.expect_output_lines("description: /a0-b0-t/" , False)
t.expect_output_lines("description: /a0-b1-t/" , False)
t.expect_output_lines("description: /a1-b0-t/" , False)
t.expect_output_lines("description: /a1-b1-t/" )
t.expect_output_lines("description: /t0-a0-b0/", False)
t.expect_output_lines("description: /t0-a0-b1/", False)
t.expect_output_lines("description: /t0-a1-b0/", False)
t.expect_output_lines("description: /t0-a1-b1/" )
t.expect_output_lines("description: /t1-a0-b0/", False)
t.expect_output_lines("description: /t1-a0-b1/", False)
t.expect_output_lines("description: /t1-a1-b0/", False)
t.expect_output_lines("description: /t1-a1-b1/", False)
t.expect_output_lines("description: /a0-t1-b0/", False)
t.expect_output_lines("description: /a0-t1-b1/", False)
t.expect_output_lines("description: /a1-t0-b0/", False)
t.expect_output_lines("description: /a1-t0-b1/" )
t.expect_output_lines("description: /b0-a1-t0/", False)
t.expect_output_lines("description: /b0-a0-t1/", False)
t.expect_output_lines("description: /b0-a1-t1/", False)
t.expect_output_lines("description: /b1-a0-t1/", False)
t.expect_output_lines("description: /b1-a1-t0/" )
t.expect_output_lines("description: /b1-a1-t1/", False)
t.run_build_system(["aaa=1", "bbb=1", "ccc=1", "toolset=%s-1" % toolset])
t.expect_output_lines("description: /t-a0/" , False)
t.expect_output_lines("description: /t-a1/" )
t.expect_output_lines("description: /t0-a0/" , False)
t.expect_output_lines("description: /t0-a1/" , False)
t.expect_output_lines("description: /t1-a0/" , False)
t.expect_output_lines("description: /t1-a1/" )
t.expect_output_lines("description: /t-a0-b0/" , False)
t.expect_output_lines("description: /t-a0-b1/" , False)
t.expect_output_lines("description: /t-a1-b0/" , False)
t.expect_output_lines("description: /t-a1-b1/" )
t.expect_output_lines("description: /a0-t-b0/" , False)
t.expect_output_lines("description: /a0-t-b1/" , False)
t.expect_output_lines("description: /a1-t-b0/" , False)
t.expect_output_lines("description: /a1-t-b1/" )
t.expect_output_lines("description: /a0-b0-t/" , False)
t.expect_output_lines("description: /a0-b1-t/" , False)
t.expect_output_lines("description: /a1-b0-t/" , False)
t.expect_output_lines("description: /a1-b1-t/" )
t.expect_output_lines("description: /t0-a0-b0/", False)
t.expect_output_lines("description: /t0-a0-b1/", False)
t.expect_output_lines("description: /t0-a1-b0/", False)
t.expect_output_lines("description: /t0-a1-b1/", False)
t.expect_output_lines("description: /t1-a0-b0/", False)
t.expect_output_lines("description: /t1-a0-b1/", False)
t.expect_output_lines("description: /t1-a1-b0/", False)
t.expect_output_lines("description: /t1-a1-b1/" )
t.expect_output_lines("description: /a0-t1-b0/", False)
t.expect_output_lines("description: /a0-t1-b1/", False)
t.expect_output_lines("description: /a1-t0-b0/", False)
t.expect_output_lines("description: /a1-t0-b1/", False)
t.expect_output_lines("description: /b0-a1-t0/", False)
t.expect_output_lines("description: /b0-a0-t1/", False)
t.expect_output_lines("description: /b0-a1-t1/", False)
t.expect_output_lines("description: /b1-a0-t1/", False)
t.expect_output_lines("description: /b1-a1-t0/", False)
t.expect_output_lines("description: /b1-a1-t1/" )
t.cleanup()
###############################################################################
#
# main()
# ------
#
###############################################################################
test_multiple_conditions()
test_multiple_conditions_with_toolset_version()
| 6,143 |
879 | <filename>header/src/main/java/org/zstack/header/volume/VolumeState.java
package org.zstack.header.volume;
public enum VolumeState {
Enabled,
Disabled
}
| 56 |
663 | <reponame>doctorpangloss/gogradle<gh_stars>100-1000
/*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.github.blindpirate.gogradle.core.dependency.produce;
import com.github.blindpirate.gogradle.core.GolangPackage;
import com.github.blindpirate.gogradle.core.UnrecognizedGolangPackage;
import com.github.blindpirate.gogradle.core.VcsGolangPackage;
import com.github.blindpirate.gogradle.core.dependency.GolangDependency;
import com.github.blindpirate.gogradle.core.dependency.GolangDependencySet;
import com.github.blindpirate.gogradle.core.dependency.ResolvedDependency;
import com.github.blindpirate.gogradle.core.dependency.VendorResolvedDependency;
import com.github.blindpirate.gogradle.core.pack.PackagePathResolver;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import static com.github.blindpirate.gogradle.core.dependency.produce.VendorDependencyFactory.VENDOR_DIRECTORY;
import static com.github.blindpirate.gogradle.util.IOUtils.isValidDirectory;
import static com.github.blindpirate.gogradle.util.IOUtils.safeList;
import static com.github.blindpirate.gogradle.util.StringUtils.toUnixString;
/**
* Analyze vendor directory to generate dependencies.
*/
public class SecondPassVendorDirectoryVisitor extends SimpleFileVisitor<Path> {
private static final Logger LOGGER = Logging.getLogger(SecondPassVendorDirectoryVisitor.class);
private ResolvedDependency parent;
private PackagePathResolver resolver;
private Path parentVendor;
private GolangDependencySet dependencies = new GolangDependencySet();
public GolangDependencySet getDependencies() {
return dependencies;
}
public SecondPassVendorDirectoryVisitor(
ResolvedDependency parent,
Path parentVendor,
PackagePathResolver resolver) {
this.parent = parent;
this.resolver = resolver;
this.parentVendor = parentVendor;
}
@Override
public FileVisitResult preVisitDirectory(Path currentPath, BasicFileAttributes attrs)
throws IOException {
if (currentPath == parentVendor) {
return FileVisitResult.CONTINUE;
}
// relative path, i.e "github.com/a/b"
String packagePath = toUnixString(parentVendor.relativize(currentPath));
GolangPackage golangPackage = resolver.produce(packagePath).get();
if (golangPackage instanceof UnrecognizedGolangPackage) {
return visitUnrecognizedVendorPackage(packagePath, currentPath);
} else if (golangPackage instanceof VcsGolangPackage) {
return visitRepoRoot(packagePath, currentPath);
} else {
LOGGER.debug("Cannot produce package with path {}, continue.", packagePath);
return FileVisitResult.CONTINUE;
}
}
private FileVisitResult visitRepoRoot(String packagePath, Path currentPath) {
LOGGER.debug("Produce recognized package {}.", packagePath);
dependencies.add(createDependency(packagePath, currentPath));
return FileVisitResult.SKIP_SUBTREE;
}
private FileVisitResult visitUnrecognizedVendorPackage(String packagePath, Path currentPath) {
// if currentPath is a empty directory, anyDotGoFileOrVendorDirExist() return false, then nothing happens
if (anyDotGoFileOrVendorDirExist(currentPath)) {
LOGGER.debug("Produce unrecognized package {}.", packagePath);
dependencies.add(createDependency(packagePath, currentPath));
return FileVisitResult.SKIP_SUBTREE;
} else {
LOGGER.debug("Cannot recognize package {}, continue.", packagePath);
return FileVisitResult.CONTINUE;
}
}
private boolean anyDotGoFileOrVendorDirExist(Path currentPath) {
return isValidDirectory(currentPath.resolve(VENDOR_DIRECTORY).toFile())
|| safeList(currentPath.toFile()).stream().anyMatch(fileName -> fileName.endsWith(".go"));
}
private GolangDependency createDependency(String packagePath, Path rootPath) {
return VendorResolvedDependency.fromParent(packagePath, parent, rootPath.toFile());
}
}
| 1,748 |
337 | <gh_stars>100-1000
#pragma once
#include "../base/PathConfigBase.h"
#include "Dynmon_dp.h"
#include "MetricConfig.h"
class DataplaneConfig;
using namespace polycube::service::model;
static const std::string DEFAULT_PATH_NAME = "Default path config";
static const std::string DEFAULT_PATH_CODE = dynmon_code;
class PathConfig : public PathConfigBase {
public:
explicit PathConfig(DataplaneConfig &parent);
PathConfig(DataplaneConfig &parent, const PathConfigJsonObject &conf);
~PathConfig() = default;
/**
* Configuration name
*/
std::string getName() override;
void setName(const std::string &value) override;
/**
* Ingress eBPF source code
*/
std::string getCode() override;
void setCode(const std::string &);
/**
* Exported Metric
*/
std::shared_ptr<MetricConfig> getMetricConfig(const std::string &name) override;
std::vector<std::shared_ptr<MetricConfig>> getMetricConfigsList() override;
void addMetricConfig(const std::string &name, const MetricConfigJsonObject &conf) override;
void addMetricConfigsList(const std::vector<MetricConfigJsonObject> &conf) override;
void replaceMetricConfig(const std::string &name, const MetricConfigJsonObject &conf) override;
void delMetricConfig(const std::string &name) override;
void delMetricConfigsList() override;
private:
std::string m_name;
std::string m_code;
std::vector<std::shared_ptr<MetricConfig>> m_metricConfigs;
};
| 465 |
680 | //
// XYBarChart.h
// XYChart
//
// Created by Daniel on 14-7-24.
// Copyright (c) 2014年 uyiuyao. All rights reserved.
//
#import "XYChartProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@class XYChart;
@interface XYBarChart : UIView<XYChartContainer>
@property (nonatomic, weak, readonly) XYChart *chartView;
@end
NS_ASSUME_NONNULL_END
| 134 |
521 | #!/usr/bin/env python3
from lib.tcpmulticonnection import TCPMultiConnection
from lib.config import Config
from lib.args import Args
from gi.repository import Gst
import logging
import gi
gi.require_version('GstController', '1.0')
class AVPreviewOutput(TCPMultiConnection):
def __init__(self, source, port, use_audio_mix=False, audio_blinded=False):
# create logging interface
self.log = logging.getLogger('AVPreviewOutput[{}]'.format(source))
# initialize super
super().__init__(port)
# remember things
self.source = source
# open bin
self.bin = "" if Args.no_bins else """
bin.(
name=AVPreviewOutput-{source}
""".format(source=self.source)
# video pipeline
self.bin += """
video-{source}.
! {vcaps}
! queue
max-size-time=3000000000
name=queue-preview-video-{source}
{vpipeline}
! queue
max-size-time=3000000000
name=queue-mux-preview-{source}
! mux-preview-{source}.
""".format(source=self.source,
vpipeline=self.construct_video_pipeline(),
vcaps=Config.getVideoCaps()
)
# audio pipeline
if use_audio_mix or source in Config.getAudioSources(internal=True):
self.bin += """
{use_audio}audio-{audio_source}{audio_blinded}.
! queue
max-size-time=3000000000
name=queue-preview-audio-{source}
! audioconvert
! queue
max-size-time=3000000000
name=queue-mux-preview-audio-{source}
! mux-preview-{source}.
""".format(source=self.source,
use_audio="" if use_audio_mix else "source-",
audio_source="mix" if use_audio_mix else self.source,
audio_blinded="-blinded" if audio_blinded else ""
)
# playout pipeline
self.bin += """
matroskamux
name=mux-preview-{source}
streamable=true
writing-app=Voctomix-AVPreviewOutput
! queue
max-size-time=3000000000
name=queue-fd-preview-{source}
! multifdsink
blocksize=1048576
buffers-max=500
sync-method=next-keyframe
name=fd-preview-{source}
""".format(source=self.source)
# close bin
self.bin += "" if Args.no_bins else "\n)\n"
def audio_channels(self):
return Config.getNumAudioStreams()
def video_channels(self):
return 1
def is_input(self):
return False
def __str__(self):
return 'AVPreviewOutput[{}]'.format(self.source)
def construct_video_pipeline(self):
if Config.getPreviewVaapi():
return self.construct_vaapi_video_pipeline()
else:
return self.construct_native_video_pipeline()
def construct_vaapi_video_pipeline(self):
# https://blogs.igalia.com/vjaquez/2016/04/06/gstreamer-vaapi-1-8-the-codec-split/
if Gst.version() < (1, 8):
vaapi_encoders = {
'h264': 'vaapiencode_h264',
'jpeg': 'vaapiencode_jpeg',
'mpeg2': 'vaapiencode_mpeg2',
}
else:
vaapi_encoders = {
'h264': 'vaapih264enc',
'jpeg': 'vaapijpegenc',
'mpeg2': 'vaapimpeg2enc',
}
vaapi_encoder_options = {
'h264': """rate-control=cqp
init-qp=10
max-bframes=0
keyframe-period=60""",
'jpeg': """quality=90
keyframe-period=0""",
'mpeg2': "keyframe-period=60",
}
# prepare selectors
size = Config.getPreviewResolution()
framerate = Config.getPreviewFramerate()
vaapi = Config.getPreviewVaapi()
denoise = Config.getDenoiseVaapi()
scale_method = Config.getScaleMethodVaapi()
# generate pipeline
# we can also force a video format here (format=I420) but this breaks scalling at least on Intel HD3000 therefore it currently removed
return """ ! capsfilter
caps=video/x-raw,interlace-mode=progressive
! vaapipostproc
! video/x-raw,width={width},height={height},framerate={n}/{d},deinterlace-mode={imode},deinterlace-method=motion-adaptive,denoise={denoise},scale-method={scale_method}
! {encoder}
{options}""".format(imode='interlaced' if Config.getDeinterlacePreviews() else 'disabled',
width=size[0],
height=size[1],
encoder=vaapi_encoders[vaapi],
options=vaapi_encoder_options[vaapi],
n=framerate[0],
d=framerate[1],
denoise=denoise,
scale_method=scale_method,
)
def construct_native_video_pipeline(self):
# maybe add deinterlacer
if Config.getDeinterlacePreviews():
pipeline = """ ! deinterlace
mode=interlaced
"""
else:
pipeline = ""
# build rest of the pipeline
pipeline += """ ! videorate
! videoscale
! {vcaps}
! jpegenc
quality = 90""".format(vcaps=Config.getPreviewCaps())
return pipeline
def attach(self, pipeline):
self.pipeline = pipeline
def on_accepted(self, conn, addr):
self.log.debug('Adding fd %u to multifdsink', conn.fileno())
# find fdsink and emit 'add'
fdsink = self.pipeline.get_by_name("fd-preview-{}".format(self.source))
fdsink.emit('add', conn.fileno())
# catch disconnect
def on_disconnect(multifdsink, fileno):
if fileno == conn.fileno():
self.log.debug('fd %u removed from multifdsink', fileno)
self.close_connection(conn)
fdsink.connect('client-fd-removed', on_disconnect)
# catch client-removed
def on_client_removed(multifdsink, fileno, status):
# GST_CLIENT_STATUS_SLOW = 3,
if fileno == conn.fileno() and status == 3:
self.log.warning('about to remove fd %u from multifdsink '
'because it is too slow!', fileno)
fdsink.connect('client-removed', on_client_removed)
| 4,083 |
1,694 | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@class NSData, NSMutableDictionary, NSString;
@interface WWKBaseObject : NSObject
{
NSString *_bundleID;
NSString *_bundleName;
unsigned long long _sequence;
}
+ (id)deserializeWithData:(id)arg1;
@property(nonatomic) unsigned long long sequence; // @synthesize sequence=_sequence;
@property(copy, nonatomic) NSString *bundleName; // @synthesize bundleName=_bundleName;
@property(copy, nonatomic) NSString *bundleID; // @synthesize bundleID=_bundleID;
- (void).cxx_destruct;
- (_Bool)deserializeWithDictionary:(id)arg1;
@property(readonly, nonatomic) NSMutableDictionary *serializedDict;
@property(readonly, nonatomic) NSData *serializedData;
- (id)init;
@end
| 322 |
1,639 | <filename>Graph Theory/Gomory Hu Tree of Planar Graph.cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
const int mod = 998244353;
struct EDGE {
int from, to, rev;
long long w;
} E[N * 4];
int n, m, bel[N * 4];
bool vis[N * 4];
vector<int> G[N];
vector<vector<int> > plr;
set<pair<long long, int> > st;
vector<pair<pair<int, int>, long long> > tr;
int fa[N], sz[N];
int Find(int x) {
return x == fa[x] ? x : fa[x] = Find(fa[x]);
}
// credit: Misaka-Mikoto-
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d%d%lld", &E[i * 2].from, &E[i * 2].to, &E[i * 2].w);
E[i * 2].from--, E[i * 2].to--;
E[i * 2 + 1] = E[i * 2];
swap(E[i * 2 + 1].from, E[i * 2 + 1].to);
}
for (int i = 0; i < m * 2; i++) {
G[E[i].from].push_back(i);
if ((E[i].from + 1) % n == E[i].to) vis[i] = true;
else vis[i] = false;
}
for (int i = 0; i < n; i++) {
sort(G[i].begin(), G[i].end(), [&](int e1, int e2) {
return (E[e1].to - i + n) % n < (E[e2].to - i + n) % n;
});
for (int j = 0; j < (int)G[i].size(); j++) {
int e = G[i][j];
E[e ^ 1].rev = j;
}
}
for (int i = 0; i < m * 2; i++) if (!vis[i]) {
int e = i;
vector<int> ve;
while (!vis[e]) {
ve.push_back(e);
vis[e] = true;
int v = E[e].to;
int ne = G[v][(E[e].rev + 1) % G[v].size()];
e = ne;
}
plr.push_back(ve);
for (int x : ve) bel[x] = plr.size() - 1;
}
for (int i = 0; i < m * 2; i++) {
if ((E[i].from + 1) % n == E[i].to) vis[i] = true;
else vis[i] = false;
}
for (int i = 0; i < m; i++) {
int x = E[i * 2].from, y = E[i * 2].to;
if ((x + 1) % n == y || (y + 1) % n == x) {
st.insert(make_pair(E[i * 2].w, i));
}
}
while (!st.empty()) {
int e = st.begin() -> second;
st.erase(st.begin());
if (vis[e * 2] && vis[e * 2 + 1]) {
tr.push_back(make_pair(make_pair(E[e * 2].from, E[e * 2].to), E[e * 2].w));
continue;
}
if (!vis[e * 2]) e *= 2;
else e = e * 2 + 1;
int b = bel[e];
for (int x : plr[b]) {
vis[x] = true;
if (x == e) continue;
st.erase(make_pair(E[x].w, x >> 1));
E[x].w += E[e].w;
E[x ^ 1].w += E[e].w;
st.insert(make_pair(E[x].w, x >> 1));
}
}
reverse(tr.begin(), tr.end()); // edges of GHT
int ans = 0;
for (int i = 0; i < n; i++) fa[i] = i, sz[i] = 1;
for (int i = 0; i < n - 1; i++) {
int x = Find(tr[i].first.first), y = Find(tr[i].first.second), w = tr[i].second % mod;
ans = (ans + 1ll * sz[x] * sz[y] % mod * w) % mod;
if (sz[x] < sz[y]) swap(x, y);
fa[y] = x;
sz[x] += sz[y];
}
printf("%d\n", ans);
return 0;
}
// https://codeforces.com/gym/102471/submission/71744464 | 1,554 |
521 | /** @file
String routines implementation
Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _EFI_STRING_FUNCS_H
#define _EFI_STRING_FUNCS_H
#include <stdio.h>
#include <stdlib.h>
#include <Common/UefiBaseTypes.h>
//
// Common data structures
//
typedef struct {
UINTN Count;
//
// Actually this array can be 0 or more items (based on Count)
//
CHAR8* Strings[1];
} STRING_LIST;
//
// Functions declarations
//
CHAR8*
CloneString (
IN CHAR8 *String
)
;
/**
Routine Description:
Allocates a new string and copies 'String' to clone it
Arguments:
String The string to clone
Returns:
CHAR8* - NULL if there are not enough resources
**/
EFI_STATUS
StripInfDscStringInPlace (
IN CHAR8 *String
)
;
/**
Routine Description:
Remove all comments, leading and trailing whitespace from the string.
Arguments:
Strin The string to 'strip'
Returns:
EFI_STATUS
**/
STRING_LIST*
SplitStringByWhitespace (
IN CHAR8 *String
)
;
/**
Routine Description:
Creates and returns a 'split' STRING_LIST by splitting the string
on whitespace boundaries.
Arguments:
String The string to 'split'
Returns:
EFI_STATUS
**/
STRING_LIST*
NewStringList (
)
;
/**
Routine Description:
Creates a new STRING_LIST with 0 strings.
Returns:
STRING_LIST* - Null if there is not enough resources to create the object.
**/
EFI_STATUS
AppendCopyOfStringToList (
IN OUT STRING_LIST **StringList,
IN CHAR8 *String
)
;
/**
Routine Description:
Adds String to StringList. A new copy of String is made before it is
added to StringList.
Returns:
EFI_STATUS
**/
EFI_STATUS
RemoveLastStringFromList (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Removes the last string from StringList and frees the memory associated
with it.
Arguments:
StringList The string list to remove the string from
Returns:
EFI_STATUS
**/
STRING_LIST*
AllocateStringListStruct (
IN UINTN StringCount
)
;
/**
Routine Description:
Allocates a STRING_LIST structure that can store StringCount strings.
Arguments:
StringCount The number of strings that need to be stored
Returns:
EFI_STATUS
**/
VOID
FreeStringList (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Frees all memory associated with StringList.
Arguments:
StringList The string list to free
Returns:
EFI_STATUS
**/
CHAR8*
StringListToString (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Generates a string that represents the STRING_LIST
Arguments:
StringList The string list to convert to a string
Returns:
CHAR8* - The string list represented with a single string. The returned
string must be freed by the caller.
**/
VOID
PrintStringList (
IN STRING_LIST *StringList
)
;
/**
Routine Description:
Prints out the string list
Arguments:
StringList The string list to print
**/
#endif
| 1,217 |
4,985 | /*
* Copyright 2008 CoreMedia AG, Hamburg
*
* 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.coremedia.iso.boxes.vodafone;
import com.coremedia.iso.IsoTypeReader;
import com.coremedia.iso.Utf8;
import com.googlecode.mp4parser.AbstractFullBox;
import java.nio.ByteBuffer;
/**
* A box in the {@link com.coremedia.iso.boxes.UserDataBox} containing information about the lyric location.
* Invented by Vodafone.
*/
public class LyricsUriBox extends AbstractFullBox {
public static final String TYPE = "lrcu";
private String lyricsUri;
public LyricsUriBox() {
super(TYPE);
}
public String getLyricsUri() {
return lyricsUri;
}
public void setLyricsUri(String lyricsUri) {
this.lyricsUri = lyricsUri;
}
protected long getContentSize() {
return Utf8.utf8StringLengthInBytes(lyricsUri) + 5;
}
@Override
public void _parseDetails(ByteBuffer content) {
parseVersionAndFlags(content);
lyricsUri = IsoTypeReader.readString(content);
}
@Override
protected void getContent(ByteBuffer byteBuffer) {
writeVersionAndFlags(byteBuffer);
byteBuffer.put(Utf8.convert(lyricsUri));
byteBuffer.put((byte) 0);
}
public String toString() {
return "LyricsUriBox[lyricsUri=" + getLyricsUri() + "]";
}
}
| 659 |
2,209 | #ifndef __PYTHON_H__
#define __PYTHON_H__
/**
* Stub out the bits of python on which which parser.c depends.
*
*/
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdbool.h>
//#include <stddef.h>
#include <unistd.h>
// XXX: Remove instances of these later
#define PyAPI_FUNC(x) extern x
#define PyAPI_DATA(x) extern x
#define PY_SIZE_MAX SSIZE_MAX
// Define this, because it's true.
#define PGEN
// Types
typedef ssize_t Py_ssize_t;
extern int Py_VerboseFlag;
extern int Py_DebugFlag;
void Py_FatalError(const char *err);
void *PyMem_MALLOC(size_t size);
void PyMem_FREE(void *ptr);
void *PyMem_REALLOC(void * ptr, size_t size);
void *PyObject_MALLOC(size_t size);
void *PyObject_REALLOC(void * ptr, size_t size);
void PyObject_FREE(void *ptr);
void PyOS_snprintf(char *buf, size_t n, const char *fmt, ...);
void PySys_WriteStdout(const char *format, ...);
void PySys_WriteStderr(const char *format, ...);
// This copied straight from the headers.
/* Argument must be a char or an int in [-128, 127] or [0, 255]. */
#define Py_CHARMASK(c) ((unsigned char)((c) & 0xff))
// not sure about this one
#if USE_PY_CTYPE
#define Py_ISALPHA(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALPHA)
#else
#define Py_ISALPHA(c) isalpha(c)
#define Py_ISALNUM(c) isalnum(c)
#endif
#endif
| 536 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Little",
"definitions": [
"To a small extent.",
"Only to a small extent; not much or often (used for emphasis)",
"Hardly or not at all."
],
"parts-of-speech": "Adverb"
} | 113 |
559 | /**
* Copyright (c) 2016-2017 Netflix, Inc. 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.
*/
#ifndef SRC_RANGEEXCEPTION_H_
#define SRC_RANGEEXCEPTION_H_
#include <Exception.h>
namespace netflix
{
namespace msl
{
/**
* Thrown if there is a range error.
*/
class IllegalStateException : public Exception
{
public:
/**
* Construct a new MSL range exception with the specified detail message.
*
* @param message the detail message.
*/
inline IllegalStateException(const std::string& details) : Exception(details) {}
/**
* Construct a new MSL range exception with the specified detail message
* and cause.
*
* @param message the detail message.
* @param cause the cause.
*/
inline IllegalStateException(const std::string& details, const IException& cause)
: Exception(details, cause) {}
virtual inline ~IllegalStateException() throw() {}
DECLARE_EXCEPTION_CLONE(IllegalStateException);
private:
IllegalStateException(); // not implemented
};
} /* namespace msl */
} /* namespace netflix */
#endif /* SRC_RANGEEXCEPTION_H_ */
| 511 |
1,538 | <reponame>gabriel-doriath-dohler/lean4<filename>stage0/stdlib/Lean/Elab/PreDefinition/WF/Main.c
// Lean compiler output
// Module: Lean.Elab.PreDefinition.WF.Main
// Imports: Init Lean.Elab.PreDefinition.Basic Lean.Elab.PreDefinition.WF.TerminationHint Lean.Elab.PreDefinition.WF.PackDomain Lean.Elab.PreDefinition.WF.PackMutual Lean.Elab.PreDefinition.WF.Rel Lean.Elab.PreDefinition.WF.Fix
#include <lean/lean.h>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wunused-label"
#elif defined(__GNUC__) && !defined(__CLANG__)
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-label"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
#ifdef __cplusplus
extern "C" {
#endif
lean_object* lean_array_set(lean_object*, lean_object*, lean_object*);
size_t lean_usize_add(size_t, size_t);
lean_object* l_Lean_registerTraceClass(lean_object*, lean_object*);
lean_object* l_Lean_stringToMessageData(lean_object*);
lean_object* l_Lean_Elab_addAsAxiom(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_mkSort(lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6;
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12;
lean_object* lean_name_mk_string(lean_object*, lean_object*);
lean_object* lean_array_uget(lean_object*, size_t);
LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Elab_wfRecursion___spec__1(lean_object*, size_t, size_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__11;
lean_object* lean_st_ref_get(lean_object*, lean_object*);
static lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___closed__1;
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__5;
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Elab_wfRecursion___closed__1;
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__10;
lean_object* lean_array_get_size(lean_object*);
lean_object* lean_string_append(lean_object*, lean_object*);
lean_object* l_Lean_Elab_WF_packMutual(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Elab_Term_instInhabitedTermElabM(lean_object*);
uint8_t lean_usize_dec_lt(size_t, size_t);
LEAN_EXPORT lean_object* l_Lean_Elab_wfRecursion___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
extern lean_object* l_Lean_levelZero;
lean_object* lean_nat_add(lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__7;
static lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__2;
uint8_t lean_nat_dec_eq(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* lean_nat_sub(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Expr_constLevels_x21(lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__3;
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___closed__1;
lean_object* l_Lean_Elab_WF_mkUnaryArg_go___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* lean_array_get(lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Meta_mkLambdaFVars(lean_object*, lean_object*, uint8_t, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_PreDefinition_WF_Main___hyg_881_(lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10;
extern lean_object* l_Lean_Elab_instInhabitedPreDefinition;
lean_object* l___private_Lean_Elab_PreDefinition_Basic_0__Lean_Elab_addNonRecAux(lean_object*, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
extern lean_object* l_Lean_instInhabitedExpr;
static lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__3;
lean_object* l___private_Init_Util_0__mkPanicMessageWithDecl(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Elab_wfRecursion___spec__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__6;
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1;
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__4;
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__9;
LEAN_EXPORT lean_object* l_Lean_Elab_wfRecursion___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Elab_WF_elabWFRel(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
size_t lean_usize_of_nat(lean_object*);
lean_object* l_Lean_Elab_addAndCompilePartialRec(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_addTrace___at___private_Lean_Elab_Term_0__Lean_Elab_Term_postponeElabTerm___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1___closed__1;
lean_object* l_Lean_Meta_lambdaTelescope___at_Lean_Meta_MatcherApp_addArg___spec__2___rarg(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__5;
static lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__1;
lean_object* l_Lean_Expr_getAppNumArgsAux(lean_object*, lean_object*);
lean_object* l___private_Lean_Util_Trace_0__Lean_checkTraceOptionM___at___private_Lean_Elab_Term_0__Lean_Elab_Term_postponeElabTerm___spec__2(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__3;
uint8_t lean_nat_dec_le(lean_object*, lean_object*);
lean_object* l_Lean_mkApp(lean_object*, lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__2;
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__1;
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Elab_wfRecursion___closed__2;
LEAN_EXPORT lean_object* l_Lean_Elab_wfRecursion(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8;
lean_object* l_List_mapTRAux___at_Lean_mkConstWithLevelParams___spec__1(lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__9;
lean_object* lean_panic_fn(lean_object*, lean_object*);
lean_object* lean_mk_array(lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4;
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2(lean_object*, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__7;
lean_object* l_Lean_Meta_whnfD(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_panic___at_Lean_Meta_whnfCore___spec__1(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Elab_WF_mkFix(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_mkConst(lean_object*, lean_object*);
lean_object* l_Lean_Meta_lambdaTelescope___at___private_Lean_Elab_PreDefinition_WF_Fix_0__Lean_Elab_WF_replaceRecApps_loop___spec__9___rarg(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8;
lean_object* l_Lean_mkApp3(lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__2;
static lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__1;
lean_object* l_Lean_Elab_WF_packDomain(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7) {
_start:
{
lean_object* x_8; lean_object* x_9; uint8_t x_10; lean_object* x_11; lean_object* x_12;
x_8 = lean_array_get_size(x_1);
x_9 = lean_unsigned_to_nat(1u);
x_10 = lean_nat_dec_eq(x_8, x_9);
lean_dec(x_8);
x_11 = lean_box(x_10);
x_12 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_12, 0, x_11);
lean_ctor_set(x_12, 1, x_7);
return x_12;
}
}
static lean_object* _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_alloc_closure((void*)(l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___lambda__1___boxed), 7, 0);
return x_1;
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6) {
_start:
{
lean_object* x_7; lean_object* x_8; uint8_t x_9;
x_7 = lean_array_get_size(x_1);
x_8 = lean_unsigned_to_nat(1u);
x_9 = lean_nat_dec_eq(x_7, x_8);
lean_dec(x_7);
if (x_9 == 0)
{
uint8_t x_10; lean_object* x_11; lean_object* x_12;
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
x_10 = 0;
x_11 = lean_box(x_10);
x_12 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_12, 0, x_11);
lean_ctor_set(x_12, 1, x_6);
return x_12;
}
else
{
lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; lean_object* x_18;
x_13 = l_Lean_Elab_instInhabitedPreDefinition;
x_14 = lean_unsigned_to_nat(0u);
x_15 = lean_array_get(x_13, x_1, x_14);
x_16 = lean_ctor_get(x_15, 5);
lean_inc(x_16);
lean_dec(x_15);
x_17 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___closed__1;
x_18 = l_Lean_Meta_lambdaTelescope___at_Lean_Meta_MatcherApp_addArg___spec__2___rarg(x_16, x_17, x_2, x_3, x_4, x_5, x_6);
return x_18;
}
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7) {
_start:
{
lean_object* x_8;
x_8 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___lambda__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
return x_8;
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6) {
_start:
{
lean_object* x_7;
x_7 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef(x_1, x_2, x_3, x_4, x_5, x_6);
lean_dec(x_1);
return x_7;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("assertion violation: ");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__2() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("args.size == 2\n ");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__3() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__1;
x_2 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__2;
x_3 = lean_string_append(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("Lean.Elab.PreDefinition.WF.Main");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__5() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("_private.Lean.Elab.PreDefinition.WF.Main.0.Lean.Elab.addNonRecPreDefs.mkSum");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__6() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6;
x_1 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4;
x_2 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__5;
x_3 = lean_unsigned_to_nat(38u);
x_4 = lean_unsigned_to_nat(12u);
x_5 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__3;
x_6 = l___private_Init_Util_0__mkPanicMessageWithDecl(x_1, x_2, x_3, x_4, x_5);
return x_6;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__7() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("Sum");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__7;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__9() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("inr");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8;
x_2 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__9;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__11() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("inl");
return x_1;
}
}
static lean_object* _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8;
x_2 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__11;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12) {
_start:
{
if (lean_obj_tag(x_5) == 5)
{
lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17;
x_13 = lean_ctor_get(x_5, 0);
lean_inc(x_13);
x_14 = lean_ctor_get(x_5, 1);
lean_inc(x_14);
lean_dec(x_5);
x_15 = lean_array_set(x_6, x_7, x_14);
x_16 = lean_unsigned_to_nat(1u);
x_17 = lean_nat_sub(x_7, x_16);
lean_dec(x_7);
x_5 = x_13;
x_6 = x_15;
x_7 = x_17;
goto _start;
}
else
{
lean_object* x_19; lean_object* x_20; uint8_t x_21;
lean_dec(x_7);
x_19 = lean_array_get_size(x_6);
x_20 = lean_unsigned_to_nat(2u);
x_21 = lean_nat_dec_eq(x_19, x_20);
lean_dec(x_19);
if (x_21 == 0)
{
lean_object* x_22; lean_object* x_23;
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_3);
x_22 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__6;
x_23 = l_panic___at_Lean_Meta_whnfCore___spec__1(x_22, x_8, x_9, x_10, x_11, x_12);
return x_23;
}
else
{
uint8_t x_24;
x_24 = lean_nat_dec_eq(x_4, x_2);
if (x_24 == 0)
{
lean_object* x_25; lean_object* x_26; lean_object* x_27; lean_object* x_28; lean_object* x_29;
x_25 = lean_unsigned_to_nat(1u);
x_26 = lean_nat_add(x_4, x_25);
x_27 = l_Lean_instInhabitedExpr;
x_28 = lean_array_get(x_27, x_6, x_25);
lean_inc(x_28);
x_29 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum(x_1, x_2, x_3, x_26, x_28, x_8, x_9, x_10, x_11, x_12);
lean_dec(x_26);
if (lean_obj_tag(x_29) == 0)
{
uint8_t x_30;
x_30 = !lean_is_exclusive(x_29);
if (x_30 == 0)
{
lean_object* x_31; lean_object* x_32; lean_object* x_33; lean_object* x_34; lean_object* x_35; lean_object* x_36; lean_object* x_37;
x_31 = lean_ctor_get(x_29, 0);
x_32 = l_Lean_Expr_constLevels_x21(x_5);
x_33 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10;
x_34 = l_Lean_mkConst(x_33, x_32);
x_35 = lean_unsigned_to_nat(0u);
x_36 = lean_array_get(x_27, x_6, x_35);
lean_dec(x_6);
x_37 = l_Lean_mkApp3(x_34, x_36, x_28, x_31);
lean_ctor_set(x_29, 0, x_37);
return x_29;
}
else
{
lean_object* x_38; lean_object* x_39; lean_object* x_40; lean_object* x_41; lean_object* x_42; lean_object* x_43; lean_object* x_44; lean_object* x_45; lean_object* x_46;
x_38 = lean_ctor_get(x_29, 0);
x_39 = lean_ctor_get(x_29, 1);
lean_inc(x_39);
lean_inc(x_38);
lean_dec(x_29);
x_40 = l_Lean_Expr_constLevels_x21(x_5);
x_41 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10;
x_42 = l_Lean_mkConst(x_41, x_40);
x_43 = lean_unsigned_to_nat(0u);
x_44 = lean_array_get(x_27, x_6, x_43);
lean_dec(x_6);
x_45 = l_Lean_mkApp3(x_42, x_44, x_28, x_38);
x_46 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_46, 0, x_45);
lean_ctor_set(x_46, 1, x_39);
return x_46;
}
}
else
{
uint8_t x_47;
lean_dec(x_28);
lean_dec(x_6);
lean_dec(x_5);
x_47 = !lean_is_exclusive(x_29);
if (x_47 == 0)
{
return x_29;
}
else
{
lean_object* x_48; lean_object* x_49; lean_object* x_50;
x_48 = lean_ctor_get(x_29, 0);
x_49 = lean_ctor_get(x_29, 1);
lean_inc(x_49);
lean_inc(x_48);
lean_dec(x_29);
x_50 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_50, 0, x_48);
lean_ctor_set(x_50, 1, x_49);
return x_50;
}
}
}
else
{
lean_object* x_51; lean_object* x_52; lean_object* x_53; lean_object* x_54;
x_51 = l_Lean_instInhabitedExpr;
x_52 = lean_unsigned_to_nat(0u);
x_53 = lean_array_get(x_51, x_6, x_52);
lean_inc(x_53);
x_54 = lean_apply_6(x_3, x_53, x_8, x_9, x_10, x_11, x_12);
if (lean_obj_tag(x_54) == 0)
{
uint8_t x_55;
x_55 = !lean_is_exclusive(x_54);
if (x_55 == 0)
{
lean_object* x_56; lean_object* x_57; lean_object* x_58; lean_object* x_59; lean_object* x_60; lean_object* x_61; lean_object* x_62;
x_56 = lean_ctor_get(x_54, 0);
x_57 = l_Lean_Expr_constLevels_x21(x_5);
x_58 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12;
x_59 = l_Lean_mkConst(x_58, x_57);
x_60 = lean_unsigned_to_nat(1u);
x_61 = lean_array_get(x_51, x_6, x_60);
lean_dec(x_6);
x_62 = l_Lean_mkApp3(x_59, x_53, x_61, x_56);
lean_ctor_set(x_54, 0, x_62);
return x_54;
}
else
{
lean_object* x_63; lean_object* x_64; lean_object* x_65; lean_object* x_66; lean_object* x_67; lean_object* x_68; lean_object* x_69; lean_object* x_70; lean_object* x_71;
x_63 = lean_ctor_get(x_54, 0);
x_64 = lean_ctor_get(x_54, 1);
lean_inc(x_64);
lean_inc(x_63);
lean_dec(x_54);
x_65 = l_Lean_Expr_constLevels_x21(x_5);
x_66 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12;
x_67 = l_Lean_mkConst(x_66, x_65);
x_68 = lean_unsigned_to_nat(1u);
x_69 = lean_array_get(x_51, x_6, x_68);
lean_dec(x_6);
x_70 = l_Lean_mkApp3(x_67, x_53, x_69, x_63);
x_71 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_71, 0, x_70);
lean_ctor_set(x_71, 1, x_64);
return x_71;
}
}
else
{
uint8_t x_72;
lean_dec(x_53);
lean_dec(x_6);
lean_dec(x_5);
x_72 = !lean_is_exclusive(x_54);
if (x_72 == 0)
{
return x_54;
}
else
{
lean_object* x_73; lean_object* x_74; lean_object* x_75;
x_73 = lean_ctor_get(x_54, 0);
x_74 = lean_ctor_get(x_54, 1);
lean_inc(x_74);
lean_inc(x_73);
lean_dec(x_54);
x_75 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_75, 0, x_73);
lean_ctor_set(x_75, 1, x_74);
return x_75;
}
}
}
}
}
}
}
static lean_object* _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Lean_levelZero;
x_2 = l_Lean_mkSort(x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11; lean_object* x_12; lean_object* x_13; uint8_t x_14;
x_11 = lean_array_get_size(x_1);
x_12 = lean_unsigned_to_nat(1u);
x_13 = lean_nat_sub(x_11, x_12);
lean_dec(x_11);
x_14 = lean_nat_dec_eq(x_4, x_13);
lean_dec(x_13);
if (x_14 == 0)
{
lean_object* x_15;
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
x_15 = l_Lean_Meta_whnfD(x_5, x_6, x_7, x_8, x_9, x_10);
if (lean_obj_tag(x_15) == 0)
{
lean_object* x_16; lean_object* x_17; lean_object* x_18; lean_object* x_19; lean_object* x_20; lean_object* x_21; lean_object* x_22; lean_object* x_23;
x_16 = lean_ctor_get(x_15, 0);
lean_inc(x_16);
x_17 = lean_ctor_get(x_15, 1);
lean_inc(x_17);
lean_dec(x_15);
x_18 = lean_unsigned_to_nat(0u);
x_19 = l_Lean_Expr_getAppNumArgsAux(x_16, x_18);
x_20 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___closed__1;
lean_inc(x_19);
x_21 = lean_mk_array(x_19, x_20);
x_22 = lean_nat_sub(x_19, x_12);
lean_dec(x_19);
x_23 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1(x_1, x_2, x_3, x_4, x_16, x_21, x_22, x_6, x_7, x_8, x_9, x_17);
return x_23;
}
else
{
uint8_t x_24;
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_3);
x_24 = !lean_is_exclusive(x_15);
if (x_24 == 0)
{
return x_15;
}
else
{
lean_object* x_25; lean_object* x_26; lean_object* x_27;
x_25 = lean_ctor_get(x_15, 0);
x_26 = lean_ctor_get(x_15, 1);
lean_inc(x_26);
lean_inc(x_25);
lean_dec(x_15);
x_27 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_27, 0, x_25);
lean_ctor_set(x_27, 1, x_26);
return x_27;
}
}
}
else
{
lean_object* x_28;
x_28 = lean_apply_6(x_3, x_5, x_6, x_7, x_8, x_9, x_10);
return x_28;
}
}
}
LEAN_EXPORT lean_object* l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12) {
_start:
{
lean_object* x_13;
x_13 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12);
lean_dec(x_4);
lean_dec(x_2);
lean_dec(x_1);
return x_13;
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11;
x_11 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
lean_dec(x_4);
lean_dec(x_2);
lean_dec(x_1);
return x_11;
}
}
static lean_object* _init_l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1___closed__1() {
_start:
{
lean_object* x_1;
x_1 = l_Lean_Elab_Term_instInhabitedTermElabM(lean_box(0));
return x_1;
}
}
LEAN_EXPORT lean_object* l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8) {
_start:
{
lean_object* x_9; lean_object* x_10; lean_object* x_11;
x_9 = l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1___closed__1;
x_10 = lean_panic_fn(x_9, x_1);
x_11 = lean_apply_7(x_10, x_2, x_3, x_4, x_5, x_6, x_7, x_8);
return x_11;
}
}
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14) {
_start:
{
lean_object* x_15; lean_object* x_16; lean_object* x_17;
x_15 = lean_unsigned_to_nat(0u);
lean_inc(x_6);
x_16 = lean_alloc_closure((void*)(l_Lean_Elab_WF_mkUnaryArg_go___boxed), 8, 2);
lean_closure_set(x_16, 0, x_6);
lean_closure_set(x_16, 1, x_15);
lean_inc(x_13);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
x_17 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum(x_1, x_2, x_16, x_15, x_3, x_10, x_11, x_12, x_13, x_14);
if (lean_obj_tag(x_17) == 0)
{
lean_object* x_18; lean_object* x_19; lean_object* x_20; lean_object* x_21; lean_object* x_22; uint8_t x_23; uint8_t x_24; lean_object* x_25;
x_18 = lean_ctor_get(x_17, 0);
lean_inc(x_18);
x_19 = lean_ctor_get(x_17, 1);
lean_inc(x_19);
lean_dec(x_17);
x_20 = lean_ctor_get(x_4, 3);
lean_inc(x_20);
lean_dec(x_4);
x_21 = l_Lean_mkConst(x_20, x_5);
x_22 = l_Lean_mkApp(x_21, x_18);
x_23 = 0;
x_24 = 1;
x_25 = l_Lean_Meta_mkLambdaFVars(x_6, x_22, x_23, x_24, x_10, x_11, x_12, x_13, x_19);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
return x_25;
}
else
{
uint8_t x_26;
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_26 = !lean_is_exclusive(x_17);
if (x_26 == 0)
{
return x_17;
}
else
{
lean_object* x_27; lean_object* x_28; lean_object* x_29;
x_27 = lean_ctor_get(x_17, 0);
x_28 = lean_ctor_get(x_17, 1);
lean_inc(x_28);
lean_inc(x_27);
lean_dec(x_17);
x_29 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_29, 0, x_27);
lean_ctor_set(x_29, 1, x_28);
return x_29;
}
}
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = lean_box(0);
x_2 = lean_alloc_ctor(1, 1, 0);
lean_ctor_set(x_2, 0, x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2(lean_object* x_1, uint8_t x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14, lean_object* x_15) {
_start:
{
lean_object* x_16; uint8_t x_17; lean_object* x_18;
x_16 = lean_alloc_ctor(0, 6, 1);
lean_ctor_set(x_16, 0, x_1);
lean_ctor_set(x_16, 1, x_3);
lean_ctor_set(x_16, 2, x_4);
lean_ctor_set(x_16, 3, x_5);
lean_ctor_set(x_16, 4, x_6);
lean_ctor_set(x_16, 5, x_7);
lean_ctor_set_uint8(x_16, sizeof(void*)*6, x_2);
x_17 = 0;
x_18 = l___private_Lean_Elab_PreDefinition_Basic_0__Lean_Elab_addNonRecAux(x_16, x_17, x_9, x_10, x_11, x_12, x_13, x_14, x_15);
if (lean_obj_tag(x_18) == 0)
{
uint8_t x_19;
x_19 = !lean_is_exclusive(x_18);
if (x_19 == 0)
{
lean_object* x_20; lean_object* x_21;
x_20 = lean_ctor_get(x_18, 0);
lean_dec(x_20);
x_21 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1;
lean_ctor_set(x_18, 0, x_21);
return x_18;
}
else
{
lean_object* x_22; lean_object* x_23; lean_object* x_24;
x_22 = lean_ctor_get(x_18, 1);
lean_inc(x_22);
lean_dec(x_18);
x_23 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1;
x_24 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_24, 0, x_23);
lean_ctor_set(x_24, 1, x_22);
return x_24;
}
}
else
{
uint8_t x_25;
x_25 = !lean_is_exclusive(x_18);
if (x_25 == 0)
{
return x_18;
}
else
{
lean_object* x_26; lean_object* x_27; lean_object* x_28;
x_26 = lean_ctor_get(x_18, 0);
x_27 = lean_ctor_get(x_18, 1);
lean_inc(x_27);
lean_inc(x_26);
lean_dec(x_18);
x_28 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_28, 0, x_26);
lean_ctor_set(x_28, 1, x_27);
return x_28;
}
}
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("Elab");
return x_1;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__3() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("definition");
return x_1;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__4() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__2;
x_2 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__3;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__5() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("wf");
return x_1;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__4;
x_2 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__5;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__7() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("");
return x_1;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__7;
x_2 = l_Lean_stringToMessageData(x_1);
return x_2;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__9() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string(" := ");
return x_1;
}
}
static lean_object* _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__10() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__9;
x_2 = l_Lean_stringToMessageData(x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14, lean_object* x_15) {
_start:
{
lean_object* x_16; uint8_t x_17;
x_16 = lean_ctor_get(x_5, 1);
x_17 = lean_nat_dec_le(x_16, x_7);
if (x_17 == 0)
{
lean_object* x_18; uint8_t x_19;
x_18 = lean_unsigned_to_nat(0u);
x_19 = lean_nat_dec_eq(x_6, x_18);
if (x_19 == 0)
{
lean_object* x_20; lean_object* x_21; lean_object* x_22; lean_object* x_23; lean_object* x_24; uint8_t x_25; lean_object* x_26; lean_object* x_27; lean_object* x_28; lean_object* x_29; lean_object* x_30; lean_object* x_31; lean_object* x_32;
lean_dec(x_8);
x_20 = lean_unsigned_to_nat(1u);
x_21 = lean_nat_sub(x_6, x_20);
lean_dec(x_6);
x_22 = l_Lean_Elab_instInhabitedPreDefinition;
x_23 = lean_array_get(x_22, x_1, x_7);
x_24 = lean_ctor_get(x_23, 0);
lean_inc(x_24);
x_25 = lean_ctor_get_uint8(x_23, sizeof(void*)*6);
x_26 = lean_ctor_get(x_23, 1);
lean_inc(x_26);
x_27 = lean_ctor_get(x_23, 2);
lean_inc(x_27);
x_28 = lean_ctor_get(x_23, 3);
lean_inc(x_28);
x_29 = lean_ctor_get(x_23, 4);
lean_inc(x_29);
x_30 = lean_ctor_get(x_23, 5);
lean_inc(x_30);
lean_dec(x_23);
lean_inc(x_4);
lean_inc(x_2);
lean_inc(x_3);
lean_inc(x_7);
lean_inc(x_1);
x_31 = lean_alloc_closure((void*)(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__1___boxed), 14, 5);
lean_closure_set(x_31, 0, x_1);
lean_closure_set(x_31, 1, x_7);
lean_closure_set(x_31, 2, x_3);
lean_closure_set(x_31, 3, x_2);
lean_closure_set(x_31, 4, x_4);
lean_inc(x_14);
lean_inc(x_13);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
x_32 = l_Lean_Meta_lambdaTelescope___at___private_Lean_Elab_PreDefinition_WF_Fix_0__Lean_Elab_WF_replaceRecApps_loop___spec__9___rarg(x_30, x_31, x_9, x_10, x_11, x_12, x_13, x_14, x_15);
if (lean_obj_tag(x_32) == 0)
{
lean_object* x_33; lean_object* x_34; lean_object* x_35; uint8_t x_36; lean_object* x_37; lean_object* x_85; lean_object* x_86; lean_object* x_87; uint8_t x_88;
x_33 = lean_ctor_get(x_32, 0);
lean_inc(x_33);
x_34 = lean_ctor_get(x_32, 1);
lean_inc(x_34);
lean_dec(x_32);
x_35 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6;
x_85 = lean_st_ref_get(x_14, x_34);
x_86 = lean_ctor_get(x_85, 0);
lean_inc(x_86);
x_87 = lean_ctor_get(x_86, 3);
lean_inc(x_87);
lean_dec(x_86);
x_88 = lean_ctor_get_uint8(x_87, sizeof(void*)*1);
lean_dec(x_87);
if (x_88 == 0)
{
lean_object* x_89; uint8_t x_90;
x_89 = lean_ctor_get(x_85, 1);
lean_inc(x_89);
lean_dec(x_85);
x_90 = 0;
x_36 = x_90;
x_37 = x_89;
goto block_84;
}
else
{
lean_object* x_91; lean_object* x_92; lean_object* x_93; lean_object* x_94; uint8_t x_95;
x_91 = lean_ctor_get(x_85, 1);
lean_inc(x_91);
lean_dec(x_85);
x_92 = l___private_Lean_Util_Trace_0__Lean_checkTraceOptionM___at___private_Lean_Elab_Term_0__Lean_Elab_Term_postponeElabTerm___spec__2(x_35, x_9, x_10, x_11, x_12, x_13, x_14, x_91);
x_93 = lean_ctor_get(x_92, 0);
lean_inc(x_93);
x_94 = lean_ctor_get(x_92, 1);
lean_inc(x_94);
lean_dec(x_92);
x_95 = lean_unbox(x_93);
lean_dec(x_93);
x_36 = x_95;
x_37 = x_94;
goto block_84;
}
block_84:
{
if (x_36 == 0)
{
lean_object* x_38; lean_object* x_39;
x_38 = lean_box(0);
lean_inc(x_14);
lean_inc(x_13);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
x_39 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2(x_24, x_25, x_26, x_27, x_28, x_29, x_33, x_38, x_9, x_10, x_11, x_12, x_13, x_14, x_37);
if (lean_obj_tag(x_39) == 0)
{
lean_object* x_40;
x_40 = lean_ctor_get(x_39, 0);
lean_inc(x_40);
if (lean_obj_tag(x_40) == 0)
{
uint8_t x_41;
lean_dec(x_21);
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_41 = !lean_is_exclusive(x_39);
if (x_41 == 0)
{
lean_object* x_42; lean_object* x_43;
x_42 = lean_ctor_get(x_39, 0);
lean_dec(x_42);
x_43 = lean_ctor_get(x_40, 0);
lean_inc(x_43);
lean_dec(x_40);
lean_ctor_set(x_39, 0, x_43);
return x_39;
}
else
{
lean_object* x_44; lean_object* x_45; lean_object* x_46;
x_44 = lean_ctor_get(x_39, 1);
lean_inc(x_44);
lean_dec(x_39);
x_45 = lean_ctor_get(x_40, 0);
lean_inc(x_45);
lean_dec(x_40);
x_46 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_46, 0, x_45);
lean_ctor_set(x_46, 1, x_44);
return x_46;
}
}
else
{
lean_object* x_47; lean_object* x_48; lean_object* x_49; lean_object* x_50;
x_47 = lean_ctor_get(x_39, 1);
lean_inc(x_47);
lean_dec(x_39);
x_48 = lean_ctor_get(x_40, 0);
lean_inc(x_48);
lean_dec(x_40);
x_49 = lean_ctor_get(x_5, 2);
x_50 = lean_nat_add(x_7, x_49);
lean_dec(x_7);
x_6 = x_21;
x_7 = x_50;
x_8 = x_48;
x_15 = x_47;
goto _start;
}
}
else
{
uint8_t x_52;
lean_dec(x_21);
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_52 = !lean_is_exclusive(x_39);
if (x_52 == 0)
{
return x_39;
}
else
{
lean_object* x_53; lean_object* x_54; lean_object* x_55;
x_53 = lean_ctor_get(x_39, 0);
x_54 = lean_ctor_get(x_39, 1);
lean_inc(x_54);
lean_inc(x_53);
lean_dec(x_39);
x_55 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_55, 0, x_53);
lean_ctor_set(x_55, 1, x_54);
return x_55;
}
}
}
else
{
lean_object* x_56; lean_object* x_57; lean_object* x_58; lean_object* x_59; lean_object* x_60; lean_object* x_61; lean_object* x_62; lean_object* x_63; lean_object* x_64; lean_object* x_65; lean_object* x_66; lean_object* x_67;
lean_inc(x_28);
x_56 = lean_alloc_ctor(4, 1, 0);
lean_ctor_set(x_56, 0, x_28);
x_57 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8;
x_58 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_58, 0, x_57);
lean_ctor_set(x_58, 1, x_56);
x_59 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__10;
x_60 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_60, 0, x_58);
lean_ctor_set(x_60, 1, x_59);
lean_inc(x_33);
x_61 = lean_alloc_ctor(2, 1, 0);
lean_ctor_set(x_61, 0, x_33);
x_62 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_62, 0, x_60);
lean_ctor_set(x_62, 1, x_61);
x_63 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_63, 0, x_62);
lean_ctor_set(x_63, 1, x_57);
x_64 = l_Lean_addTrace___at___private_Lean_Elab_Term_0__Lean_Elab_Term_postponeElabTerm___spec__1(x_35, x_63, x_9, x_10, x_11, x_12, x_13, x_14, x_37);
x_65 = lean_ctor_get(x_64, 0);
lean_inc(x_65);
x_66 = lean_ctor_get(x_64, 1);
lean_inc(x_66);
lean_dec(x_64);
lean_inc(x_14);
lean_inc(x_13);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
x_67 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2(x_24, x_25, x_26, x_27, x_28, x_29, x_33, x_65, x_9, x_10, x_11, x_12, x_13, x_14, x_66);
lean_dec(x_65);
if (lean_obj_tag(x_67) == 0)
{
lean_object* x_68;
x_68 = lean_ctor_get(x_67, 0);
lean_inc(x_68);
if (lean_obj_tag(x_68) == 0)
{
uint8_t x_69;
lean_dec(x_21);
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_69 = !lean_is_exclusive(x_67);
if (x_69 == 0)
{
lean_object* x_70; lean_object* x_71;
x_70 = lean_ctor_get(x_67, 0);
lean_dec(x_70);
x_71 = lean_ctor_get(x_68, 0);
lean_inc(x_71);
lean_dec(x_68);
lean_ctor_set(x_67, 0, x_71);
return x_67;
}
else
{
lean_object* x_72; lean_object* x_73; lean_object* x_74;
x_72 = lean_ctor_get(x_67, 1);
lean_inc(x_72);
lean_dec(x_67);
x_73 = lean_ctor_get(x_68, 0);
lean_inc(x_73);
lean_dec(x_68);
x_74 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_74, 0, x_73);
lean_ctor_set(x_74, 1, x_72);
return x_74;
}
}
else
{
lean_object* x_75; lean_object* x_76; lean_object* x_77; lean_object* x_78;
x_75 = lean_ctor_get(x_67, 1);
lean_inc(x_75);
lean_dec(x_67);
x_76 = lean_ctor_get(x_68, 0);
lean_inc(x_76);
lean_dec(x_68);
x_77 = lean_ctor_get(x_5, 2);
x_78 = lean_nat_add(x_7, x_77);
lean_dec(x_7);
x_6 = x_21;
x_7 = x_78;
x_8 = x_76;
x_15 = x_75;
goto _start;
}
}
else
{
uint8_t x_80;
lean_dec(x_21);
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_80 = !lean_is_exclusive(x_67);
if (x_80 == 0)
{
return x_67;
}
else
{
lean_object* x_81; lean_object* x_82; lean_object* x_83;
x_81 = lean_ctor_get(x_67, 0);
x_82 = lean_ctor_get(x_67, 1);
lean_inc(x_82);
lean_inc(x_81);
lean_dec(x_67);
x_83 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_83, 0, x_81);
lean_ctor_set(x_83, 1, x_82);
return x_83;
}
}
}
}
}
else
{
uint8_t x_96;
lean_dec(x_29);
lean_dec(x_28);
lean_dec(x_27);
lean_dec(x_26);
lean_dec(x_24);
lean_dec(x_21);
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_96 = !lean_is_exclusive(x_32);
if (x_96 == 0)
{
return x_32;
}
else
{
lean_object* x_97; lean_object* x_98; lean_object* x_99;
x_97 = lean_ctor_get(x_32, 0);
x_98 = lean_ctor_get(x_32, 1);
lean_inc(x_98);
lean_inc(x_97);
lean_dec(x_32);
x_99 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_99, 0, x_97);
lean_ctor_set(x_99, 1, x_98);
return x_99;
}
}
}
else
{
lean_object* x_100;
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_100 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_100, 0, x_8);
lean_ctor_set(x_100, 1, x_15);
return x_100;
}
}
else
{
lean_object* x_101;
lean_dec(x_14);
lean_dec(x_13);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_101 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_101, 0, x_8);
lean_ctor_set(x_101, 1, x_15);
return x_101;
}
}
}
static lean_object* _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("_private.Lean.Elab.PreDefinition.WF.Main.0.Lean.Elab.addNonRecPreDefs");
return x_1;
}
}
static lean_object* _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__2() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string("unreachable code has been reached");
return x_1;
}
}
static lean_object* _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__3() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6;
x_1 = l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4;
x_2 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__1;
x_3 = lean_unsigned_to_nat(26u);
x_4 = lean_unsigned_to_nat(54u);
x_5 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__2;
x_6 = l___private_Init_Util_0__mkPanicMessageWithDecl(x_1, x_2, x_3, x_4, x_5);
return x_6;
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11;
lean_dec(x_3);
x_11 = lean_ctor_get(x_1, 4);
lean_inc(x_11);
if (lean_obj_tag(x_11) == 7)
{
lean_object* x_12; lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; lean_object* x_18; lean_object* x_19; lean_object* x_20; lean_object* x_21;
x_12 = lean_ctor_get(x_11, 1);
lean_inc(x_12);
lean_dec(x_11);
x_13 = lean_ctor_get(x_1, 1);
lean_inc(x_13);
x_14 = lean_box(0);
x_15 = l_List_mapTRAux___at_Lean_mkConstWithLevelParams___spec__1(x_13, x_14);
x_16 = lean_array_get_size(x_2);
x_17 = lean_unsigned_to_nat(0u);
x_18 = lean_unsigned_to_nat(1u);
lean_inc(x_16);
x_19 = lean_alloc_ctor(0, 3, 0);
lean_ctor_set(x_19, 0, x_17);
lean_ctor_set(x_19, 1, x_16);
lean_ctor_set(x_19, 2, x_18);
x_20 = lean_box(0);
x_21 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2(x_2, x_1, x_12, x_15, x_19, x_16, x_17, x_20, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
lean_dec(x_19);
if (lean_obj_tag(x_21) == 0)
{
uint8_t x_22;
x_22 = !lean_is_exclusive(x_21);
if (x_22 == 0)
{
lean_object* x_23;
x_23 = lean_ctor_get(x_21, 0);
lean_dec(x_23);
lean_ctor_set(x_21, 0, x_20);
return x_21;
}
else
{
lean_object* x_24; lean_object* x_25;
x_24 = lean_ctor_get(x_21, 1);
lean_inc(x_24);
lean_dec(x_21);
x_25 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_25, 0, x_20);
lean_ctor_set(x_25, 1, x_24);
return x_25;
}
}
else
{
uint8_t x_26;
x_26 = !lean_is_exclusive(x_21);
if (x_26 == 0)
{
return x_21;
}
else
{
lean_object* x_27; lean_object* x_28; lean_object* x_29;
x_27 = lean_ctor_get(x_21, 0);
x_28 = lean_ctor_get(x_21, 1);
lean_inc(x_28);
lean_inc(x_27);
lean_dec(x_21);
x_29 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_29, 0, x_27);
lean_ctor_set(x_29, 1, x_28);
return x_29;
}
}
}
else
{
lean_object* x_30; lean_object* x_31;
lean_dec(x_11);
lean_dec(x_2);
lean_dec(x_1);
x_30 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__3;
x_31 = l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1(x_30, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
return x_31;
}
}
}
LEAN_EXPORT lean_object* l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9) {
_start:
{
lean_object* x_10;
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
x_10 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef(x_1, x_5, x_6, x_7, x_8, x_9);
if (lean_obj_tag(x_10) == 0)
{
lean_object* x_11; uint8_t x_12;
x_11 = lean_ctor_get(x_10, 0);
lean_inc(x_11);
x_12 = lean_unbox(x_11);
lean_dec(x_11);
if (x_12 == 0)
{
lean_object* x_13; lean_object* x_14; lean_object* x_15;
x_13 = lean_ctor_get(x_10, 1);
lean_inc(x_13);
lean_dec(x_10);
x_14 = lean_box(0);
x_15 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1(x_2, x_1, x_14, x_3, x_4, x_5, x_6, x_7, x_8, x_13);
return x_15;
}
else
{
uint8_t x_16;
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_16 = !lean_is_exclusive(x_10);
if (x_16 == 0)
{
lean_object* x_17; lean_object* x_18;
x_17 = lean_ctor_get(x_10, 0);
lean_dec(x_17);
x_18 = lean_box(0);
lean_ctor_set(x_10, 0, x_18);
return x_10;
}
else
{
lean_object* x_19; lean_object* x_20; lean_object* x_21;
x_19 = lean_ctor_get(x_10, 1);
lean_inc(x_19);
lean_dec(x_10);
x_20 = lean_box(0);
x_21 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_21, 0, x_20);
lean_ctor_set(x_21, 1, x_19);
return x_21;
}
}
}
else
{
uint8_t x_22;
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_22 = !lean_is_exclusive(x_10);
if (x_22 == 0)
{
return x_10;
}
else
{
lean_object* x_23; lean_object* x_24; lean_object* x_25;
x_23 = lean_ctor_get(x_10, 0);
x_24 = lean_ctor_get(x_10, 1);
lean_inc(x_24);
lean_inc(x_23);
lean_dec(x_10);
x_25 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_25, 0, x_23);
lean_ctor_set(x_25, 1, x_24);
return x_25;
}
}
}
}
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14) {
_start:
{
lean_object* x_15;
x_15 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13, x_14);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_2);
lean_dec(x_1);
return x_15;
}
}
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14, lean_object* x_15) {
_start:
{
uint8_t x_16; lean_object* x_17;
x_16 = lean_unbox(x_2);
lean_dec(x_2);
x_17 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2(x_1, x_16, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13, x_14, x_15);
lean_dec(x_8);
return x_17;
}
}
LEAN_EXPORT lean_object* l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13, lean_object* x_14, lean_object* x_15) {
_start:
{
lean_object* x_16;
x_16 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13, x_14, x_15);
lean_dec(x_5);
return x_16;
}
}
LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Elab_wfRecursion___spec__1(lean_object* x_1, size_t x_2, size_t x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11) {
_start:
{
uint8_t x_12;
x_12 = lean_usize_dec_lt(x_3, x_2);
if (x_12 == 0)
{
lean_object* x_13;
lean_dec(x_9);
x_13 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_13, 0, x_4);
lean_ctor_set(x_13, 1, x_11);
return x_13;
}
else
{
lean_object* x_14; lean_object* x_15;
lean_dec(x_4);
x_14 = lean_array_uget(x_1, x_3);
lean_inc(x_9);
x_15 = l_Lean_Elab_addAsAxiom(x_14, x_7, x_8, x_9, x_10, x_11);
lean_dec(x_14);
if (lean_obj_tag(x_15) == 0)
{
lean_object* x_16; size_t x_17; size_t x_18; lean_object* x_19;
x_16 = lean_ctor_get(x_15, 1);
lean_inc(x_16);
lean_dec(x_15);
x_17 = 1;
x_18 = lean_usize_add(x_3, x_17);
x_19 = lean_box(0);
x_3 = x_18;
x_4 = x_19;
x_11 = x_16;
goto _start;
}
else
{
uint8_t x_21;
lean_dec(x_9);
x_21 = !lean_is_exclusive(x_15);
if (x_21 == 0)
{
return x_15;
}
else
{
lean_object* x_22; lean_object* x_23; lean_object* x_24;
x_22 = lean_ctor_get(x_15, 0);
x_23 = lean_ctor_get(x_15, 1);
lean_inc(x_23);
lean_inc(x_22);
lean_dec(x_15);
x_24 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_24, 0, x_22);
lean_ctor_set(x_24, 1, x_23);
return x_24;
}
}
}
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_wfRecursion___lambda__1(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
uint8_t x_11; lean_object* x_12;
x_11 = 0;
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
lean_inc(x_4);
lean_inc(x_1);
x_12 = l___private_Lean_Elab_PreDefinition_Basic_0__Lean_Elab_addNonRecAux(x_1, x_11, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
if (lean_obj_tag(x_12) == 0)
{
lean_object* x_13; lean_object* x_14;
x_13 = lean_ctor_get(x_12, 1);
lean_inc(x_13);
lean_dec(x_12);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
lean_inc(x_4);
lean_inc(x_2);
x_14 = l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs(x_2, x_1, x_4, x_5, x_6, x_7, x_8, x_9, x_13);
if (lean_obj_tag(x_14) == 0)
{
lean_object* x_15; lean_object* x_16;
x_15 = lean_ctor_get(x_14, 1);
lean_inc(x_15);
lean_dec(x_14);
x_16 = l_Lean_Elab_addAndCompilePartialRec(x_2, x_4, x_5, x_6, x_7, x_8, x_9, x_15);
return x_16;
}
else
{
uint8_t x_17;
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_2);
x_17 = !lean_is_exclusive(x_14);
if (x_17 == 0)
{
return x_14;
}
else
{
lean_object* x_18; lean_object* x_19; lean_object* x_20;
x_18 = lean_ctor_get(x_14, 0);
x_19 = lean_ctor_get(x_14, 1);
lean_inc(x_19);
lean_inc(x_18);
lean_dec(x_14);
x_20 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_20, 0, x_18);
lean_ctor_set(x_20, 1, x_19);
return x_20;
}
}
}
else
{
uint8_t x_21;
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_2);
lean_dec(x_1);
x_21 = !lean_is_exclusive(x_12);
if (x_21 == 0)
{
return x_12;
}
else
{
lean_object* x_22; lean_object* x_23; lean_object* x_24;
x_22 = lean_ctor_get(x_12, 0);
x_23 = lean_ctor_get(x_12, 1);
lean_inc(x_23);
lean_inc(x_22);
lean_dec(x_12);
x_24 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_24, 0, x_22);
lean_ctor_set(x_24, 1, x_23);
return x_24;
}
}
}
}
static lean_object* _init_l_Lean_Elab_wfRecursion___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string(">> ");
return x_1;
}
}
static lean_object* _init_l_Lean_Elab_wfRecursion___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2;
x_1 = l_Lean_Elab_wfRecursion___closed__1;
x_2 = l_Lean_stringToMessageData(x_1);
return x_2;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_wfRecursion(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11; size_t x_12; size_t x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; lean_object* x_18; lean_object* x_19;
x_11 = lean_array_get_size(x_1);
x_12 = lean_usize_of_nat(x_11);
lean_dec(x_11);
x_13 = 0;
x_14 = lean_st_ref_get(x_9, x_10);
x_15 = lean_ctor_get(x_14, 0);
lean_inc(x_15);
x_16 = lean_ctor_get(x_14, 1);
lean_inc(x_16);
lean_dec(x_14);
x_17 = lean_ctor_get(x_15, 0);
lean_inc(x_17);
lean_dec(x_15);
x_18 = lean_box(0);
lean_inc(x_8);
x_19 = l_Array_forInUnsafe_loop___at_Lean_Elab_wfRecursion___spec__1(x_1, x_12, x_13, x_18, x_4, x_5, x_6, x_7, x_8, x_9, x_16);
if (lean_obj_tag(x_19) == 0)
{
lean_object* x_20; lean_object* x_21;
x_20 = lean_ctor_get(x_19, 1);
lean_inc(x_20);
lean_dec(x_19);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_1);
x_21 = l_Lean_Elab_WF_packDomain(x_1, x_6, x_7, x_8, x_9, x_20);
if (lean_obj_tag(x_21) == 0)
{
lean_object* x_22; lean_object* x_23; lean_object* x_24;
x_22 = lean_ctor_get(x_21, 0);
lean_inc(x_22);
x_23 = lean_ctor_get(x_21, 1);
lean_inc(x_23);
lean_dec(x_21);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
x_24 = l_Lean_Elab_WF_packMutual(x_22, x_6, x_7, x_8, x_9, x_23);
if (lean_obj_tag(x_24) == 0)
{
lean_object* x_25; lean_object* x_26; lean_object* x_27; lean_object* x_28; lean_object* x_29;
x_25 = lean_ctor_get(x_24, 0);
lean_inc(x_25);
x_26 = lean_ctor_get(x_24, 1);
lean_inc(x_26);
lean_dec(x_24);
x_27 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_17, x_4, x_5, x_6, x_7, x_8, x_9, x_26);
x_28 = lean_ctor_get(x_27, 1);
lean_inc(x_28);
lean_dec(x_27);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
lean_inc(x_4);
lean_inc(x_25);
x_29 = l_Lean_Elab_WF_elabWFRel(x_25, x_2, x_4, x_5, x_6, x_7, x_8, x_9, x_28);
if (lean_obj_tag(x_29) == 0)
{
lean_object* x_30; lean_object* x_31; lean_object* x_32; lean_object* x_33; lean_object* x_34; lean_object* x_35; lean_object* x_36;
x_30 = lean_ctor_get(x_29, 0);
lean_inc(x_30);
x_31 = lean_ctor_get(x_29, 1);
lean_inc(x_31);
lean_dec(x_29);
x_32 = lean_st_ref_get(x_9, x_31);
x_33 = lean_ctor_get(x_32, 0);
lean_inc(x_33);
x_34 = lean_ctor_get(x_32, 1);
lean_inc(x_34);
lean_dec(x_32);
x_35 = lean_ctor_get(x_33, 0);
lean_inc(x_35);
lean_dec(x_33);
lean_inc(x_8);
x_36 = l_Lean_Elab_addAsAxiom(x_25, x_6, x_7, x_8, x_9, x_34);
if (lean_obj_tag(x_36) == 0)
{
lean_object* x_37; lean_object* x_38;
x_37 = lean_ctor_get(x_36, 1);
lean_inc(x_37);
lean_dec(x_36);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
lean_inc(x_4);
x_38 = l_Lean_Elab_WF_mkFix(x_25, x_30, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_37);
if (lean_obj_tag(x_38) == 0)
{
lean_object* x_39; lean_object* x_40; lean_object* x_41; lean_object* x_42; lean_object* x_43; uint8_t x_44; lean_object* x_45; lean_object* x_58; lean_object* x_59; lean_object* x_60; uint8_t x_61;
x_39 = lean_ctor_get(x_38, 0);
lean_inc(x_39);
x_40 = lean_ctor_get(x_38, 1);
lean_inc(x_40);
lean_dec(x_38);
x_41 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_35, x_4, x_5, x_6, x_7, x_8, x_9, x_40);
x_42 = lean_ctor_get(x_41, 1);
lean_inc(x_42);
lean_dec(x_41);
x_43 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6;
x_58 = lean_st_ref_get(x_9, x_42);
x_59 = lean_ctor_get(x_58, 0);
lean_inc(x_59);
x_60 = lean_ctor_get(x_59, 3);
lean_inc(x_60);
lean_dec(x_59);
x_61 = lean_ctor_get_uint8(x_60, sizeof(void*)*1);
lean_dec(x_60);
if (x_61 == 0)
{
lean_object* x_62; uint8_t x_63;
x_62 = lean_ctor_get(x_58, 1);
lean_inc(x_62);
lean_dec(x_58);
x_63 = 0;
x_44 = x_63;
x_45 = x_62;
goto block_57;
}
else
{
lean_object* x_64; lean_object* x_65; lean_object* x_66; lean_object* x_67; uint8_t x_68;
x_64 = lean_ctor_get(x_58, 1);
lean_inc(x_64);
lean_dec(x_58);
x_65 = l___private_Lean_Util_Trace_0__Lean_checkTraceOptionM___at___private_Lean_Elab_Term_0__Lean_Elab_Term_postponeElabTerm___spec__2(x_43, x_4, x_5, x_6, x_7, x_8, x_9, x_64);
x_66 = lean_ctor_get(x_65, 0);
lean_inc(x_66);
x_67 = lean_ctor_get(x_65, 1);
lean_inc(x_67);
lean_dec(x_65);
x_68 = lean_unbox(x_66);
lean_dec(x_66);
x_44 = x_68;
x_45 = x_67;
goto block_57;
}
block_57:
{
if (x_44 == 0)
{
lean_object* x_46;
x_46 = l_Lean_Elab_wfRecursion___lambda__1(x_39, x_1, x_18, x_4, x_5, x_6, x_7, x_8, x_9, x_45);
return x_46;
}
else
{
lean_object* x_47; lean_object* x_48; lean_object* x_49; lean_object* x_50; lean_object* x_51; lean_object* x_52; lean_object* x_53; lean_object* x_54; lean_object* x_55; lean_object* x_56;
x_47 = lean_ctor_get(x_39, 3);
lean_inc(x_47);
x_48 = lean_alloc_ctor(4, 1, 0);
lean_ctor_set(x_48, 0, x_47);
x_49 = l_Lean_Elab_wfRecursion___closed__2;
x_50 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_50, 0, x_49);
lean_ctor_set(x_50, 1, x_48);
x_51 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8;
x_52 = lean_alloc_ctor(10, 2, 0);
lean_ctor_set(x_52, 0, x_50);
lean_ctor_set(x_52, 1, x_51);
x_53 = l_Lean_addTrace___at___private_Lean_Elab_Term_0__Lean_Elab_Term_postponeElabTerm___spec__1(x_43, x_52, x_4, x_5, x_6, x_7, x_8, x_9, x_45);
x_54 = lean_ctor_get(x_53, 0);
lean_inc(x_54);
x_55 = lean_ctor_get(x_53, 1);
lean_inc(x_55);
lean_dec(x_53);
x_56 = l_Lean_Elab_wfRecursion___lambda__1(x_39, x_1, x_54, x_4, x_5, x_6, x_7, x_8, x_9, x_55);
lean_dec(x_54);
return x_56;
}
}
}
else
{
lean_object* x_69; lean_object* x_70; lean_object* x_71; uint8_t x_72;
lean_dec(x_1);
x_69 = lean_ctor_get(x_38, 0);
lean_inc(x_69);
x_70 = lean_ctor_get(x_38, 1);
lean_inc(x_70);
lean_dec(x_38);
x_71 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_35, x_4, x_5, x_6, x_7, x_8, x_9, x_70);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_72 = !lean_is_exclusive(x_71);
if (x_72 == 0)
{
lean_object* x_73;
x_73 = lean_ctor_get(x_71, 0);
lean_dec(x_73);
lean_ctor_set_tag(x_71, 1);
lean_ctor_set(x_71, 0, x_69);
return x_71;
}
else
{
lean_object* x_74; lean_object* x_75;
x_74 = lean_ctor_get(x_71, 1);
lean_inc(x_74);
lean_dec(x_71);
x_75 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_75, 0, x_69);
lean_ctor_set(x_75, 1, x_74);
return x_75;
}
}
}
else
{
lean_object* x_76; lean_object* x_77; lean_object* x_78; uint8_t x_79;
lean_dec(x_30);
lean_dec(x_25);
lean_dec(x_3);
lean_dec(x_1);
x_76 = lean_ctor_get(x_36, 0);
lean_inc(x_76);
x_77 = lean_ctor_get(x_36, 1);
lean_inc(x_77);
lean_dec(x_36);
x_78 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_35, x_4, x_5, x_6, x_7, x_8, x_9, x_77);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_79 = !lean_is_exclusive(x_78);
if (x_79 == 0)
{
lean_object* x_80;
x_80 = lean_ctor_get(x_78, 0);
lean_dec(x_80);
lean_ctor_set_tag(x_78, 1);
lean_ctor_set(x_78, 0, x_76);
return x_78;
}
else
{
lean_object* x_81; lean_object* x_82;
x_81 = lean_ctor_get(x_78, 1);
lean_inc(x_81);
lean_dec(x_78);
x_82 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_82, 0, x_76);
lean_ctor_set(x_82, 1, x_81);
return x_82;
}
}
}
else
{
uint8_t x_83;
lean_dec(x_25);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_1);
x_83 = !lean_is_exclusive(x_29);
if (x_83 == 0)
{
return x_29;
}
else
{
lean_object* x_84; lean_object* x_85; lean_object* x_86;
x_84 = lean_ctor_get(x_29, 0);
x_85 = lean_ctor_get(x_29, 1);
lean_inc(x_85);
lean_inc(x_84);
lean_dec(x_29);
x_86 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_86, 0, x_84);
lean_ctor_set(x_86, 1, x_85);
return x_86;
}
}
}
else
{
lean_object* x_87; lean_object* x_88; lean_object* x_89; uint8_t x_90;
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_87 = lean_ctor_get(x_24, 0);
lean_inc(x_87);
x_88 = lean_ctor_get(x_24, 1);
lean_inc(x_88);
lean_dec(x_24);
x_89 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_17, x_4, x_5, x_6, x_7, x_8, x_9, x_88);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_90 = !lean_is_exclusive(x_89);
if (x_90 == 0)
{
lean_object* x_91;
x_91 = lean_ctor_get(x_89, 0);
lean_dec(x_91);
lean_ctor_set_tag(x_89, 1);
lean_ctor_set(x_89, 0, x_87);
return x_89;
}
else
{
lean_object* x_92; lean_object* x_93;
x_92 = lean_ctor_get(x_89, 1);
lean_inc(x_92);
lean_dec(x_89);
x_93 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_93, 0, x_87);
lean_ctor_set(x_93, 1, x_92);
return x_93;
}
}
}
else
{
lean_object* x_94; lean_object* x_95; lean_object* x_96; uint8_t x_97;
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_94 = lean_ctor_get(x_21, 0);
lean_inc(x_94);
x_95 = lean_ctor_get(x_21, 1);
lean_inc(x_95);
lean_dec(x_21);
x_96 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_17, x_4, x_5, x_6, x_7, x_8, x_9, x_95);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_97 = !lean_is_exclusive(x_96);
if (x_97 == 0)
{
lean_object* x_98;
x_98 = lean_ctor_get(x_96, 0);
lean_dec(x_98);
lean_ctor_set_tag(x_96, 1);
lean_ctor_set(x_96, 0, x_94);
return x_96;
}
else
{
lean_object* x_99; lean_object* x_100;
x_99 = lean_ctor_get(x_96, 1);
lean_inc(x_99);
lean_dec(x_96);
x_100 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_100, 0, x_94);
lean_ctor_set(x_100, 1, x_99);
return x_100;
}
}
}
else
{
lean_object* x_101; lean_object* x_102; lean_object* x_103; uint8_t x_104;
lean_dec(x_3);
lean_dec(x_2);
lean_dec(x_1);
x_101 = lean_ctor_get(x_19, 0);
lean_inc(x_101);
x_102 = lean_ctor_get(x_19, 1);
lean_inc(x_102);
lean_dec(x_19);
x_103 = l_Lean_setEnv___at_Lean_Elab_Term_evalExpr___spec__1(x_17, x_4, x_5, x_6, x_7, x_8, x_9, x_102);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_104 = !lean_is_exclusive(x_103);
if (x_104 == 0)
{
lean_object* x_105;
x_105 = lean_ctor_get(x_103, 0);
lean_dec(x_105);
lean_ctor_set_tag(x_103, 1);
lean_ctor_set(x_103, 0, x_101);
return x_103;
}
else
{
lean_object* x_106; lean_object* x_107;
x_106 = lean_ctor_get(x_103, 1);
lean_inc(x_106);
lean_dec(x_103);
x_107 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_107, 0, x_101);
lean_ctor_set(x_107, 1, x_106);
return x_107;
}
}
}
}
LEAN_EXPORT lean_object* l_Array_forInUnsafe_loop___at_Lean_Elab_wfRecursion___spec__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11) {
_start:
{
size_t x_12; size_t x_13; lean_object* x_14;
x_12 = lean_unbox_usize(x_2);
lean_dec(x_2);
x_13 = lean_unbox_usize(x_3);
lean_dec(x_3);
x_14 = l_Array_forInUnsafe_loop___at_Lean_Elab_wfRecursion___spec__1(x_1, x_12, x_13, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11);
lean_dec(x_10);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_1);
return x_14;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_wfRecursion___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11;
x_11 = l_Lean_Elab_wfRecursion___lambda__1(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
lean_dec(x_3);
return x_11;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_initFn____x40_Lean_Elab_PreDefinition_WF_Main___hyg_881_(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3;
x_2 = l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6;
x_3 = l_Lean_registerTraceClass(x_2, x_1);
return x_3;
}
}
lean_object* initialize_Init(lean_object*);
lean_object* initialize_Lean_Elab_PreDefinition_Basic(lean_object*);
lean_object* initialize_Lean_Elab_PreDefinition_WF_TerminationHint(lean_object*);
lean_object* initialize_Lean_Elab_PreDefinition_WF_PackDomain(lean_object*);
lean_object* initialize_Lean_Elab_PreDefinition_WF_PackMutual(lean_object*);
lean_object* initialize_Lean_Elab_PreDefinition_WF_Rel(lean_object*);
lean_object* initialize_Lean_Elab_PreDefinition_WF_Fix(lean_object*);
static bool _G_initialized = false;
LEAN_EXPORT lean_object* initialize_Lean_Elab_PreDefinition_WF_Main(lean_object* w) {
lean_object * res;
if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));
_G_initialized = true;
res = initialize_Init(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_PreDefinition_Basic(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_PreDefinition_WF_TerminationHint(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_PreDefinition_WF_PackDomain(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_PreDefinition_WF_PackMutual(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_PreDefinition_WF_Rel(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_PreDefinition_WF_Fix(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___closed__1 = _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___closed__1();
lean_mark_persistent(l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_isOnlyOneUnaryDef___closed__1);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__1 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__1();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__1);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__2 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__2();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__2);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__3 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__3();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__3);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__4);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__5 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__5();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__5);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__6 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__6();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__6);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__7 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__7();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__7);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__8);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__9 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__9();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__9);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__10);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__11 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__11();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__11);
l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12 = _init_l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12();
lean_mark_persistent(l_Lean_Expr_withAppAux___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___spec__1___closed__12);
l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___closed__1 = _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___closed__1();
lean_mark_persistent(l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs_mkSum___closed__1);
l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1___closed__1 = _init_l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1___closed__1();
lean_mark_persistent(l_panic___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__1___closed__1);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___lambda__2___closed__1);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__1 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__1();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__1);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__2 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__2();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__2);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__3 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__3();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__3);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__4 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__4();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__4);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__5 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__5();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__5);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__6);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__7 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__7();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__7);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__8);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__9 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__9();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__9);
l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__10 = _init_l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__10();
lean_mark_persistent(l_Std_Range_forIn_loop___at___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___spec__2___closed__10);
l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__1 = _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__1();
lean_mark_persistent(l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__1);
l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__2 = _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__2();
lean_mark_persistent(l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__2);
l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__3 = _init_l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__3();
lean_mark_persistent(l___private_Lean_Elab_PreDefinition_WF_Main_0__Lean_Elab_addNonRecPreDefs___lambda__1___closed__3);
l_Lean_Elab_wfRecursion___closed__1 = _init_l_Lean_Elab_wfRecursion___closed__1();
lean_mark_persistent(l_Lean_Elab_wfRecursion___closed__1);
l_Lean_Elab_wfRecursion___closed__2 = _init_l_Lean_Elab_wfRecursion___closed__2();
lean_mark_persistent(l_Lean_Elab_wfRecursion___closed__2);
res = l_Lean_Elab_initFn____x40_Lean_Elab_PreDefinition_WF_Main___hyg_881_(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
return lean_io_result_mk_ok(lean_box(0));
}
#ifdef __cplusplus
}
#endif
| 41,125 |
366 | package com.hi.dhl.algorithms.leetcode._258.java;
/**
* <pre>
* author: dhl
* desc : add-digits
* site: https://leetcode.com/problems/add-digits/
*
* Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
* Example:
* Input: 38
* Output: 2
* Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
* Since 2 has only one digit, return it.
* </pre>
*/
public class Solution {
//方法二
public int addDigits(int num) {
if (num == 0) return num;
if (num > 0 && num <= 9) return num;
int sum = 0;
while (num != 0) {
sum = sum + num % 10;
num = num / 10;
}
sum = sum + num % 10;
return addDigits(sum);
}
//方法一
public int addDigits2(int num) {
String builder = String.valueOf(num);
while (builder.length() > 1) {
int sum = 0;
for (int i = 0; i < builder.length(); i++) {
sum += builder.charAt(i) - '0';
}
builder = String.valueOf(sum);
}
return Integer.parseInt(builder);
}
public static void main(String... args) {
int num = 1122;
Solution solution = new Solution();
int sum = solution.addDigits(num);
System.out.println(sum);
}
}
| 660 |
3,102 | #include "macros_top.h"
#undef TOP_REDEF_IN_SUBMODULES
#define TOP_REDEF_IN_SUBMODULES 1
#undef TOP_REDEF_IN_SUBMODULES
#define TOP_REDEF_IN_SUBMODULES 2
| 75 |
1,292 | /*******************************************************************************
* Copyright (c) 2009, 2011 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* <NAME> - initial API and implementation
*
*******************************************************************************/
package org.jacoco.examples;
import java.io.File;
import java.io.IOException;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.analysis.ICoverageVisitor;
import org.jacoco.core.data.ExecutionDataStore;
/**
* This example reads given Java class files, directories or JARs and dumps
* information about the classes.
*/
public class ClassInfo implements ICoverageVisitor {
private final Analyzer analyzer;
private ClassInfo() {
analyzer = new Analyzer(new ExecutionDataStore(), this);
}
private void dumpInfo(final String file) throws IOException {
analyzer.analyzeAll(new File(file));
}
public void visitCoverage(final IClassCoverage coverage) {
System.out.printf("class name: %s%n", coverage.getName());
System.out.printf("class id: %016x%n",
Long.valueOf(coverage.getId()));
System.out.printf("instructions: %s%n", Integer.valueOf(coverage
.getInstructionCounter().getTotalCount()));
System.out.printf("branches: %s%n",
Integer.valueOf(coverage.getBranchCounter().getTotalCount()));
System.out.printf("lines: %s%n",
Integer.valueOf(coverage.getLineCounter().getTotalCount()));
System.out.printf("methods: %s%n",
Integer.valueOf(coverage.getMethodCounter().getTotalCount()));
System.out.printf("complexity: %s%n%n", Integer.valueOf(coverage
.getComplexityCounter().getTotalCount()));
}
/**
* Reads all class file specified as the arguments and dumps information
* about it to <code>stdout</code>.
*
* @param args
* list of class files
* @throws IOException
*/
public static void main(final String[] args) throws IOException {
final ClassInfo info = new ClassInfo();
for (final String file : args) {
info.dumpInfo(file);
}
}
}
| 756 |
5,169 | <filename>Specs/f/d/7/InstantSearchCore/7.0.0-beta.1/InstantSearchCore.podspec.json
{
"name": "InstantSearchCore",
"module_name": "InstantSearchCore",
"version": "7.0.0-beta.1",
"summary": "Instant Search library for Swift by Algolia",
"homepage": "https://github.com/algolia/instantsearch-core-swift",
"license": "Apache 2.0",
"authors": {
"Algolia": "<EMAIL>"
},
"documentation_url": "https://www.algolia.com/doc/guides/building-search-ui/getting-started/ios/",
"platforms": {
"ios": "8.0",
"osx": "10.10",
"watchos": "3.0"
},
"swift_versions": "5.1",
"source": {
"git": "https://github.com/algolia/instantsearch-core-swift.git",
"tag": "7.0.0-beta.1"
},
"source_files": "Sources/InstantSEarchCore/**/*.{swift}",
"dependencies": {
"AlgoliaSearchClientSwift": [
"~> 8.0.0-beta.6"
],
"InstantSearchInsights": [
"~> 2.3"
],
"Logging": [
]
},
"swift_version": "5.1"
}
| 430 |
558 | package skadistats.clarity.processor.reader;
import skadistats.clarity.event.UsagePointMarker;
import skadistats.clarity.event.UsagePointType;
import skadistats.clarity.wire.common.proto.Demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
@UsagePointMarker(value = UsagePointType.EVENT_LISTENER, parameterClasses = { Demo.CDemoFullPacket.class })
public @interface OnFullPacket {
}
| 188 |
864 | #ifndef IIT_TESTIRB4600_JSIM_H_
#define IIT_TESTIRB4600_JSIM_H_
#include <iit/rbd/rbd.h>
#include <iit/rbd/StateDependentMatrix.h>
#include "declarations.h"
#include "transforms.h"
#include "inertia_properties.h"
#include <iit/rbd/robcogen_commons.h>
#include <iit/rbd/traits/DoubleTrait.h>
namespace iit {
namespace testirb4600 {
namespace dyn {
namespace tpl{
/**
* The type of the Joint Space Inertia Matrix (JSIM) of the robot testirb4600.
*/
template <class TRAIT>
class JSIM : public iit::rbd::StateDependentMatrix<iit::testirb4600::JointState, 6, 6, JSIM<TRAIT>>
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
typedef iit::rbd::StateDependentMatrix<iit::testirb4600::JointState, 6, 6, JSIM<TRAIT>> Base;
public:
typedef typename TRAIT::Scalar SCALAR;
typedef typename Base::Index Index;
typedef Eigen::Matrix<SCALAR,6,6> MatrixType;
typedef InertiaProperties<TRAIT> IProperties;
typedef iit::testirb4600::tpl::ForceTransforms<TRAIT> FTransforms;
typedef iit::rbd::tpl::InertiaMatrixDense<SCALAR> InertiaMatrix;
public:
JSIM(IProperties&, FTransforms&);
~JSIM() {}
const JSIM& update(const iit::testirb4600::JointState&);
/**
* Computes and saves the matrix L of the L^T L factorization of this JSIM.
*/
void computeL();
/**
* Computes and saves the inverse of this JSIM.
* This function assumes that computeL() has been called already, since it
* uses L to compute the inverse. The algorithm takes advantage of the branch
* induced sparsity of the robot, if any.
*/
void computeInverse();
/**
* Returns an unmodifiable reference to the matrix L. See also computeL()
*/
const MatrixType& getL() const;
/**
* Returns an unmodifiable reference to the inverse of this JSIM
*/
const MatrixType& getInverse() const;
protected:
/**
* Computes and saves the inverse of the matrix L. See also computeL()
*/
void computeLInverse();
private:
IProperties& linkInertias;
FTransforms* frcTransf;
// The composite-inertia tensor for each link
InertiaMatrix link1_Ic;
InertiaMatrix link2_Ic;
InertiaMatrix link3_Ic;
InertiaMatrix link4_Ic;
InertiaMatrix link5_Ic;
const InertiaMatrix& link6_Ic;
InertiaMatrix Ic_spare;
MatrixType L;
MatrixType Linv;
MatrixType inverse;
};
template <class TRAIT>
inline const typename JSIM<TRAIT>::MatrixType& JSIM<TRAIT>::getL() const {
return L;
}
template <class TRAIT>
inline const typename JSIM<TRAIT>::MatrixType& JSIM<TRAIT>::getInverse() const {
return inverse;
}
} // namespace tpl
typedef tpl::JSIM<rbd::DoubleTrait> JSIM;
}
}
}
#include "jsim.impl.h"
#endif
| 1,303 |
1,330 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.opensymphony.xwork2.factory;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.entities.InterceptorConfig;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.interceptor.WithLazyParams;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
/**
* Default implementation
*/
public class DefaultInterceptorFactory implements InterceptorFactory {
private static final Logger LOG = LogManager.getLogger(DefaultInterceptorFactory.class);
private ObjectFactory objectFactory;
private ReflectionProvider reflectionProvider;
@Inject
public void setObjectFactory(ObjectFactory objectFactory) {
this.objectFactory = objectFactory;
}
@Inject
public void setReflectionProvider(ReflectionProvider reflectionProvider) {
this.reflectionProvider = reflectionProvider;
}
public Interceptor buildInterceptor(InterceptorConfig interceptorConfig, Map<String, String> interceptorRefParams) throws ConfigurationException {
String interceptorClassName = interceptorConfig.getClassName();
Map<String, String> thisInterceptorClassParams = interceptorConfig.getParams();
Map<String, String> params = (thisInterceptorClassParams == null) ? new HashMap<String, String>() : new HashMap<>(thisInterceptorClassParams);
params.putAll(interceptorRefParams);
String message;
Throwable cause;
try {
// interceptor instances are long-lived and used across user sessions, so don't try to pass in any extra context
Object o = objectFactory.buildBean(interceptorClassName, null);
if (o instanceof WithLazyParams) {
LOG.debug("Interceptor {} is marked with interface {} and params will be set during action invocation",
interceptorClassName, WithLazyParams.class.getName());
} else {
reflectionProvider.setProperties(params, o);
}
if (o instanceof Interceptor) {
Interceptor interceptor = (Interceptor) o;
interceptor.init();
return interceptor;
}
throw new ConfigurationException("Class [" + interceptorClassName + "] does not implement Interceptor", interceptorConfig);
} catch (InstantiationException e) {
cause = e;
message = "Unable to instantiate an instance of Interceptor class [" + interceptorClassName + "].";
} catch (IllegalAccessException e) {
cause = e;
message = "IllegalAccessException while attempting to instantiate an instance of Interceptor class [" + interceptorClassName + "].";
} catch (ClassCastException e) {
cause = e;
message = "Class [" + interceptorClassName + "] does not implement com.opensymphony.xwork2.interceptor.Interceptor";
} catch (Exception e) {
cause = e;
message = "Caught Exception while registering Interceptor class " + interceptorClassName;
} catch (NoClassDefFoundError e) {
cause = e;
message = "Could not load class " + interceptorClassName + ". Perhaps it exists but certain dependencies are not available?";
}
throw new ConfigurationException(message, cause, interceptorConfig);
}
}
| 1,488 |
2,151 | // Copyright (C) 2014 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.
#ifndef I18N_ADDRESSINPUT_ONDEMAND_SUPPLIER_H_
#define I18N_ADDRESSINPUT_ONDEMAND_SUPPLIER_H_
#include <libaddressinput/callback.h>
#include <libaddressinput/supplier.h>
#include <map>
#include <memory>
#include <string>
namespace i18n {
namespace addressinput {
class LookupKey;
class Retriever;
class Rule;
class Source;
class Storage;
// An implementation of the Supplier interface that owns a Retriever object,
// through which it loads address metadata as needed, creating Rule objects and
// caching these.
//
// When using an OndemandSupplier, address validation will benefit from address
// metadata server synonym resolution, because the server will be contacted for
// every new LookupKey (ie. every LookupKey that isn't on canonical form and
// isn't already cached).
//
// The maximum size of this cache is naturally limited to the amount of data
// available from the data server. (Currently this is less than 12,000 items of
// in total less than 2 MB of JSON data.)
class OndemandSupplier : public Supplier {
public:
OndemandSupplier(const OndemandSupplier&) = delete;
OndemandSupplier& operator=(const OndemandSupplier&) = delete;
// Takes ownership of |source| and |storage|.
OndemandSupplier(const Source* source, Storage* storage);
~OndemandSupplier() override;
// Loads the metadata needed for |lookup_key|, then calls |supplied|.
void Supply(const LookupKey& lookup_key, const Callback& supplied) override;
// For now, this is identical to Supply.
void SupplyGlobally(const LookupKey& lookup_key,
const Callback& supplied) override;
private:
const std::unique_ptr<const Retriever> retriever_;
std::map<std::string, const Rule*> rule_cache_;
};
} // namespace addressinput
} // namespace i18n
#endif // I18N_ADDRESSINPUT_ONDEMAND_SUPPLIER_H_
| 723 |
23,220 | <gh_stars>1000+
package com.alibaba.otter.canal.client.adapter.hbase.test;
import com.alibaba.otter.canal.client.adapter.hbase.support.HbaseTemplate;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.junit.Test;
public class HBaseConnectionTest {
@Test
public void test01() {
Configuration hbaseConfig = HBaseConfiguration.create();
hbaseConfig.set("hbase.zookeeper.quorum", "127.0.0.1");
hbaseConfig.set("hbase.zookeeper.property.clientPort", "2181");
hbaseConfig.set("zookeeper.znode.parent", "/hbase");
HbaseTemplate hbaseTemplate = new HbaseTemplate(hbaseConfig);
System.out.println(hbaseTemplate.tableExists("ttt"));
}
}
| 290 |
715 | <reponame>iabhimanyu/Algorithms<filename>Dynamic Programming/coin change/cpp/min_coin_change_value.cpp
// Minimum coins needed for a value
#include <bits/stdc++.h>
using namespace std;
int get_change(int m, vector <int> c) {
vector <int> s(m + 1, m);
int n = c.size();
s[0] = 0;
for (int i = 1; i < m + 1; ++i) {
for (int j = 0; j < n; ++j) {
if(i >= c[j] && s[i - c[j]] + 1 < s[i]) {
s[i] = s[i - c[j]] + 1;
}
}
}
return s[m];
}
int main() {
int m, n; cin >> m >> n; // m is the value needed, n is the size of coins array
vector <int> c(n);
for (int i = 0; i < n; ++i) {
cin >> c[i];
}
cout << get_change(m, c);
}
| 306 |
473 | <filename>src/lapack_like/condense/Hessenberg/ApplyQ.hpp
/*
Copyright (c) 2009-2016, <NAME>
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef EL_HESSENBERG_APPLYQ_HPP
#define EL_HESSENBERG_APPLYQ_HPP
namespace El {
namespace hessenberg {
template<typename F>
void ApplyQ
( LeftOrRight side, UpperOrLower uplo, Orientation orientation,
const Matrix<F>& A,
const Matrix<F>& householderScalars,
Matrix<F>& B )
{
EL_DEBUG_CSE
const bool normal = (orientation==NORMAL);
const bool onLeft = (side==LEFT);
const ForwardOrBackward direction = ( normal==onLeft ? BACKWARD : FORWARD );
if( uplo == LOWER )
{
const Conjugation conjugation = ( normal ? UNCONJUGATED : CONJUGATED );
ApplyPackedReflectors
( side, UPPER, HORIZONTAL, direction, conjugation, 1,
A, householderScalars, B );
}
else
{
const Conjugation conjugation = ( normal ? CONJUGATED : UNCONJUGATED );
ApplyPackedReflectors
( side, LOWER, VERTICAL, direction, conjugation, -1,
A, householderScalars, B );
}
}
template<typename F>
void ApplyQ
( LeftOrRight side, UpperOrLower uplo, Orientation orientation,
const AbstractDistMatrix<F>& A,
const AbstractDistMatrix<F>& householderScalars,
AbstractDistMatrix<F>& B )
{
EL_DEBUG_CSE
const bool normal = (orientation==NORMAL);
const bool onLeft = (side==LEFT);
const ForwardOrBackward direction = ( normal==onLeft ? BACKWARD : FORWARD );
if( uplo == LOWER )
{
const Conjugation conjugation = ( normal ? UNCONJUGATED : CONJUGATED );
ApplyPackedReflectors
( side, UPPER, HORIZONTAL, direction, conjugation, 1,
A, householderScalars, B );
}
else
{
const Conjugation conjugation = ( normal ? CONJUGATED : UNCONJUGATED );
ApplyPackedReflectors
( side, LOWER, VERTICAL, direction, conjugation, -1,
A, householderScalars, B );
}
}
} // namespace hessenberg
} // namespace El
#endif // ifndef EL_HESSENBERG_APPLYQ_HPP
| 912 |
419 | #pragma once
#include "Engine/Animation/Graph/Animation_RuntimeGraph_Node.h"
//-------------------------------------------------------------------------
namespace KRG::Animation::GraphNodes
{
class KRG_ENGINE_ANIMATION_API ConstBoolNode final : public BoolValueNode
{
public:
struct KRG_ENGINE_ANIMATION_API Settings final : public BoolValueNode::Settings
{
KRG_REGISTER_TYPE( Settings );
KRG_SERIALIZE_GRAPHNODESETTINGS( BoolValueNode::Settings, m_value );
virtual void InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const override;
bool m_value;
};
private:
virtual void GetValueInternal( GraphContext& context, void* pOutValue ) override;
};
//-------------------------------------------------------------------------
class KRG_ENGINE_ANIMATION_API ConstIDNode final : public IDValueNode
{
public:
struct KRG_ENGINE_ANIMATION_API Settings final : public IDValueNode::Settings
{
KRG_REGISTER_TYPE( Settings );
KRG_SERIALIZE_GRAPHNODESETTINGS( IDValueNode::Settings, m_value );
virtual void InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const override;
StringID m_value;
};
private:
virtual void GetValueInternal( GraphContext& context, void* pOutValue ) override;
};
//-------------------------------------------------------------------------
class KRG_ENGINE_ANIMATION_API ConstIntNode final : public IntValueNode
{
public:
struct KRG_ENGINE_ANIMATION_API Settings final : public IntValueNode::Settings
{
KRG_REGISTER_TYPE( Settings );
KRG_SERIALIZE_GRAPHNODESETTINGS( IntValueNode::Settings, m_value );
virtual void InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const override;
int32 m_value;
};
private:
virtual void GetValueInternal( GraphContext& context, void* pOutValue ) override;
};
//-------------------------------------------------------------------------
class KRG_ENGINE_ANIMATION_API ConstFloatNode final : public FloatValueNode
{
public:
struct KRG_ENGINE_ANIMATION_API Settings final : public FloatValueNode::Settings
{
KRG_REGISTER_TYPE( Settings );
KRG_SERIALIZE_GRAPHNODESETTINGS( FloatValueNode::Settings, m_value );
virtual void InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const override;
float m_value;
};
private:
virtual void GetValueInternal( GraphContext& context, void* pOutValue ) override;
};
//-------------------------------------------------------------------------
class KRG_ENGINE_ANIMATION_API ConstVectorNode final : public VectorValueNode
{
public:
struct KRG_ENGINE_ANIMATION_API Settings final : public VectorValueNode::Settings
{
KRG_REGISTER_TYPE( Settings );
KRG_SERIALIZE_GRAPHNODESETTINGS( VectorValueNode::Settings, m_value );
virtual void InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const override;
Vector m_value;
};
private:
virtual void GetValueInternal( GraphContext& context, void* pOutValue ) override;
};
//-------------------------------------------------------------------------
class KRG_ENGINE_ANIMATION_API ConstTargetNode final : public TargetValueNode
{
public:
struct KRG_ENGINE_ANIMATION_API Settings final : public TargetValueNode::Settings
{
KRG_REGISTER_TYPE( Settings );
KRG_SERIALIZE_GRAPHNODESETTINGS( TargetValueNode::Settings, m_value );
virtual void InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const override;
Target m_value;
};
private:
virtual void GetValueInternal( GraphContext& context, void* pOutValue ) override;
};
} | 1,556 |
1,025 | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file pdGDBOutputReader.cpp
///
//==================================================================================
//------------------------------ pdGDBOutputReader.cpp ------------------------------
// Standard C:
#include <unistd.h>
// std
#include <sstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <future>
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTBaseTools/Include/gtASCIIStringTokenizer.h>
#include <AMDTOSWrappers/Include/osCriticalSectionLocker.h>
#include <AMDTOSWrappers/Include/osDebuggingFunctions.h>
#include <AMDTOSWrappers/Include/osDebugLog.h>
#include <AMDTOSWrappers/Include/osPipeSocket.h>
#include <AMDTOSWrappers/Include/osSystemError.h>
#include <AMDTAPIClasses/Include/Events/apBreakpointHitEvent.h>
#include <AMDTAPIClasses/Include/Events/apDebuggedProcessOutputStringEvent.h>
#include <AMDTAPIClasses/Include/Events/apDebuggedProcessRunResumedEvent.h>
#include <AMDTAPIClasses/Include/Events/apDebuggedProcessRunStartedEvent.h>
#include <AMDTAPIClasses/Include/Events/apDebuggedProcessRunSuspendedEvent.h>
#include <AMDTAPIClasses/Include/Events/apEventsHandler.h>
#include <AMDTAPIClasses/Include/Events/apExceptionEvent.h>
#include <AMDTAPIClasses/Include/Events/apGDBErrorEvent.h>
#include <AMDTAPIClasses/Include/Events/apGDBOutputStringEvent.h>
#include <AMDTAPIClasses/Include/Events/apModuleLoadedEvent.h>
#include <AMDTAPIClasses/Include/Events/apModuleUnloadedEvent.h>
#include <AMDTAPIClasses/Include/Events/apOutputDebugStringEvent.h>
#include <AMDTAPIClasses/Include/Events/apDebuggedProcessTerminatedEvent.h>
#include <AMDTAPIClasses/Include/Events/apThreadCreatedEvent.h>
#include <AMDTApiFunctions/Include/gaGRApiFunctions.h>
#include <AMDTAPIClasses/Include/apExpression.h>
// Local:
#include <src/pdStringConstants.h>
#include <src/pdGDBCommandInfo.h>
#include <src/pdGDBDriver.h>
#include <src/pdGDBOutputReader.h>
#include <AMDTProcessDebugger/Include/pdProcessDebugger.h>
// The length of the gdb printouts aid buffer:
#define PD_GDB_PRINTOUTS_BUFF_LENGTH 4098
// GDB strings:
static const gtASCIIString s_gdbPromtStr = "(gdb)";
static const gtASCIIString s_gdbOperationSuccessStr = "^done";
static const gtASCIIString s_debuggedProcessStoppedMsg = "*stopped";
static const gtASCIIString s_runningThreadMsg = "*running,thread-id=\"";
static const gtASCIIString s_stoppedThreads = "stopped-threads=[\"";
static const gtASCIIString s_debuggedProcessRunningMsg = "*running";
static const gtASCIIString s_exitedGDBStr = "exited";
static const gtASCIIString s_newThreadMsg1 = "~\"[New Thread ";
static const gtASCIIString s_newThreadMsg2 = "=thread-created";
static const gtASCIIString s_newThreadMsg = "~\"[New Thread ";
static const gtASCIIString s_exitingThread = "=thread-exited,id=\"";
static const gtASCIIString s_switchingToThreadMsg = "~\"[Switching to Thread";
static const gtASCIIString s_switchingToProcessMsg = "~\"[Switching to process";
static const gtASCIIString s_switchingToProcessAndThread = " thread ";
// Maximal amount of GDB string printouts:
#define PD_MAX_GDB_STRING_PRINTOUTS 500
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::pdGDBOutputReader
// Description: Constructor.
// Author: <NAME>
// Date: 21/12/2006
// ---------------------------------------------------------------------------
pdGDBOutputReader::pdGDBOutputReader()
: _executedGDBCommandId(PD_GDB_NULL_CMD),
_executedGDBCommandRequiresFlush(false),
_pGDBDriver(NULL),
_pGDBCommunicationPipe(NULL),
_wasDebuggedProcessSuspended(false),
m_didDebuggedProcessReceiveFatalSignal(false),
_wasDebuggedProcessTerminated(false),
_wasDebuggedProcessCreated(false),
_debuggedProcessCurrentThreadGDBId(-1),
_debuggedProcessCurrentThreadId(OS_NO_THREAD_ID),
_isWaitingForInternalDebuggedProcessInterrupt(false),
_isKernelDebuggingAboutToStart(false),
_isKernelDebuggingJustFinished(false),
_currentThreadNumber(-1),
_processId(0),
_findAddress(NULL),
_debuggedExecutableArchitecture(OS_UNKNOWN_ARCHITECTURE),
_amountOfGDBStringPrintouts(0)
{
initMembers();
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::~pdGDBOutputReader
// Description: Destructor.
// Author: <NAME>
// Date: 21/12/2006
// ---------------------------------------------------------------------------
pdGDBOutputReader::~pdGDBOutputReader()
{
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::readGDBOutput
// Description: Does this class work - reads the current GDB output and
// acts accordingly.
// Arguments: gdbCommunicationPipe - The GDB communication pipe.
// pGDBDriver - A GDB driver that can be used to drive GDB and perform additional actions.
// executedGDBCommandId - The last executed GDB command.
// ppGDBOutputData - Will get GDB output data (if relevant to
// the executed GDB command).
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 21/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::readGDBOutput(osPipeSocket& gdbCommunicationPipe, pdGDBDriver& GDBDriver, pdGDBCommandId executedGDBCommandId,
bool& wasDebuggedProcessSuspended, bool& wasDebuggedProcessTerminated, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
// Prevent the GUI main thread and the pdGDBListenerThread from accessing this function at the same time:
osCriticalSectionLocker gdbPipeAccessLocker(m_gdbPipeAccessCS);
// Initialize this class members:
initMembers();
// Clear the output data pointer (if any):
if (ppGDBOutputData != NULL)
{
*ppGDBOutputData = NULL;
}
// Log the executed GDB command:
_executedGDBCommandId = executedGDBCommandId;
_executedGDBCommandRequiresFlush = pdDoesCommandRequireFlush(_executedGDBCommandId);
// Log the GDB driver:
_pGDBDriver = &GDBDriver;
// Log GDB's communication pipe:
_pGDBCommunicationPipe = &gdbCommunicationPipe;
// Read the gdb output:
gtASCIIString gdbOutput;
bool rc3 = readGDBOutput(gdbOutput);
GT_IF_WITH_ASSERT(rc3)
{
// Parse the command results:
bool rc4 = parseGDBOutput(gdbOutput, ppGDBOutputData);
GT_IF_WITH_ASSERT(rc4)
{
retVal = true;
}
}
// If the reading or parsing failed, assume no change was made:
wasDebuggedProcessSuspended = retVal && _wasDebuggedProcessSuspended;
wasDebuggedProcessTerminated = retVal && _wasDebuggedProcessTerminated;
// Register all the events for this command at once. This is done to allow event registration
// observers to use the GDB driver without:
// 1. Causing feedback loops
// 2. Corrupting this class's members (see BUG 356150)
gtPtrVector<apEvent*> eventsToRegister = m_eventsToRegister;
// Clear the events:
m_eventsToRegister.clear();
int numberOfEvents = (int)eventsToRegister.size();
for (int i = 0; numberOfEvents > i; i++)
{
// Register the event:
apEventsHandler::instance().registerPendingDebugEvent(*(eventsToRegister[i]));
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::readGDBOutput
// Description: Reads the current GDB output string.
// Arguments: gdbOutputString - Will get GDB's current output string.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 19/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::readGDBOutput(gtASCIIString& gdbOutputString)
{
bool retVal = false;
// If we are executing a synchronous command:
bool isSyncCommand = isExecutingSynchronousCommand();
if (isSyncCommand)
{
retVal = readSynchronousCommandGDBOutput(gdbOutputString);
}
else
{
retVal = readAsynchronousCommandGDBOutput(gdbOutputString);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::readSynchronousCommandGDBOutput
// Description: Reads GDB output string resulting from the run of a synchronous GDB command.
// Arguments: gdbOutputString - Will GDB's output string.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 21/12/2008
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::readSynchronousCommandGDBOutput(gtASCIIString& gdbOutputString)
{
bool retVal = false;
gdbOutputString.makeEmpty();
bool goOn = true;
if (_wasGDBPrompt)
{
//_wasGDBPrompt = false;
return true;
}
while (goOn)
{
// Read printouts chunk from gdb's output stream:
static char buff[PD_GDB_PRINTOUTS_BUFF_LENGTH];
gtSize_t bytesRead = 0;
bool rc1 = _pGDBCommunicationPipe->readAvailableData(buff, PD_GDB_PRINTOUTS_BUFF_LENGTH, bytesRead);
if (!rc1)
{
GT_ASSERT(rc1);
goOn = false;
}
else
{
// Add the read buffer into the output string:
buff[bytesRead] = 0;
gdbOutputString += buff;
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
gtString dbgMsg;
dbgMsg.fromUtf8String(buff);
dbgMsg.prepend(L"GDB Read sync line row data: ");
OS_OUTPUT_DEBUG_LOG(dbgMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
// If we finished reading all currently available gdb printouts:
if (bytesRead < PD_GDB_PRINTOUTS_BUFF_LENGTH)
{
// Verify that we got the gdb prompt that ends all synchronous commands:
bool gotGDBPrompt = (gdbOutputString.find(s_gdbPromtStr) != -1);
if (gotGDBPrompt)
{
_wasGDBPrompt = true;
if (_executedGDBCommandRequiresFlush)
{
// Uri, 28/12/09 - We add a "\n" to gdb on certain commands that execute slow. This causes the output to be:
// ^done, XXXXXXXX
// XXXXXX
// ...
// (gdb)
// &"\n"
// ^done
// (gdb)
// and would sometimes not be read entirely by the command itself (as this loop might stop on the first (gdb) ).
// The output would then flow over to the next command, causing all sorts of trouble (see Geo Paradigm emails from Nov. - Dec. 2009).
// If we get only one gdb prompt with a &"\n" (echo of the flush string), we wait for another one (in fact, we wait for as many as needed):
static const gtASCIIString flushCommandOutput = "&\"\\n\"";
int numberOfFlushEchoes = gdbOutputString.count(flushCommandOutput);
int numberOfGDBPrompts = gdbOutputString.count(s_gdbPromtStr);
if (((numberOfFlushEchoes + 1) == numberOfGDBPrompts) && (numberOfFlushEchoes > 0))
{
retVal = true;
goOn = false;
}
}
else // !_executedGDBCommandRequiresFlush
{
retVal = true;
goOn = false;
}
}
else // !gotGDBPrompt
{
// If we got the "failed to launch gdb" string:
bool failedToLaunchGDB = (gdbOutputString.find(PD_STR_failedToLaunchGDBASCII) != -1);
if (failedToLaunchGDB)
{
retVal = true;
goOn = false;
}
else // failedToLaunchGDB
{
// Wait 1 millisecond to release the CPU and let gdb output the rest of its output:
osSleep(1);
// Go on for another read loop:
goOn = true;
}
// handleGDBConsoleOutput(gdbOutputString);
}
}
}
}
GetStoppedThreadGDBId(gdbOutputString);
GetRunningThreadGDBId(gdbOutputString);
GT_RETURN_WITH_ASSERT(retVal);
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::readAsynchronousCommandGDBOutput
// Description: Reads the next GDB asynchronous output. Use this function for reading
// GDB outputs of GDB asynchronous commands.
// Arguments: gdbOutputString - Will get GDB's current output line.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 21/12/2008
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::readAsynchronousCommandGDBOutput(gtASCIIString& gdbOutputString)
{
bool retVal = false;
// Read the next GDB output line:
bool rc1 = readGDBOutputLine(gdbOutputString);
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
gtString dbgMsg;
dbgMsg.fromUtf8String(gdbOutputString.asCharArray());
dbgMsg.prepend(L"GDB Read async line row data: ");
OS_OUTPUT_DEBUG_LOG(dbgMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
if (gdbOutputString.find(s_gdbPromtStr) != -1)
{
_wasGDBPrompt = true;
}
if (rc1)
{
retVal = true;
// If the debugged process run was suspended or terminated:
if (gdbOutputString.find(s_debuggedProcessStoppedMsg) != -1)
{
// If we didn't read the "(gdb)" prompt yet:
if (gdbOutputString.find(s_gdbPromtStr) == -1)
{
OS_OUTPUT_DEBUG_LOG(PD_STR_waitingForGDBCommandPrompt, OS_DEBUG_LOG_DEBUG);
// The "(gdb)" prompt is waiting for us in the pipe - read it:
gtASCIIString commandPromptString;
if (gdbOutputString.find("SIGINT"))
{
GetStoppedThreadGDBId(gdbOutputString);
}
}
}
if (gdbOutputString.find("=thread-exited,id=\"") != -1)
{
handleExitThreadMessage(gdbOutputString);
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::readGDBOutputLine
// Description: Reads the next GDB output line.
// Arguments: gdbOutputLine - Will get GDB's current output line.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 21/12/2008
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::readGDBOutputLine(gtASCIIString& gdbOutputLine)
{
bool retVal = false;
gdbOutputLine.makeEmpty();
bool goOn = true;
while (goOn)
{
// A null terminated buffer that will receive the read chars:
static char buff[2];
buff[1] = 0;
// Read one char from GDB's current output:
gtSize_t bytesRead = 0;
bool rc1 = _pGDBCommunicationPipe->readAvailableData(buff, 1, bytesRead);
if (!rc1)
{
GT_ASSERT(rc1);
goOn = false;
}
else
{
// If we finished reading an entire GDB output line (terminated by a new line):
if (buff[0] == '\n')
{
retVal = true;
goOn = false;
}
else
{
// Add the read char into the output string:
gdbOutputLine += buff;
// Go on for another read loop:
goOn = true;
}
}
}
// Check if some thread exited or stopped
GetStoppedThreadGDBId(gdbOutputLine);
// Check if some thread created or start running
GetRunningThreadGDBId(gdbOutputLine);
GT_RETURN_WITH_ASSERT(retVal);
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::parseGDBOutput
// Description:
// Parses an input GDB output string. This string may contain multiple lines.
//
// Arguments: gdbOutputString - The output string to be parsed.
// ppGDBOutputData - Will get GDB output data (if relevant to
// the executed GDB command).
// Return Val: bool - false - iff a GDB error / internal error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::parseGDBOutput(const gtASCIIString& gdbOutputString,
const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
// Output debug log message:
outputParsingGDBOutputLogMessage(_executedGDBCommandId, gdbOutputString);
switch (_executedGDBCommandId)
{
case PD_SET_ENV_VARIABLE_CMD:
{
retVal = gdbOutputString.find("^done") != -1;
}
break;
case PD_GDB_SET_BREAKPOINT_CMD:
{
retVal = handleSetBreakpointOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_CONTINUE_THREAD_CMD:
{
retVal = parseGeneralGDBOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_THREADS_INFO_CMD:
{
// Executing the "get threads info" command:
retVal = handleGetThreadsInfoOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_THREADS_INFO_VIA_MI_CMD:
{
// Executing the "get threads info" command:
retVal = handleGetThreadsInfoViaMachineInterfaceOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_THREAD_INFO_CMD:
{
// Executing the "get thread info" command:
retVal = handleGetThreadInfoOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_CUR_THREAD_CALL_STACK_CMD:
{
// Executing the "get current thread call stack" command:
retVal = handleGetCurrThreadCallStackOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_EXECUTABLE_PID_CMD:
{
// Executing the "get debugged process pid" command:
retVal = handleGetExecutablePidOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_SYMBOL_AT_ADDRESS:
{
// Executing the "get symbol name at address" command:
retVal = handleGetSymbolAtAddressOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_DEBUG_INFO_AT_ADDRESS:
{
bool retValHuman = handleGetDebugHumanInfoAtAddressOutput(gdbOutputString, ppGDBOutputData);
bool retValMachine = handleGetDebugInfoAtAddressOutput(gdbOutputString, ppGDBOutputData);
retVal = retValHuman || retValMachine;
}
break;
case PD_GET_LIBRARY_AT_ADDRESS:
{
retVal = handleGetLibraryAtAddressOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GDB_ABORT_DEBUGGED_PROCESS_CMD:
{
// Executing the "kill" command:
retVal = handleAbortDebuggedProcessOutput(gdbOutputString);
}
break;
case PD_GDB_WAIT_FOR_PROCESS_CMD:
{
retVal = handleWaitingForDebuggedProcessOutput(gdbOutputString);
}
break;
case PD_GDB_SUSPEND_DEBUGGED_PROCESS_CMD:
{
retVal = handleSuspendProcess(gdbOutputString);
}
break;
case PD_GDB_RESUME_DEBUGGED_PROCESS_CMD:
{
retVal = handleResumeProcess(gdbOutputString);
}
break;
case PD_SET_ACTIVE_FRAME_CMD:
{
retVal = handleSwitchToFrame(gdbOutputString);
}
break;
case PD_GET_LOCALS_INFO_CMD:
{
retVal = handleGetLocalsFrame(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_LOCAL_VARIABLE_CMD:
{
retVal = handleGetVariable(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GET_VARIABLE_TYPE_CMD:
{
retVal = handleGetVariableTypeGDBOutput(gdbOutputString, ppGDBOutputData);
}
break;
case PD_GDB_STEP_INTO_CMD:
case PD_GDB_STEP_OVER_CMD:
case PD_GDB_STEP_OUT_CMD:
case PD_GDB_UNTIL_CMD:
{
retVal = handleHostSteps(gdbOutputString, ppGDBOutputData);
}
break;
default:
{
// Executing any other command:
retVal = parseGeneralGDBOutput(gdbOutputString, ppGDBOutputData);
}
break;
}
// Output debug log message:
outputEndedParsingGDBOutputLogMessage(gdbOutputString);
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::parseGeneralGDBOutput
// Description:
// Parses a "general" GDB output string.
// A "general" GDB output is a GDB output that is the result of
// ruuning a GDB command that doe not require specific output parsing.
// This string may contain multiple lines.
//
// Arguments: gdbOutputString - The output string to be parsed.
// ppGDBOutputData - Will get GDB output data (if relevant to
// the executed GDB command).
// Return Val: bool - false - iff a GDB error / internal error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::parseGeneralGDBOutput(const gtASCIIString& gdbOutputString,
const pdGDBData** ppGDBOutputData)
{
(void)(ppGDBOutputData); // unused
bool retVal = true;
// Parse the output line by line:
gtASCIIString currentOutputLine;
int currPos = 0;
int gdbPrintoutsLen = gdbOutputString.length();
while (currPos < gdbPrintoutsLen)
{
currentOutputLine.makeEmpty();
// Search for the current line delimiter:
int lineDelimiterPos = gdbOutputString.find('\n', currPos);
// If we found a line delimiter:
if (lineDelimiterPos != -1)
{
gdbOutputString.getSubString(currPos, lineDelimiterPos, currentOutputLine);
currPos = lineDelimiterPos + 1;
}
else
{
gdbOutputString.getSubString(currPos, gdbPrintoutsLen - 1, currentOutputLine);
currPos = gdbPrintoutsLen;
}
// Parse the current GDB output line:
bool rc = parseGeneralGDBOutputLine(currentOutputLine);
retVal = retVal && rc;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::parseGeneralGDBOutputLine
// Description:
// Parses an input GDB output string. This string may contain multiple lines.
// Arguments: gdbOutputLine - A GDB single output line to be parsed.
// Return Val: bool - false - iff the printout contains a gdb reported error.
// Author: <NAME>
// Date: 19/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::parseGeneralGDBOutputLine(const gtASCIIString& gdbOutputLine)
{
bool retVal = true;
// If under debug log severity, output debug printout:
outputGeneralLineLogMessage(gdbOutputLine);
char outputType = gdbOutputLine[0];
switch (outputType)
{
case '^':
{
retVal = handleGDBResultOutput(gdbOutputLine);
}
break;
case '~':
{
// This is a GDB console output:
retVal = handleGDBConsoleOutput(gdbOutputLine);
}
break;
case '@':
{
// This is a debugged process output:
retVal = handleDebuggedProcessOutput(gdbOutputLine);
}
break;
case '&':
{
// This is a GDB internal output:
retVal = handleGDBInternalOutput(gdbOutputLine);
}
break;
case '*':
{
// This is "execution asynchronous output" notification:
retVal = handleAsynchronousOutput(gdbOutputLine);
}
break;
case '=':
{
// This is "status asynchronous output" notification:
retVal = handleStatusAsynchronousOutput(gdbOutputLine);
}
break;
case '(':
{
// If we got the GDB prompt:
if (gdbOutputLine.startsWith(s_gdbPromtStr))
{
// Nothing to be done.
}
else
{
// Unknown output type:
retVal = handleUnknownGDBOutput(gdbOutputLine);
}
}
break;
default:
{
// The current GDB line does not contain any prefix. This usually happens when
// the debugged process writes outputs.
retVal = handleDebuggedProcessOutput(gdbOutputLine);
}
break;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetThreadsInfoOutput
// Description:
// Parses and handles a GDB output string that is the result of
// an "info threads" GDB command.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 11/1/2007
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetThreadsInfoOutput(const gtASCIIString& gdbOutputString,
const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
// Create a data structure that will hold the threads list:
pdGDBThreadDataList* pThreadsList = new pdGDBThreadDataList;
GT_IF_WITH_ASSERT(pThreadsList != NULL)
{
retVal = true;
// Parse the output line by line:
gtASCIIString currentOutputLine;
int currPos = 0;
int gdbPrintoutsLen = gdbOutputString.length();
while (currPos < gdbPrintoutsLen)
{
currentOutputLine.makeEmpty();
// Search for the current line delimiter:
int lineDelimiterPos = gdbOutputString.find('\n', currPos);
// If we found a line delimiter:
if (lineDelimiterPos != -1)
{
gdbOutputString.getSubString(currPos, lineDelimiterPos, currentOutputLine);
currPos = lineDelimiterPos + 1;
}
else
{
gdbOutputString.getSubString(currPos, gdbPrintoutsLen - 1, currentOutputLine);
currPos = gdbPrintoutsLen;
}
// Parse the current GDB output line:
bool rc3 = handleThreadsInfoLineOutput(currentOutputLine, *pThreadsList);
retVal = retVal && rc3;
}
if (retVal || pThreadsList->_threadsDataList.size())
{
if (ppGDBOutputData != NULL)
{
// Output the threads list:
*ppGDBOutputData = pThreadsList;
retVal = true;
}
}
else
{
// Failure cleanup:
delete pThreadsList;
}
_currentThreadNumber = -1;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleThreadsInfoLineOutput
// Parses and handles a single GDB output line that is the result of
// an "info threads" GDB command.
// Arguments: gdbOutputLine - The GDB output line.
// outputThreadsList - Threads list to be filled up.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 11/1/2007
//
// Implementation notes:
//
// On Linux, An example result of an "info threads" GDB command may be:
// &"info threads\n"
// ~"\n"
// ~" 2 Thread 1084229952 (LWP 3379) "
// ~"* 1 Thread 46912520689776 (LWP 3378) "
// ^done,frame={addr="0x00000030e89097e6",func="pthread_cond_wait@@GLIBC_2.3.2",args=[],from="/lib64/libpthread.so.0"},frame={addr="0x00000030e74c3086",func="poll",args=[],from="/lib64/libc.so.6"}
// (gdb)
//
// On Mac OS X, An example result of an "info threads" GDB command may be:
// ~" 2 process 1671 thread 0x2403 "
// ~"* 1 process 1671 local thread 0x2f33 "
// ^done,frame={addr="0x900a2eee",fp="0xb0122ea4",func="__semwait_signal",args=[]},frame={addr="0x900eb672",fp="0xb00a0d04",func="select$DARWIN_EXTSN"
// ,args=[]},frame={addr="0x00000000",fp="0xbffff074",func="??",args=[]}
// (gdb)
// Furthermore:
// - As of XCode tools 3.1.2 (gdb v 6.3.50 / apple version gdb-962), the format is indeed more machine readable, and is only a single line:
// ^done,threadno="4",target_tid="process 10583 thread 0x5207",frame={addr="0x93ce83ae",fp="0xb01a4ea4",func="__semwait_signal",args=[]},threadno="3",target_tid="process 10583 thread 0x4d07",frame={addr="0x93ce11c6",fp="0xb0122e74",func="mach_msg_trap",args=[]},threadno="2" ...
// (gdb)
// - As of XCode tools 3.2 (comes with Snow Leopard), gdb version 6.3.50-20050815 (Apple version gdb-1344), the format was changed to:
// ^done,threadno="4",target_tid="port# 0x2a03",frame={addr="0x9766a876",fp="0xb0184d20",func="select$DARWIN_EXTSN",args=[]},threadno="3",target_tid="port# 0x1903",frame={addr="0x976711a2",fp="0xb0102f70",func="__workq_kernreturn",args=[]},threadno="2",target_tid="port# 0x1503",frame={addr="0x9767210a",fp="0xb0080d60",func="kevent",args=[]},threadno="1",target_tid="port# 0x903",frame={addr="0x976ac972",fp="0xbffff160",func="__kill",args=[]}
// (gdb)
// - As of XCode tools 3.2.3 (Comes with iPhone SDK 4.0), gdb version 6.3.50-20050815 (Apple version gdb-1469), the above formatted
// output no longer contains thread ids. As a result, we need to use the machine interface command -thread-list-ids, see handleThreadsInfoViaMachineInterfaceLineOutput below.
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleThreadsInfoLineOutput(const gtASCIIString& gdbOutputLine,
pdGDBThreadDataList& outputThreadsList)
{
bool retVal = true;
bool threadDataFound = false;
// Linux / old mac format
static gtASCIIString stat_threadString1("Thread");
static gtASCIIString stat_threadString2("thread");
static gtASCIIString stat_threadString3("port#");
static gtASCIIString stat_threadString4("process");
static gtASCIIString stat_localString("local");
static gtASCIIString stat_starString("*");
static gtASCIIString stat_consultOutputStringPrefix("~");
static gtASCIIString stat_executedCommandEcho;
#if (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)
// New Mac format
static gtASCIIString stat_threadNumberString("threadno");
static gtASCIIString stat_threadTargetThreadIDString("target_tid");
static gtASCIIString stat_threadProcessID("process");
#endif
// Get the executed command echo:
if (stat_executedCommandEcho.isEmpty())
{
const pdGDBCommandInfo* pCommandInfo = pdGetGDBCommandInfo(PD_GET_THREADS_INFO_CMD);
GT_IF_WITH_ASSERT(pCommandInfo != NULL)
{
stat_executedCommandEcho = pCommandInfo->_commandExecutionString;
}
}
// If under debug log severity, output debug log message:
outputThreadLineLogMessage(gdbOutputLine);
// Will get the current line's thread data:
pdGDBThreadData currThreadData;
// Look for "Thread" or "thread" or port#.
// NOTICE: Look for a space after the Thread word, otherwise, a line like this -
// "~ () from /lib64/libpthread.so.0\n"
// (which could be produced by gdb broken line)
// is threated as thread line:
gtASCIIString tmp = stat_threadString1;
tmp.append(" ");
int pos1 = gdbOutputLine.find(tmp);
if (pos1 == -1)
{
tmp = stat_threadString2;
tmp.append(" ");
pos1 = gdbOutputLine.find(tmp);
if (pos1 == -1)
{
tmp = stat_threadString3;
tmp.append(" ");
pos1 = gdbOutputLine.find(tmp);
if (pos1 == -1)
{
tmp = stat_threadString4;
tmp.append(" ");
pos1 = gdbOutputLine.find(tmp);
}
}
}
// If this is a thread related line:
if (pos1 != -1)
{
// If this is not just an echo of the executed GDB command:
if (gdbOutputLine.find(stat_executedCommandEcho) == -1)
{
#if (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)
// Check if this is the new format:
pos1 = gdbOutputLine.find(stat_threadNumberString);
if (pos1 != -1)
{
// If we found at least one "threadno=".." ", this is the new format, which has all the threads in one line
GT_ASSERT(outputThreadsList._threadsDataList.size() == 0);
retVal = true;
threadDataFound = false;
gtASCIIString currentToken1;
gtASCIIStringTokenizer strTokenizer1(gdbOutputLine, ",");
pdGDBThreadData* pCurrentThreadData = NULL;
while (strTokenizer1.getNextToken(currentToken1))
{
if (currentToken1.startsWith(stat_threadNumberString))
{
// Store the previous thread in our list and create a new "thread data":
if (threadDataFound)
{
GT_IF_WITH_ASSERT(pCurrentThreadData != NULL)
{
outputThreadsList._threadsDataList.push_back(*pCurrentThreadData);
delete pCurrentThreadData;
pCurrentThreadData = new pdGDBThreadData;
}
else
{
// We found data, but no thread to match it...
retVal = false;
}
}
else
{
// We only allow this to happen during the first run
GT_IF_WITH_ASSERT(pCurrentThreadData == NULL)
{
pCurrentThreadData = new pdGDBThreadData;
}
else
{
// There is a thread with data we didn't find...
retVal = false;
}
}
// Mark that we don't yet have this thread's data:
threadDataFound = false;
// Make sure we have a thread data to work with:
GT_IF_WITH_ASSERT(pCurrentThreadData != NULL)
{
// Get the thread number (gdb index):
GT_IF_WITH_ASSERT(currentToken1.count('\"') == 2)
{
gtASCIIString threadIndexAsString = currentToken1;
int firstQuotePosition = threadIndexAsString.find('\"');
int secondQuotePosition = threadIndexAsString.find('\"', (firstQuotePosition + 1));
threadIndexAsString.truncate((firstQuotePosition + 1), (secondQuotePosition - 1));
unsigned long threadIndex = 0;
bool rcInd = threadIndexAsString.toUnsignedLongNumber(threadIndex);
GT_IF_WITH_ASSERT(rcInd)
{
pCurrentThreadData->_gdbThreadId = threadIndex;
if ((_currentThreadNumber > 0) && (threadIndex == (unsigned int)_currentThreadNumber))
{
pCurrentThreadData->_isGDBsActiveThread = true;
}
}
}
}
}
else if (currentToken1.startsWith(stat_threadTargetThreadIDString))
{
// Make sure we have exactly two quotation marks:
GT_IF_WITH_ASSERT(currentToken1.count('\"') == 2)
{
bool isLocal = false;
gtASCIIString targetThreadIdInfo = currentToken1;
int firstQuotePosition = targetThreadIdInfo.find('\"');
int secondQuotePosition = targetThreadIdInfo.find('\"', (firstQuotePosition + 1));
targetThreadIdInfo.truncate((firstQuotePosition + 1), (secondQuotePosition - 1));
gtASCIIString currentToken2;
gtASCIIStringTokenizer strTokenizer2(targetThreadIdInfo, " ");
while (strTokenizer2.getNextToken(currentToken2))
{
if (currentToken2.startsWith(stat_threadProcessID))
{
// skip this token and the next one, which is the process id
strTokenizer2.getNextToken(currentToken2);
}
else if (currentToken2.startsWith(stat_localString))
{
// This is a local thread
isLocal = true;
}
else if (currentToken2.startsWith(stat_threadString2) || currentToken2.startsWith(stat_threadString3))
{
// Threads ids marked with "port#" are Mach thread ids:
/*
if (currentToken2.startsWith(stat_threadString3) == true)
{
isLocal = true;
}
*/
// This is the thread number, make sure we got only one:
GT_IF_WITH_ASSERT(!threadDataFound)
{
// Skip to the next token, the actual thread Id:
strTokenizer2.getNextToken(currentToken2);
unsigned long threadOSId = 0;
bool rcNum = currentToken2.toUnsignedLongNumber(threadOSId);
GT_IF_WITH_ASSERT(rcNum)
{
GT_IF_WITH_ASSERT(pCurrentThreadData != NULL)
{
if (isLocal)
{
// Get the thread id in the debugged application address space:
osThreadId applicationThreadId = getThreadIdInDebuggedApplicationAddressSpace(pCurrentThreadData->_gdbThreadId);
GT_ASSERT(applicationThreadId != OS_NO_THREAD_ID);
pCurrentThreadData->_OSThreadId = applicationThreadId;
}
else
{
pCurrentThreadData->_OSThreadId = (osThreadId)threadOSId;
}
}
threadDataFound = true;
}
}
}
else
{
// Unexpected token!
GT_ASSERT_EX(false, L"Unexpected token inside target_tid");
}
}
}
}
else
{
// All other tokens (namely the thread frame and its subtokens) are ignored
}
}
// Store the last thread in our list:
if (threadDataFound)
{
GT_IF_WITH_ASSERT(pCurrentThreadData != NULL)
{
outputThreadsList._threadsDataList.push_back(*pCurrentThreadData);
}
else
{
// We found data, but no thread to match it...
retVal = false;
}
}
else
{
// There is a thread with data we didn't find, or we didn't find any threads at all...
retVal = false;
}
// free up memory
delete pCurrentThreadData;
pCurrentThreadData = NULL;
// Reset the "found thread data" flag, so we don't push back the same thread twice by accident:
threadDataFound = false;
}
else
#endif // Mac only
{
// This is the Linux / old Mac format(s), thus this line describes only one thread.
// Parse the string token by token:
int tokenIndex = 0;
int threadOSIdTokenIndex = -1;
int localTokenIndex = -1;
gtASCIIString currToken;
gtASCIIStringTokenizer strTokenizer(gdbOutputLine, " ");
while (strTokenizer.getNextToken(currToken))
{
// If the current token contains "*":
if (currToken.find(stat_starString) != -1)
{
// "*" marks GDB's active thread:
currThreadData._isGDBsActiveThread = true;
}
else if (currToken.startsWith(stat_consultOutputStringPrefix))
{
// "~" prefixes are ignored.
}
else
{
if (tokenIndex == 0)
{
// Read the thread's GDB id:
int threadGDBId = 0;
bool rc1 = currToken.toIntNumber(threadGDBId);
GT_IF_WITH_ASSERT(rc1)
{
currThreadData._gdbThreadId = threadGDBId;
threadDataFound = true;
}
else
{
retVal = false;
}
}
else if (tokenIndex == threadOSIdTokenIndex)
{
// Read the thread's OS id:
unsigned long threadOSId = 0;
bool rc2 = currToken.toUnsignedLongNumber(threadOSId);
GT_IF_WITH_ASSERT(rc2)
{
// If this is a "local" thread id:
if (localTokenIndex == (tokenIndex - 2))
{
// Get the thread id in the debugged application address space:
osThreadId applicationThreadId = getThreadIdInDebuggedApplicationAddressSpace(currThreadData._gdbThreadId);
GT_ASSERT(applicationThreadId == OS_NO_THREAD_ID);
currThreadData._OSThreadId = applicationThreadId;
}
else
{
currThreadData._OSThreadId = threadOSId;
}
// We are done parsing this line:
break;
}
else
{
retVal = false;
}
}
else if ((currToken == stat_threadString1) || (currToken == stat_threadString2) || (currToken == stat_threadString3) || (currToken == stat_threadString4))
{
// If the current token is "Thread" or "thread", the next token is the OS thread id:
threadOSIdTokenIndex = tokenIndex + 1;
}
else if (currToken == stat_localString)
{
// This is part of a "local thread" string that tells us that the thread id is given in local GDB address space:
localTokenIndex = tokenIndex;
}
// Next token index:
tokenIndex++;
}
}
}
}
}
if (retVal && threadDataFound)
{
// Output the current line's thread data:
if (!outputThreadsList._threadsDataList.empty())
{
if (outputThreadsList._threadsDataList.front()._gdbThreadId > currThreadData._gdbThreadId)
{
outputThreadsList._threadsDataList.push_front(currThreadData);
}
else
{
outputThreadsList._threadsDataList.push_back(currThreadData);
}
}
else
{
outputThreadsList._threadsDataList.push_front(currThreadData);
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetThreadsInfoViaMachineInterfaceOutput
// Description:
// Parses and handles a GDB output string that is the result of
// an "-thread-list-ids" GDB command.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 18/7/2010
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetThreadsInfoViaMachineInterfaceOutput(const gtASCIIString& gdbOutputString,
const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
// Create a data structure that will hold the threads list:
pdGDBThreadDataList* pThreadsList = new pdGDBThreadDataList;
GT_IF_WITH_ASSERT(pThreadsList != NULL)
{
retVal = true;
// Parse the output line by line:
gtASCIIString currentOutputLine;
int currPos = 0;
int gdbPrintoutsLen = gdbOutputString.length();
while (currPos < gdbPrintoutsLen)
{
currentOutputLine.makeEmpty();
// Search for the current line delimiter:
int lineDelimiterPos = gdbOutputString.find('\n', currPos);
// If we found a line delimiter:
if (lineDelimiterPos != -1)
{
gdbOutputString.getSubString(currPos, lineDelimiterPos, currentOutputLine);
currPos = lineDelimiterPos + 1;
}
else
{
gdbOutputString.getSubString(currPos, gdbPrintoutsLen - 1, currentOutputLine);
currPos = gdbPrintoutsLen;
}
// Parse the current GDB output line:
bool rc3 = handleThreadsInfoViaMachineInterfaceLineOutput(currentOutputLine, *pThreadsList);
retVal = retVal && rc3;
}
if (retVal)
{
if (ppGDBOutputData != NULL)
{
// Output the threads list:
*ppGDBOutputData = pThreadsList;
}
}
else
{
// Failure cleanup:
delete pThreadsList;
}
_currentThreadNumber = -1;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleThreadsInfoViaMachineInterfaceLineOutput
// Parses and handles a single GDB output line that is the result of
// an "-thread-list-ids" GDB command.
// Arguments: gdbOutputLine - The GDB output line.
// outputThreadsList - Threads list to be filled up.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 15/7/2010
//
// Implementation notes:
//
// On Mac OS X, An example result of an "info threads" GDB command may be:
// ^done,thread-ids={thread-id="3",thread-id="2",thread-id="1"},number-of-threads="3",threads=[thread={thread-id="3",state="WAITING",mach-port-number="0x1f03",pthread-id="0x1005c1000",unique-id="0x644c"},thread={thread-id="2", ...}],time={wallclock="0.00106",user="0.00041",system="0.00064",start="1279211248.950793",end="1279211248.951850"}
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleThreadsInfoViaMachineInterfaceLineOutput(const gtASCIIString& gdbOutputLine,
pdGDBThreadDataList& outputThreadsList)
{
bool retVal = false;
static const gtASCIIString stat_threadsDataStart("threads=[");
static const gtASCIIString stat_threadsDataEnd("]");
static const int stat_threadsDataPrefixLength = stat_threadsDataStart.length();
static const int stat_threadsDataSuffixLength = stat_threadsDataEnd.length();
static const gtASCIIString stat_threadDataStart("thread={");
static const gtASCIIString stat_threadDataEnd("}");
static const int stat_threadDataPrefixLength = stat_threadDataStart.length();
static const int stat_threadDataSuffixLength = stat_threadDataEnd.length();
static const gtASCIIString start_threadIndexTokenStart("thread-id=\"");
static const gtASCIIString start_threadMachPortNumberTokenStart("mach-port-number=\"");
static const gtASCIIString start_threadLocalTokenStart("local");
// If under debug log severity, output debug log message:
outputThreadLineLogMessage(gdbOutputLine);
// Find the threads data delimiters:
int threadsDataStart = gdbOutputLine.find(stat_threadsDataStart);
int threadsDataEnd = gdbOutputLine.find(stat_threadsDataEnd, threadsDataStart);
if ((threadsDataStart != -1) || (threadsDataEnd != -1))
{
GT_IF_WITH_ASSERT((threadsDataStart > -1) && (threadsDataEnd > threadsDataStart))
{
// Get only the threads data itself:
gtASCIIString threadsData;
gdbOutputLine.getSubString(threadsDataStart + stat_threadsDataPrefixLength, threadsDataEnd - stat_threadsDataSuffixLength, threadsData);
GT_IF_WITH_ASSERT(!threadsData.isEmpty())
{
GT_ASSERT(outputThreadsList._threadsDataList.size() == 0);
retVal = true;
// Find the first thread's Data:
int currentThreadDataStart = threadsData.find(stat_threadDataStart);
int currentThreadDataEnd = threadsData.find(stat_threadDataEnd, currentThreadDataStart);
pdGDBThreadData* pCurrentThreadData = NULL;
// While we get more threads' data:
while ((currentThreadDataStart > -1) && (currentThreadDataEnd > currentThreadDataStart))
{
// Get the current thread's data:
bool threadDataFound = false;
gtASCIIString currentThreadData;
threadsData.getSubString(currentThreadDataStart + stat_threadDataPrefixLength, currentThreadDataEnd - stat_threadDataSuffixLength, currentThreadData);
GT_IF_WITH_ASSERT(!currentThreadData.isEmpty())
{
// Tokenize by commas, each field will be shown as name="value":
gtASCIIString threadDataToken;
gtASCIIStringTokenizer threadDataStrTokenizer(currentThreadData, ",");
pCurrentThreadData = new pdGDBThreadData;
bool isThreadNumberLocal = false;
while (threadDataStrTokenizer.getNextToken(threadDataToken))
{
// See which field is this:
if (threadDataToken.startsWith(start_threadIndexTokenStart))
{
// This is the (gdb) thread index, labelled "thread-id":
gtASCIIString threadIndexAsString;
GT_ASSERT(threadDataToken.count('\"') == 2);
int firstQuote = threadDataToken.find('\"');
int lastQuote = threadDataToken.reverseFind('\"');
threadDataToken.getSubString(firstQuote + 1, lastQuote - 1, threadIndexAsString);
// If the index is a number:
unsigned long threadIndex = 0;
bool rcInd = threadIndexAsString.toUnsignedLongNumber(threadIndex);
GT_IF_WITH_ASSERT(rcInd)
{
// Store it:
pCurrentThreadData->_gdbThreadId = threadIndex;
if ((_currentThreadNumber > 0) && (threadIndex == (unsigned int)_currentThreadNumber))
{
pCurrentThreadData->_isGDBsActiveThread = true;
}
}
}
else if (threadDataToken.startsWith(start_threadMachPortNumberTokenStart))
{
// This is the thread OS id (mach port #), labelled "mach-port-number":
gtASCIIString machPortNumberAsString;
GT_ASSERT(threadDataToken.count('\"') == 2);
int firstQuote = threadDataToken.find('\"');
int lastQuote = threadDataToken.reverseFind('\"');
threadDataToken.getSubString(firstQuote + 1, lastQuote - 1, machPortNumberAsString);
// If the port number is a number:
unsigned long machPortNumberAsULong = 0;
bool rcNum = machPortNumberAsString.toUnsignedLongNumber(machPortNumberAsULong);
GT_IF_WITH_ASSERT(rcNum)
{
// Store it:
osThreadId machPortNumber = (osThreadId)machPortNumberAsULong;
GT_ASSERT(machPortNumber != OS_NO_THREAD_ID);
pCurrentThreadData->_OSThreadId = machPortNumber;
threadDataFound = true;
// Avoid getting the thread ID twice:
isThreadNumberLocal = false;
}
}
else if (threadDataToken.startsWith(start_threadLocalTokenStart))
{
// This is a local thread id, note that we got SOME thread id, but we need to get the mach port from gdb:
if (!threadDataFound)
{
isThreadNumberLocal = true;
}
}
else
{
// Ignore other fields, they are irrelevant to us.
}
}
// If we only found a local id, get the global one from gdb:
if (isThreadNumberLocal)
{
// Get the thread id in the debugged application address space:
osThreadId applicationThreadId = getThreadIdInDebuggedApplicationAddressSpace(pCurrentThreadData->_gdbThreadId);
GT_IF_WITH_ASSERT(applicationThreadId != OS_NO_THREAD_ID)
{
pCurrentThreadData->_OSThreadId = applicationThreadId;
threadDataFound = true;
}
}
// Threads with no ids do not interest us:
if (threadDataFound)
{
outputThreadsList._threadsDataList.push_back(*pCurrentThreadData);
}
// Free up memory
delete pCurrentThreadData;
pCurrentThreadData = NULL;
}
// Get the next thread's data:
currentThreadDataStart = threadsData.find(stat_threadDataStart, currentThreadDataEnd);
currentThreadDataEnd = threadsData.find(stat_threadDataEnd, currentThreadDataStart);
// We take >= here for the case where both values are -1 (i.e. no threads data)
GT_ASSERT(currentThreadDataEnd >= currentThreadDataStart);
}
}
}
}
else // ((threadsDataStart == -1) && (threadsDataEnd == -1))
{
// This is the gdb prompt or a command echo:
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::getThreadIdInDebuggedApplicationAddressSpace
// Description: Inputs a GDB thread id and returns the thread OS id in the
// debugged application address space, or OS_NO_THREAD_ID in case of failure.
// Author: <NAME>
// Date: 23/12/2008
// Implementation notes:
// Under Mac OS X, GDB sometimes outputs thread ids as ~"2 process 1671 local thread 0x2f33" which
// means that GDB's output thread id is the Mach threads id under the GDB address space. However, we
// need the Mach thread id under the debugged process address space. This function enables getting
// the thread id under the debugged process address space.
// ---------------------------------------------------------------------------
osThreadId pdGDBOutputReader::getThreadIdInDebuggedApplicationAddressSpace(int gdbThreadId) const
{
osThreadId retVal = OS_NO_THREAD_ID;
// This functionality is relevant to Mac OS X only:
//#if AMDT_BUILD_TARGET == AMDT_MAC_OS_X_LINUX_VARIANT
{
gtASCIIString commandArguments;
commandArguments.appendFormattedString("%d", gdbThreadId);
const pdGDBData* pGDBOutputData = NULL;
bool rc1 = _pGDBDriver->executeGDBCommand(PD_GET_THREAD_INFO_CMD, commandArguments, &pGDBOutputData);
GT_IF_WITH_ASSERT(rc1 && (pGDBOutputData != NULL))
{
// Sanity check:
GT_IF_WITH_ASSERT(pGDBOutputData->type() == pdGDBData::PD_GDB_THREAD_DATA)
{
// Downcast the result to thread data:
const pdGDBThreadData* pThreadData = (const pdGDBThreadData*)pGDBOutputData;
// Output the thread's OS id given in the debugged process address space:
retVal = pThreadData->_OSThreadId;
}
}
}
//#else
// {
// // This functionality should not be reached under none-Mac OS X platforms!
// GT_ASSERT(false);
// }
//#endif
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetThreadInfoOutput
// Description:
// Parses and handles a GDB output string that is the result of an "info thread" GDB command.
// Arguments: gdbOutputString - The GDB output for the "info thread" command.
// ppGDBOutputData - Will get the queried thread information.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 24/12/2008
// Implementation notes:
// The "info thread" command has the following output format:
// ~"Thread 0x813 (local 0x2f3b) has current state \"WAITING\"\n"
// ~"Thread 0x813 has a suspend count of 0.\n"</p>
//
// As of XCode tools 3.2 (comes with Snow Leopard), gdb version 6.3.50-20050815 (Apple version gdb-1344), the format was changed to:
// ~"Thread 2 has current state \"WAITING\"\n"
// ~"\tMach port #0x1503 (gdb port #0x4833)\n"
// ~"\tframe 0: "
// ~"\tpthread ID: 0xb0081000\n"
// ~"\tsystem-wide unique thread id: 0x2af5\n"
// ~"\ttotal user time: 0x29fe0\n"
// ~"\ttotal system time: 0x4ca90\n"
// ~"\tscaled cpu usage percentage: 0\n"
// ~"\tscheduling policy in effect: 0x1\n"
// ~"\trun state: 0x3 (WAITING)\n"
// ~"\tflags: 0x1 (SWAPPED)\n"
// ~"\tnumber of seconds that thread has slept: 0\n"
// ~"\tcurrent priority: 31\n"
// ~"\tmax priority: 63\n"
// ~"\tsuspend count: 0.\n"
// ^done,frame={addr="0x976711a2",fp="0xb0080f70",func="__workq_kernreturn",args=[]}
// (gdb)
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetThreadInfoOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
static gtASCIIString stat_threadOSIdPrefix1 = "~\"Thread";
static gtASCIIString stat_threadOSIdPrefix2 = "Mach port #";
static int stat_threadOSIdPrefix1Length = stat_threadOSIdPrefix1.length();
static int stat_threadOSIdPrefix2Length = stat_threadOSIdPrefix2.length();
int threadIdPrefixLength = 0;
gtASCIIString threadIdSuffix;
// If the current line contains the thread's OS id in format 2:
int pos1 = gdbOutputString.find(stat_threadOSIdPrefix2);
GetStoppedThreadGDBId(gdbOutputString);
if (pos1 != -1)
{
threadIdPrefixLength = stat_threadOSIdPrefix2Length;
threadIdSuffix = " ";
}
else
{
// If the current line contains the thread's OS id in format 1:
pos1 = gdbOutputString.find(stat_threadOSIdPrefix1);
if (pos1 != -1)
{
threadIdPrefixLength = stat_threadOSIdPrefix1Length;
threadIdSuffix = " ";
}
}
// If we found the thread id's perfix:
if (pos1 != -1)
{
// Calculate the place where the thread's pthread id begin:
int pos2 = pos1 + threadIdPrefixLength + 1;
// Search for the suffic that is located after the thread's OS id:
int pos3 = gdbOutputString.find(threadIdSuffix, pos2);
GT_IF_WITH_ASSERT(pos3 != -1)
{
// Get the thread's OS id as a string:
gtASCIIString threadOSIdString;
gdbOutputString.getSubString(pos2, pos3 - 1, threadOSIdString);
// Translate it to an unsigned long:
unsigned long threadOSId = 0;
bool rc1 = threadOSIdString.toUnsignedLongNumber(threadOSId);
GT_IF_WITH_ASSERT(rc1)
{
// Create an output structure:
pdGDBThreadData* pOutputStruct = new pdGDBThreadData;
GT_IF_WITH_ASSERT(pOutputStruct != NULL)
{
// Output the queried thread id:
pOutputStruct->_OSThreadId = threadOSId;
if (ppGDBOutputData != NULL)
{
*ppGDBOutputData = pOutputStruct;
}
retVal = true;
}
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetCurrThreadCallStackOutput
// Description:
// Parses and handles a GDB output string that is the result of
// an "get current thread call stack" GDB command.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 14/3/2007
// Implementation notes:
// The call stack data format is similar to the below example:
// stack=[frame={level="0",addr="0x00000030e74c3086",func="poll",from="/lib64/libc.so.6"},
// frame={level="1",addr="0x00002aaaab801e99",func="wxapp_poll_func",file="../src/gtk/app.cpp",line="332"}]
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetCurrThreadCallStackOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
static gtASCIIString gdbStackPerfix = "stack=";
static gtASCIIString gdbFramePerfix = "frame=";
static int gdbFramePerfixSize = gdbFramePerfix.length();
// If under debug log severity, output debug printout:
outputCallStackLogMessage(gdbOutputString);
GetStoppedThreadGDBId(gdbOutputString);
// Sanity check - verify that the input contains the stack prefix:
int stackDataLoc = gdbOutputString.find(gdbStackPerfix) ;
if (stackDataLoc != -1)
{
// Allocate the output struct:
pdGDBCallStack* pReadCallStack = new pdGDBCallStack;
GT_IF_WITH_ASSERT(pReadCallStack)
{
retVal = true;
// Look for the first frame data:
int searchStartPos = stackDataLoc + gdbStackPerfix.length();
int currFramePos = gdbOutputString.find(gdbFramePerfix, searchStartPos);
// While there are frames that we didn't parse:
while (currFramePos != -1)
{
// Look for the frame opening bracket:
int openingBracketPos = gdbOutputString.find('{', currFramePos);
GT_IF_WITH_ASSERT(openingBracketPos != -1)
{
// Look for the frame closing bracket:
int closingBracketPos = gdbOutputString.find('}', openingBracketPos);
GT_IF_WITH_ASSERT(closingBracketPos != -1)
{
// Get the frame data string:
gtASCIIString frameDataString;
gdbOutputString.getSubString(openingBracketPos + 1, closingBracketPos - 1, frameDataString);
// Add the current frame data to the call stack:
bool rc1 = addFrameDataToCallStack(frameDataString, pReadCallStack->_callStack);
GT_ASSERT(rc1);
}
}
// Look for the next frame data:
currFramePos = gdbOutputString.find(gdbFramePerfix, currFramePos + gdbFramePerfixSize);
}
// If all went well - output the call stack:
if (retVal && (ppGDBOutputData != NULL))
{
*ppGDBOutputData = pReadCallStack;
}
else
{
// Failure clean up:
delete pReadCallStack;
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetExecutablePidOutput
// Description:
// Parses and handles a GDB output string that is the result of
// a "get executable pid" GDB command.
// Arguments: gdbOutputLine - The GDB output line.
// ppGDBOutputData - Will get the executable pid.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 29/8/2007
// Implementation notes:
// The output of the GDB "info proc" command format is similar to the below example:
// &"info proc\n"
// ~"process 592\n"
// ~"cmdline = '/home/yaki/work/driveo/debug/bin/CodeXL-bin'\n"
// ~"cwd = '/home/yaki/work/driveo/debug/bin/examples/teapot'\n"
// ~"exe = '/home/yaki/work/driveo/debug/bin/CodeXL-bin'\n"
// ^done
// (gdb)
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetExecutablePidOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
static gtASCIIString gdbProcessIdPerfix = "process ";
static int gdbProcessIdPerfixLen = gdbProcessIdPerfix.length();
// Find the process id prefix:
int pos1 = gdbOutputString.find(gdbProcessIdPerfix) ;
if (pos1 != -1)
{
// Read the process id:
int pos2 = pos1 + gdbProcessIdPerfixLen;
long processId = 0;
const char* pProcessIdStr = gdbOutputString.asCharArray() + pos2;
int rc1 = sscanf(pProcessIdStr, "%ld", &processId);
GT_IF_WITH_ASSERT(rc1 == 1)
{
// Allocate the output struct:
pdGDBProcessId* pProcessIdStruct = new pdGDBProcessId;
GT_IF_WITH_ASSERT(pProcessIdStruct != NULL)
{
// Output the process id:
pProcessIdStruct->_processPid = processId;
if (ppGDBOutputData != NULL)
{
*ppGDBOutputData = pProcessIdStruct;
}
retVal = true;
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetSymbolAtAddressOutput
// Description:
// Parses and handles a GDB output string that is the result of
// a "get symbol name at address" GDB command.
//
// Arguments: gdbOutputLine - The GDB output line.
// ppGDBOutputData - Will get the name of the symbol that resides under the input address.
//
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 9/1/2008
// Implementation notes:
// The output of the GDB "info symbol" command format is similar to the below example:
// info symbol 0x2aaaaab1c146
// &"info symbol 0x2aaaaab1c146\n"
// ~"gaUpdateCurrentThreadTextureRawDataStub() in section .text\n"
// ^done
// (gdb)
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetSymbolAtAddressOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
static gtASCIIString stat_startSymbolPrefix = "\"";
static int stat_startSymbolPrefixLen = stat_startSymbolPrefix.length();
static gtASCIIString stat_endSymbolSuffix = "in section";
// Find the symbol suffix:
int pos3 = gdbOutputString.find(stat_endSymbolSuffix);
GT_IF_WITH_ASSERT(pos3 != -1)
{
// Find the start symbol prefix:
int pos1 = gdbOutputString.reverseFind(stat_startSymbolPrefix, pos3);
GT_IF_WITH_ASSERT(pos1 != -1)
{
// Calculate the first symbol char position:
int pos2 = pos1 + stat_startSymbolPrefixLen;
// Calculate the last symbol char position:
int pos4 = pos3 - 2;
// The symbol is sometimes prefixed with few spaces - if so, the symbol start position
// should reside after these spaces:
int pos5 = gdbOutputString.reverseFind(" ", pos4);
if (pos2 <= pos5)
{
pos2 = pos5 + 1;
}
// Sanity check:
GT_IF_WITH_ASSERT(pos2 < pos4)
{
// Get the symbol name:
gtASCIIString symbolName;
gdbOutputString.getSubString(pos2, pos4, symbolName);
// Create a structure that will contain the output symbol name:
pdGDBStringData* pStringOutputStruct = new pdGDBStringData(symbolName);
GT_IF_WITH_ASSERT(pStringOutputStruct != NULL)
{
if (ppGDBOutputData != NULL)
{
*ppGDBOutputData = pStringOutputStruct;
}
retVal = true;
}
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetDebugInfoAtAddressOutput
// Description: Handles the output of the "info line" commands human format. The commands we
// issue are solely of the form "info line *0xfeedface", which gives the debug info of the address.
// The answer is human readable with the following format:
// ~"Line 2027 of \"Examples/AMDTTeaPot/AMDTTeaPotLib/src/AMDTTeapotOCLSmokeSystem.cpp\" starts at address 0x41d384 <AMDTTeapotOCLSmokeSystem::compute(AMDTTeapotRenderState const&, Mat4 const&, float, float)+2344> and ends at 0x41d3f6 <AMDTTeapotOCLSmokeSystem::compute(AMDTTeapotRenderState const&, Mat4 const&, float, float)+2458>.\n"
// since it is implementation-dependant, we instead use the uniform
// output, which is supplied by running gdb with the --fullname switch.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 12/11/2012
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetDebugHumanInfoAtAddressOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
static const gtASCIIString debugInformationReadableLineStart = "~\"Line ";
static const gtASCIIString debugInformationReadableNumberEnd = " of \\\"";
static const gtASCIIString debugInformationReadableSourceEnd = "\\\"";
// Find the different section of the string:
int readableLineStart = gdbOutputString.find(debugInformationReadableLineStart);
if (readableLineStart > -1)
{
int readableLineNumberEnd = gdbOutputString.find(debugInformationReadableNumberEnd, readableLineStart);
GT_IF_WITH_ASSERT(readableLineNumberEnd > readableLineStart)
{
int readableSourceEnd = gdbOutputString.find(debugInformationReadableSourceEnd, readableLineNumberEnd + debugInformationReadableNumberEnd.length());
GT_IF_WITH_ASSERT(readableSourceEnd > readableLineNumberEnd)
{
// parse the different sections:
gtASCIIString filePathAsString, lineNumberAsString;
unsigned int lineNumber = 0;
gdbOutputString.getSubString((readableLineStart + debugInformationReadableLineStart.length()), (readableLineNumberEnd - 1), lineNumberAsString);
gdbOutputString.getSubString((readableLineNumberEnd + debugInformationReadableNumberEnd.length()), (readableSourceEnd - 1), filePathAsString);
bool rcNum = lineNumberAsString.toUnsignedIntNumber(lineNumber);
GT_IF_WITH_ASSERT(rcNum)
{
gtString filePathAsUnicodeString;
filePathAsUnicodeString.fromASCIIString(filePathAsString.asCharArray());
osFilePath filePath(filePathAsUnicodeString);
if (ppGDBOutputData != NULL)
{
pdGDBSourceCodeData* pSourceCodeData = new pdGDBSourceCodeData(filePath, lineNumber);
if (ppGDBOutputData != NULL)
{
*ppGDBOutputData = pSourceCodeData;
}
retVal = true;
}
}
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetDebugInfoAtAddressOutput
// Description: Handles the output of the "info line" commands machine format. The commands we
// issue are solely of the form "info line *0xfeedface", which gives
// the debug info of the address. The answer is human readable, but
// since it is implementation-dependant, we instead use the uniform
// output, which is supplied by running gdb with the --fullname switch.
// this output begins with two \032 characters, followed by a colon
// separated list of: full source code file path, line number(1-based),
// character number (0-based from the start of the file), and further
// information which is irrelevant to us and doesn't appear in all
// implementations
// ~"\032\032/home/jdoe/myFolder/myProject/src/mySource.cpp:42:1337\n"
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 17/2/2009
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetDebugInfoAtAddressOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
static const gtASCIIString debugInformationReadableLineStart = "~\"\\032\\032";
static const gtASCIIString debugInformationReadableLineEnd = "\\n\"";
int readableLineStart = gdbOutputString.find(debugInformationReadableLineStart);
if (readableLineStart > -1)
{
int readableLineEnd = gdbOutputString.find(debugInformationReadableLineEnd, readableLineStart);
GT_IF_WITH_ASSERT(readableLineEnd > readableLineStart)
{
gtASCIIString readableLine;
gdbOutputString.getSubString((readableLineStart + debugInformationReadableLineStart.length()), (readableLineEnd + 1), readableLine);
GT_IF_WITH_ASSERT(readableLine.count(':') >= 2)
{
int firstColonPosition = readableLine.find(':');
int secondColonPosition = readableLine.find(':', (firstColonPosition + 1));
if (secondColonPosition == -1)
{
secondColonPosition = readableLine.length();
}
GT_IF_WITH_ASSERT(secondColonPosition > (firstColonPosition + 1))
{
gtASCIIString filePathAsString, lineNumberAsString;
unsigned int lineNumber = 0;
readableLine.getSubString(0, (firstColonPosition - 1), filePathAsString);
readableLine.getSubString((firstColonPosition + 1), (secondColonPosition - 1), lineNumberAsString);
bool rcNum = lineNumberAsString.toUnsignedIntNumber(lineNumber);
GT_IF_WITH_ASSERT(rcNum)
{
gtString filePathAsUnicodeString;
filePathAsUnicodeString.fromASCIIString(filePathAsString.asCharArray());
osFilePath filePath(filePathAsUnicodeString);
GT_IF_WITH_ASSERT(filePath.isRegularFile())
{
if (ppGDBOutputData != NULL)
{
pdGDBSourceCodeData* pSourceCodeData = new pdGDBSourceCodeData(filePath, lineNumber);
GT_IF_WITH_ASSERT(pSourceCodeData != NULL)
{
if (ppGDBOutputData != NULL)
{
// If data was created by human format release it since it might not be with full path:
if (NULL != *ppGDBOutputData)
{
delete(*ppGDBOutputData);
}
*ppGDBOutputData = pSourceCodeData;
}
retVal = true;
}
}
else
{
retVal = true;
}
}
}
}
}
}
}
else
{
// We didn't find the line we looked for, this probably means the address has no debug information:
if ((ppGDBOutputData != NULL) && (*ppGDBOutputData == NULL))
{
pdGDBSourceCodeData* pSourceCodeData = new pdGDBSourceCodeData(osFilePath(), 0);
*ppGDBOutputData = pSourceCodeData;
}
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGetLibraryAtAddressOutput
// Description: Handles the output from the "info sharedlibrary 0xfeedface" function
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 22/2/2009
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGetLibraryAtAddressOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool retVal = false;
pdGDBLibraryData* pLibraryInfo = new pdGDBLibraryData();
// The "info sharedlibrary" has a different implementation on Mac, so we use it otherwise.
static const gtASCIIString macOutputIdentifier = ",shlib-info=";
if (gdbOutputString.find(macOutputIdentifier) >= 0)
{
// On Mac, the output is machine-readable, starts with ^done, and continues with the shared library
// information as displayed when reading the output from the command with no address specified.
// this output starts with 'shlib-info=[num="42",name="myLib.dylib",kind=...' and has somewhere in
// the rest of the output a 'path="/myFolder/bin/myLib.dylib"' field.
// Make sure we only got one shared library as a result:
GT_IF_WITH_ASSERT(gdbOutputString.count(macOutputIdentifier) == 1)
{
// We need to make sure that the field we read is named "path" (or if that fails, "name") and not something containing
// these strings, so we search for them with a delimiter before:
static const gtASCIIString macLibraryNameStart1 = ",path=\"";
static const gtASCIIString macLibraryNameStart2 = "[path=\"";
static const gtASCIIString macLibraryNameStart3 = ",name=\"";
static const gtASCIIString macLibraryNameStart4 = "[name=\"";
int nameFieldStart = gdbOutputString.find(macLibraryNameStart1);
if (nameFieldStart < 0)
{
nameFieldStart = gdbOutputString.find(macLibraryNameStart2);
if (nameFieldStart < 0)
{
nameFieldStart = gdbOutputString.find(macLibraryNameStart3);
if (nameFieldStart < 0)
{
nameFieldStart = gdbOutputString.find(macLibraryNameStart4);
if (nameFieldStart < 0)
{
GT_ASSERT_EX(false, L"Could not find file name in 'info sharedlibrary' output");
}
else
{
nameFieldStart += macLibraryNameStart4.length();
}
}
else
{
nameFieldStart += macLibraryNameStart3.length();
}
}
else
{
nameFieldStart += macLibraryNameStart2.length();
}
}
else
{
nameFieldStart += macLibraryNameStart1.length();
}
if (nameFieldStart > 0)
{
int nameFieldEnd = gdbOutputString.find('\"', nameFieldStart);
GT_IF_WITH_ASSERT(nameFieldEnd > nameFieldStart + 1)
{
nameFieldEnd--;
gtASCIIString filePathAsString;
gdbOutputString.getSubString(nameFieldStart, nameFieldEnd, filePathAsString);
gtString filePathAsUnicodeString;
filePathAsUnicodeString.fromASCIIString(filePathAsString.asCharArray());
pLibraryInfo->_libraryFilePath.setFullPathFromString(filePathAsUnicodeString);
retVal = true;
}
}
}
}
else //gdbOutputString.find(macOutputIdentifier) < 0
{
// This is a linux-style output.
// Linux ignores the address we sent it (which is why we hold it as a member) and outputs
// a table with all the shared libraries in the following format:
// From To Syms Read Shared Object Library
// 0xfacefeed 0xfeedface Yes ./myLib.so
// 0x00b00f00 0x00f00b00 No /usr/lib/myOtherLib.so
// This output is also human readable, so we need to parse out the ~" at the beginning of lines
// and the \n" at the end.
// Sanity check:
GT_IF_WITH_ASSERT(_findAddress != (osInstructionPointer)NULL)
{
// Iterate the libraries until we find one that has the right address range:
gtASCIIStringTokenizer stringTokenizer1(gdbOutputString, "\n\r");
gtASCIIString currentToken1;
while (stringTokenizer1.getNextToken(currentToken1))
{
static const gtASCIIString outputLineStart = "~\"";
// Ignore the command echo and the prompt:
if (currentToken1.startsWith(outputLineStart))
{
// Make sure the line ends as we expect it:
static const gtASCIIString outputLineEnd = "\\n\"";
int expectedLineEnd = (currentToken1.length() - outputLineEnd.length());
GT_IF_WITH_ASSERT(currentToken1.reverseFind(outputLineEnd) == expectedLineEnd)
{
// Ignore "not found" messages:
static const gtASCIIString notFoundMessage1 = "No shared libraries matched"; // Ubuntu 10 message
if (gdbOutputString.find(notFoundMessage1) != -1)
{
continue;
}
currentToken1.truncate(outputLineStart.length(), (expectedLineEnd - 1));
gtASCIIStringTokenizer stringTokenizer2(currentToken1, " ");
gtASCIIString currentToken2;
// Each line should have four strings:
bool rcToken = stringTokenizer2.getNextToken(currentToken2);
GT_IF_WITH_ASSERT(rcToken)
{
// If the first one is "From:" this is the header line, ignore it:
static const gtASCIIString firstHeader = "From";
if (currentToken2.compareNoCase(firstHeader) != 0)
{
// The first token is the start address:
unsigned long long addressAsULongLong = 0;
bool rcNum = currentToken2.toUnsignedLongLongNumber(addressAsULongLong);
GT_IF_WITH_ASSERT(rcNum)
{
osInstructionPointer startAddress = (osInstructionPointer)addressAsULongLong;
rcToken = stringTokenizer2.getNextToken(currentToken2);
GT_IF_WITH_ASSERT(rcToken)
{
// The second token is the end address:
addressAsULongLong = 0;
rcNum = currentToken2.toUnsignedLongLongNumber(addressAsULongLong);
GT_IF_WITH_ASSERT(rcNum)
{
osInstructionPointer endAddress = (osInstructionPointer)addressAsULongLong;
// See if this library contains our address:
if ((endAddress > _findAddress) && (startAddress < _findAddress))
{
rcToken = stringTokenizer2.getNextToken(currentToken2);
GT_IF_WITH_ASSERT(rcToken)
{
rcToken = stringTokenizer2.getNextToken(currentToken2);
// The third token is the debug symbols loaded status, ignore it
GT_IF_WITH_ASSERT(rcToken)
{
gtString filePathAsUnicodeString;
filePathAsUnicodeString.fromASCIIString(currentToken2.asCharArray());
pLibraryInfo->_libraryFilePath.setFullPathFromString(filePathAsUnicodeString);
retVal = true;
break;
}
}
}
}
}
}
}
}
}
}
}
}
}
if (retVal)
{
if (ppGDBOutputData != NULL)
{
*ppGDBOutputData = pLibraryInfo;
}
else
{
// cleanup
delete pLibraryInfo;
}
}
else
{
// cleanup
delete pLibraryInfo;
// We failed to find anything, but it doesn't mean we really failed:
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleAbortDebuggedProcessOutput
// Description:
// Parses and handles a GDB output string that is the result of
// an "abort debugged process" GDB command.
//
// Arguments: gdbOutputLine - The GDB output line.
//
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 27/1/2009
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleAbortDebuggedProcessOutput(const gtASCIIString& gdbOutputString)
{
bool retVal = false;
// If the debugged process termination was successful:
// (we don't search for "^done", since on Mac gdb only outputs "done")
int pos1 = gdbOutputString.find("done");
GT_IF_WITH_ASSERT(pos1 != -1)
{
retVal = true;
}
std::stringstream ss(gdbOutputString.asCharArray());
std::string token;
while (std::getline(ss, token, '\n'))
{
if (std::string::npos != token.find("=thread-exited,id=\""))
{
handleExitThreadMessage(gtASCIIString(token.c_str()));
}
}
GT_IF_WITH_ASSERT(nullptr != _pGDBDriver)
{
if (_pGDBDriver->IsAllThreadsStopped())
{
retVal = true;
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleWaitingForDebuggedProcessOutput
// Description: Handle the output from a "attach -waitfor" command
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 11/5/2009
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleWaitingForDebuggedProcessOutput(const gtASCIIString& gdbOutputString)
{
bool retVal = false;
// We are expecting a string of format "Attaching to process ####"
static const gtASCIIString echoMessage = "attach -waitfor";
static const gtASCIIString waitingMessageStart = "Waiting for process ";
static const gtASCIIString attachingMessageStart = "~\"Attaching to process ";
if (gdbOutputString.startsWith(attachingMessageStart))
{
gtASCIIString processIdAsString = gdbOutputString;
processIdAsString.truncate(attachingMessageStart.length(), -1);
processIdAsString.removeTrailing('\"');
processIdAsString.removeTrailing('n');
processIdAsString.removeTrailing('\\');
processIdAsString.removeTrailing('.');
int processId = -1;
bool rcNum = processIdAsString.toIntNumber(processId);
GT_IF_WITH_ASSERT(rcNum)
{
// Mark that the debugged process is terminated:
_wasDebuggedProcessTerminated = false;
_wasDebuggedProcessSuspended = false;
m_didDebuggedProcessReceiveFatalSignal = false;
_debuggedProcessCurrentThreadGDBId = -1;
_debuggedProcessCurrentThreadId = OS_NO_THREAD_ID;
// Trigger a process run started event:
osTime processRunStartedTime;
processRunStartedTime.setFromCurrentTime();
apDebuggedProcessRunStartedEvent* pProcessRunStartedEvent = new apDebuggedProcessRunStartedEvent(processId, processRunStartedTime);
m_eventsToRegister.push_back(pProcessRunStartedEvent);
_wasDebuggedProcessCreated = true;
// When attaching to a process, it is suspended by GDB. Resume it:
gtASCIIString commandArg;
_pGDBDriver->executeGDBCommand(PD_CONTINUE_CMD, commandArg);
retVal = true;
}
}
else if (gdbOutputString.startsWith(s_gdbPromtStr))
{
// The attachment was cancelled, mark that the process doesn't exist:
_wasDebuggedProcessTerminated = true;
_wasDebuggedProcessCreated = false;
_wasDebuggedProcessSuspended = false;
m_didDebuggedProcessReceiveFatalSignal = false;
_processId = 0;
retVal = true;
}
else if ((gdbOutputString.startsWith(waitingMessageStart)) || (gdbOutputString.find(echoMessage) > -1))
{
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::addFrameDataToCallStack
// Description:
// Parses an input string that contains call stack's frame data
// and adds the frame's data into a given call stack.
// Arguments: frameDataString - A string containing the frame's data.
// callStack - A call stack into which the frame's data will be added.
// Return Val: bool - true / false - success / failure.
// Author: <NAME>
// Date: 15/3/2007
// Implementation notes:
// The frame data format is similar to the below examples:
// level="0",addr="0x00000030e74c3086",func="poll",from="/lib64/libc.so.6"
// level="1",addr="0x00002aaaab820647",func="wxEventLoop::Run",file="../src/gtk/evtloop.cpp",line="76"
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::addFrameDataToCallStack(const gtASCIIString& frameDataString, osCallStack& callStack)
{
bool retVal = false;
static const gtASCIIString gdbAddressStr = "addr";
static const gtASCIIString gdbFuncStr = "func";
static const gtASCIIString gdbFileStr = "file";
static const gtASCIIString gdbFullFileStr = "fullname";
static const gtASCIIString gdbLineStr = "line";
static const gtASCIIString gdbModuleStr = "from";
// If under debug log severity, output debug printout:
outputCallStackLineLogMessage(frameDataString);
// Will get the call stack frame:
osCallStackFrame readCallStackFrame;
// Parse the string by (name="value") pairs:
gtASCIIString curPairString;
gtASCIIStringTokenizer strTokenizer(frameDataString, ",");
while (strTokenizer.getNextToken(curPairString))
{
retVal = true;
// Look for the = sign:
int equalSignPos = curPairString.find('=');
if (equalSignPos != -1)
{
// Get the pair name:
gtASCIIString name;
curPairString.getSubString(0, equalSignPos - 1, name);
// Get the pair value:
gtASCIIString value;
curPairString.getSubString(equalSignPos + 2, curPairString.length() - 2, value);
// Act according to the pair name:
if (name == gdbAddressStr)
{
// value is an instruction couter address value:
osInstructionPointer address = NULL;
#if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT))
int rc1 = 0;
if (_debuggedExecutableArchitecture == OS_I386_ARCHITECTURE)
{
osProcedureAddress addressAsProcAddress = NULL;
rc1 = sscanf(value.asCharArray(), "%p", &addressAsProcAddress);
address = (osInstructionPointer)addressAsProcAddress;
}
else if (_debuggedExecutableArchitecture == OS_X86_64_ARCHITECTURE)
{
gtASCIIString valueToRead = value;
valueToRead.toLowerCase();
if (valueToRead.startsWith("0x"))
{
valueToRead.truncate(2, -1);
rc1 = sscanf(value.asCharArray(), "%llx", &address);
}
else
{
rc1 = sscanf(value.asCharArray(), "%llu", &address);
}
}
else
{
// Unsupported or unknown architecture, we should not get here!
GT_ASSERT(false);
}
#else
int rc1 = sscanf(value.asCharArray(), "%p", &address);
#endif
GT_IF_WITH_ASSERT(rc1 == 1)
{
// We move the pointer one instruction back so it points to the current instruction
address = (osInstructionPointer)((gtUInt64)address - 1);
readCallStackFrame.setInstructionCounterAddress(address);
}
}
else if (name == gdbFuncStr)
{
// value is a function name:
gtString functionNameAsUnicodeString;
functionNameAsUnicodeString.fromASCIIString(value.asCharArray());
readCallStackFrame.setFunctionName(functionNameAsUnicodeString);
}
else if ((name == gdbFileStr) || (name == gdbFullFileStr))
{
// value is a file name:
gtString filePathAsUnicodeString;
filePathAsUnicodeString.fromASCIIString(value.asCharArray());
osFilePath moduleFilePath(filePathAsUnicodeString);
readCallStackFrame.setSourceCodeFilePath(moduleFilePath);
}
else if (name == gdbLineStr)
{
// value is a line number:
int lineNumber = 0;
bool rc2 = value.toIntNumber(lineNumber);
GT_IF_WITH_ASSERT(rc2)
{
readCallStackFrame.setSourceCodeFileLineNumber(lineNumber);
}
}
else if (name == gdbModuleStr)
{
// value is a module file path:
gtString filePathAsUnicodeString;
filePathAsUnicodeString.fromASCIIString(value.asCharArray());
osFilePath moduleFilePath(filePathAsUnicodeString);
readCallStackFrame.setModuleFilePath(moduleFilePath);
}
}
}
if (retVal)
{
// Check if the frame is a spy frame and mark it if needed:
markSpyFrames(readCallStackFrame);
// Add the frame to the call stack:
callStack.addStackFrame(readCallStackFrame);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::markSpyFrames
// Description:
// Inputs a call stack frame. Checks if it is an OpenGL spy frame,
// and marks it as such if needed.
// Arguments: callStackFrame - The input call stack frame.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
void pdGDBOutputReader::markSpyFrames(osCallStackFrame& callStackFrame)
{
static gtVector<gtString> spySourceFileNames;
// Initialize the vector on the first time this is called:
if (spySourceFileNames.empty())
{
// TO_DO: A better approach would be to check the module name or part of a full
// source file name path, but currently we don't get them out of GDB.
// So, meanwhile we check the following file names:
spySourceFileNames.push_back(L"gsOpenGLWrappers.cpp");
#if AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT
spySourceFileNames.push_back(L"gsGLXWrappers.cpp");
#elif AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT
spySourceFileNames.push_back(L"gsCGLWrappers.cpp");
spySourceFileNames.push_back(L"gsEAGLWrappers.mm");
#else
#error unknown Linux variant
#endif
spySourceFileNames.push_back(L"gsOpenGLExtensionsWrappers.cpp");
spySourceFileNames.push_back(L"gsOpenGLMonitor.cpp");
spySourceFileNames.push_back(L"gsOpenGLModuleInitializer.cpp");
spySourceFileNames.push_back(L"gsOpenGLSpyInitFuncs.cpp");
spySourceFileNames.push_back(L"csOpenCLWrappers.cpp");
spySourceFileNames.push_back(L"csOpenGLIntegrationWrappers.cpp");
spySourceFileNames.push_back(L"csOpenCLMonitor.cpp");
spySourceFileNames.push_back(L"csOpenCLModuleInitializer.cpp");
spySourceFileNames.push_back(L"csSingletonsDelete.cpp");
spySourceFileNames.push_back(L"csOpenCLServerInitialization.cpp");
}
static const gtString openGLSpyModuleName = OS_GREMEDY_OPENGL_SERVER_MODULE_NAME;
static const gtString openGLSpyESModuleName = OS_OPENGL_ES_COMMON_DLL_NAME;
static const gtString openCLSpyModuleName = OS_GREMEDY_OPENCL_SERVER_MODULE_NAME;
// Will get true iff the input frame is a spy frame:
bool isSpyFrame = false;
// Get the module file path:
const gtString& modulePath = callStackFrame.moduleFilePath().asString();
bool isSpyFileName = (modulePath.find(openGLSpyModuleName) != -1) || (modulePath.find(openGLSpyESModuleName) != -1) || (modulePath.find(openCLSpyModuleName) != -1);
static const gtString linuxSystemPathPrefix = L"/usr/lib";
if (isSpyFileName && (!modulePath.startsWith(linuxSystemPathPrefix)))
{
isSpyFrame = true;
}
else
{
// Get the source code file path:
const gtString& frameSourcePath = callStackFrame.sourceCodeFilePath().asString();
// Check if it contains spy files:
for (const gtString& fn : spySourceFileNames)
{
if (-1 != frameSourcePath.find(fn))
{
isSpyFrame = true;
break;
}
}
}
// If this is a spy function frame - mark it as such:
if (isSpyFrame)
{
callStackFrame.markAsSpyFunction();
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGDBResultOutput
// Description:
// Parses and handles a GDB output line that contains GDB result.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGDBResultOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = true;
static gtASCIIString targetIsRunningMsg = "^running";
static gtASCIIString errorMsg = "^error";
static gtASCIIString connectedToRemoteTargetMsg = "^connected";
static const gtASCIIString badThreadMsg = "^done,bad_thread=";
static const gtASCIIString exitedMsg = "exited";
gtString gdbOutputLineAsUnicodeString;
gdbOutputLineAsUnicodeString.fromASCIIString(gdbOutputLine.asCharArray());
bool sendTermination = false;
if (gdbOutputLine.startsWith(s_gdbOperationSuccessStr))
{
const pdGDBCommandInfo* pCommandInfo = pdGetGDBCommandInfo(_executedGDBCommandId);
GT_IF_WITH_ASSERT(pCommandInfo != NULL)
{
// If we got this during an asynchronus command, this might mean the debugged process exited:
if (pCommandInfo->_commandType == PD_GDB_ASYNCHRONOUS_CMD)
{
// If the application exited:
if (gdbOutputLine.find(s_exitedGDBStr) > -1)
{
// Report it (see the end of the function):
sendTermination = true;
}
}
else
{
// An synchronous operation was successful, do nothing for now.
if (gdbOutputLine.startsWith(badThreadMsg))
{
// This means that the command "succeeded" but did not have the desired result, so we consider it failed:
retVal = false;
}
}
}
// Clear the last logged GDB command:
_executedGDBCommandId = PD_GDB_NULL_CMD;
}
else if (gdbOutputLine.startsWith(targetIsRunningMsg))
{
// The debugged process is running:
// Raise an appropriate event, but don't notify this more than once (Apple's gdb V. 1344 - 6.3.50 shows "switch to process" for every break)
bool debuggedProcessExists = pdProcessDebugger::instance().debuggedProcessExists();
if (!(_wasDebuggedProcessCreated && debuggedProcessExists))
{
#if AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT
{
_wasDebuggedProcessCreated = true;
// The process run started:
osTime processRunStartedTime;
processRunStartedTime.setFromCurrentTime();
apDebuggedProcessRunStartedEvent* pProcessRunStartedEvent = new apDebuggedProcessRunStartedEvent(_processId, processRunStartedTime);
m_eventsToRegister.push_back(pProcessRunStartedEvent);
}
#endif
}
else
{
// Some thread was resumed
GT_IF_WITH_ASSERT(_pGDBDriver != NULL)
{
if (_pGDBDriver->IsAllThreadsRunning())
{
// The process run was resumed:
apDebuggedProcessRunResumedEvent* pProcessRunResumedEvent = new apDebuggedProcessRunResumedEvent;
m_eventsToRegister.push_back(pProcessRunResumedEvent);
}
}
}
}
else if (gdbOutputLine.startsWith(errorMsg))
{
// A GDB operation failed:
retVal = false;
int messageStartPosition = gdbOutputLine.find("msg=\"");
int messageEndPosition = gdbOutputLine.reverseFind('"');
GT_IF_WITH_ASSERT_EX((messageEndPosition - messageStartPosition > 5) && (messageStartPosition >= 0),
gdbOutputLineAsUnicodeString.asCharArray())
{
retVal = true;
gtString errorMsg;
gdbOutputLineAsUnicodeString.getSubString((messageStartPosition + 5), (messageEndPosition - 1), errorMsg);
apGDBErrorEvent* pErrorEvent = new apGDBErrorEvent(errorMsg);
m_eventsToRegister.push_back(pErrorEvent);
// If the error is "exited during function execution", also send a termination event:
if (PD_EXECUTE_FUNCTION_CMD == _executedGDBCommandId)
{
if (-1 != gdbOutputLine.find(exitedMsg))
{
sendTermination = true;
}
}
else if (PD_GDB_RUN_DEBUGGED_PROCESS_CMD == _executedGDBCommandId)
{
if (-1 != gdbOutputLine.find(exitedMsg))
{
sendTermination = true;
}
}
}
}
else if (gdbOutputLine.startsWith(connectedToRemoteTargetMsg))
{
// We don't support remote debugging yet ...
GT_ASSERT_EX(false, gdbOutputLineAsUnicodeString.asCharArray());
retVal = false;
}
else
{
// Unknown GDB result output:
GT_ASSERT_EX(false, gdbOutputLineAsUnicodeString.asCharArray());
retVal = false;
}
// Handle process exits:
if (sendTermination)
{
// Mark that the process terminated:
_wasDebuggedProcessTerminated = true;
_wasDebuggedProcessCreated = false;
// Trigger a process terminated event:
apDebuggedProcessTerminatedEvent* pDebuggedProcessTerminationEvent = new apDebuggedProcessTerminatedEvent(0);
m_eventsToRegister.push_back(pDebuggedProcessTerminationEvent);
// Mark that the debugged process is not suspended (it is terminated):
_wasDebuggedProcessSuspended = false;
m_didDebuggedProcessReceiveFatalSignal = false;
// Mark that there is no current debugged process thread:
_debuggedProcessCurrentThreadGDBId = -1;
_debuggedProcessCurrentThreadId = OS_NO_THREAD_ID;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGDBConsoleOutput
// Description:
// Parses and handles a GDB output line that contains GDB console output.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGDBConsoleOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = true;
if (gdbOutputLine.startsWith(s_newThreadMsg))
{
// A new debugged process thread was created:
handleNewThreadMessage(gdbOutputLine);
}
else if (gdbOutputLine.find(s_switchingToThreadMsg) != -1)
{
// Handle the "[Switching to Thread..." message:
handleSwitchingToThreadMessage(gdbOutputLine);
}
else if (gdbOutputLine.startsWith(s_debuggedProcessStoppedMsg))
{
bool wasBreakpointHit = false;
handleSignalOutput(gdbOutputLine, wasBreakpointHit);
}
else if (gdbOutputLine.find(s_switchingToProcessMsg) != -1)
{
bool doesProcessExist = pdProcessDebugger::instance().debuggedProcessExists();
if ((gdbOutputLine.find(s_switchingToProcessAndThread) != -1) && doesProcessExist)
{
// Handle the "[Switching to process ... {local} thread ..." message:
handleSwitchingToProcessAndThreadMessage(gdbOutputLine);
}
else
{
// Handle the "[Switching to process..." message:
handleSwitchingToProcessMessage(gdbOutputLine);
}
}
else
{
// The "set environment" command echos a string when setting environment
// variables to null. We would like to ignore this string.
if (_executedGDBCommandId != PD_SET_ENV_VARIABLE_CMD)
{
// Increment the amount of GDB string printouts:
_amountOfGDBStringPrintouts++;
if (_amountOfGDBStringPrintouts == PD_MAX_GDB_STRING_PRINTOUTS)
{
// Tell the user that we reached the maximal debug printouts:
static gtString maxReportsMsg;
maxReportsMsg.makeEmpty();
maxReportsMsg.appendFormattedString(PD_STR_GDBStringMaxPrintoutsReached, PD_MAX_GDB_STRING_PRINTOUTS);
apGDBOutputStringEvent* pOutputEvent = new apGDBOutputStringEvent(maxReportsMsg);
m_eventsToRegister.push_back(pOutputEvent);
}
else if (_amountOfGDBStringPrintouts < PD_MAX_GDB_STRING_PRINTOUTS)
{
// Report the GDB console output as a debugged process output string:
gtString gdbOutputLineAsUnicodeString;
gdbOutputLineAsUnicodeString.fromASCIIString(gdbOutputLine.asCharArray());
apGDBOutputStringEvent* pOutputEvent = new apGDBOutputStringEvent(gdbOutputLineAsUnicodeString);
m_eventsToRegister.push_back(pOutputEvent);
}
// Otherwise ignore the printouts:
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleDebuggedProcessOutput
// Description:
// Parses and handles a GDB output line that contains a debugged
// process output.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleDebuggedProcessOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = true;
// If we got a message that tells us that gdb launch failed:
bool failedToLaunchGDB = (gdbOutputLine.find(PD_STR_failedToLaunchGDBASCII) != -1);
if (failedToLaunchGDB)
{
retVal = false;
}
else
{
gtString gdbOutputLineAsUnicodeString;
gdbOutputLineAsUnicodeString.fromASCIIString(gdbOutputLine.asCharArray());
static const gtString debugStringPrefix(OS_STR_DebugStringOutputPrefix);
if (gdbOutputLineAsUnicodeString.startsWith(debugStringPrefix))
{
// This is a debug string generated by osOutputDebugString.
// Get the debug string itself:
int prefixLength = debugStringPrefix.length();
gtString debugMessage = gdbOutputLineAsUnicodeString;
debugMessage.truncate(prefixLength, -1);
// Make a debug string event:
apOutputDebugStringEvent* pDebugStringEve = new apOutputDebugStringEvent(OS_NO_THREAD_ID, debugMessage);
m_eventsToRegister.push_back(pDebugStringEve);
}
else
{
// Trigger a "debugged process output string" event:
apDebuggedProcessOutputStringEvent* pOutputStringEve = new apDebuggedProcessOutputStringEvent(gdbOutputLineAsUnicodeString);
m_eventsToRegister.push_back(pOutputStringEve);
}
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleGDBInternalOutput
// Description:
// Parses and handles a GDB internal output.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleGDBInternalOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = true;
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
// Output the messages to the debug log:
gtString gdbOutputLineAsUnicodeString;
gdbOutputLineAsUnicodeString.fromASCIIString(gdbOutputLine.asCharArray());
OS_OUTPUT_DEBUG_LOG(gdbOutputLineAsUnicodeString.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleAsynchronousOutput
// Description:
// Parses and handles a GDB output line that contains a GDB "exec-async-output"
// outputs.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occurred.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleAsynchronousOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = false;
static const gtASCIIString breakpointHitGDBStr = "breakpoint-hit";
static const gtASCIIString breakpointNextGDBStr = "end-stepping-range";
static const gtASCIIString breakpointFinishGDBStr = "function-finished";
static const gtASCIIString signalReceivedGDBStr = "signal-received";
static const gtASCIIString runningThreadGDBStr = "running";
// If the debugged process is running:
if (gdbOutputLine.startsWith(s_debuggedProcessRunningMsg))
{
// Sigal 29/9/2009
// On OpenSuse OS, gdb version 6.8.50.20081120 : An example result of an "-exec-continue" GDB command may be:
// *running, thread id="all"
// We skip this line, since gdb already told us that the debugged process run was resumed using the "^running" output.
GetRunningThreadGDBId(gdbOutputLine);
retVal = true;
}
// If the debugged process stopped running:
else if (gdbOutputLine.startsWith(s_debuggedProcessStoppedMsg))
{
// Mark that the debugged process run was suspended:
//_wasDebuggedProcessSuspended = true;
m_didDebuggedProcessReceiveFatalSignal = false;
// Will get true if we caught a signal:
bool wasSignalCaught = false;
bool wasBreakpointHit = false;
// The following mechanism is only needed in Mac, where the "info threads" output
// does not supply the information of which thread is current:
#if (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT)
// If there is a thread number specified, store it:
static gtASCIIString threadNumberGDBStr = "thread-id=\"";
// Clear the current thread number:
_currentThreadNumber = -1;
int threadNumberLocation = gdbOutputLine.find(threadNumberGDBStr);
if (threadNumberLocation != -1)
{
// Get the thread number:
gtASCIIString threadNumberAsString;
threadNumberLocation += threadNumberGDBStr.length();
int threadNumberEnd = gdbOutputLine.find('\"', threadNumberLocation);
GT_IF_WITH_ASSERT(threadNumberEnd > threadNumberLocation)
{
// We are on the quotation mark, move one char back:
threadNumberEnd--;
gdbOutputLine.getSubString(threadNumberLocation, threadNumberEnd, threadNumberAsString);
int threadNumber = -1;
bool rcNum = threadNumberAsString.toIntNumber(threadNumber);
GT_IF_WITH_ASSERT(rcNum)
{
_currentThreadNumber = threadNumber;
}
}
}
#endif
// Get the string that describes the stop reason:
gtASCIIString stopReason;
bool rc1 = getStopReasonString(gdbOutputLine, stopReason);
bool wasHostBreakPoint = false;
if (!rc1)
{
/// Gdb not always put stop reason of the "*stopped" message for steps
if (gdbOutputLine.find("frame=") != -1)
{
flushGDBPrompt();
rc1 = true;
}
}
if (rc1)
{
// If a signal was received:
wasSignalCaught = stopReason.startsWith(signalReceivedGDBStr);
bool isBreakpoint = stopReason.startsWith(breakpointHitGDBStr);
bool isStep = stopReason.startsWith(breakpointNextGDBStr) || stopReason.startsWith(breakpointFinishGDBStr);
if ((isBreakpoint && gdbOutputLine.find("disp=\"del\"") != -1))
{
isBreakpoint = false;
isStep = true;
}
if (wasSignalCaught)
{
// Handle the signal:
handleSignalOutput(gdbOutputLine, wasBreakpointHit);
}
else if (isBreakpoint || isStep)
{
bool isGDBBreakpoint = (-1 != gdbOutputLine.find("bkptno") && (gdbOutputLine.find("disp=\"del\"") == -1));
if (isStep || isGDBBreakpoint)
{
// Host breakpoint
int pos1 = gdbOutputLine.find("thread-id=\"");
if (-1 != pos1)
{
int length = ::strlen("thread-id=\"");
int pos2 = gdbOutputLine.find("\"", pos1 + length);
GT_IF_WITH_ASSERT(-1 != pos2)
{
gtASCIIString strThreadId;
gdbOutputLine.getSubString(pos1 + length, pos2 - 1, strThreadId);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(strThreadId.toIntNumber(threadGDBId))
{
_pGDBDriver->OnThreadGDBStopped(threadGDBId);
_debuggedProcessCurrentThreadGDBId = threadGDBId;
_debuggedProcessCurrentThreadId = threadIdFromGDBId(_debuggedProcessCurrentThreadGDBId);
wasBreakpointHit = handleBreakpointHit(isGDBBreakpoint, isStep);
_wasDebuggedProcessSuspended = true;
wasHostBreakPoint = true;
}
}
}
}
else
{
// The debugged process hit a breakpoint (usually set by GDB):
// If this breakpoint came from the spy, report it to the application. Otherwise,
// treat it as a non-fatal signal (SIGTRAP is non-fatal):
bool wasStoppedInSpy = false;
bool rcLoc = isCurrentThreadStoppedInsideSpy(wasStoppedInSpy);
GT_ASSERT(rcLoc);
// Some applications (l3com case 7852, OpenSceneGraph) have a thread that sits in pthread_cond_wait, which is the same as the
// breakpoint triggering thread.
// This sometimes confuses gdb making it think that a different thread triggered the signal, causing spy breakpoints to be considered
// as foreign breaks, and making the app become stuck. So, to be on the safe side, before deciding a SIGTRAP is a foreign break, we
// check all threads to make sure none of them is inside the spy.
if (!wasStoppedInSpy)
{
wasStoppedInSpy = isAnyThreadStoppedInSpy();
}
wasBreakpointHit = wasStoppedInSpy;
if (wasBreakpointHit)
{
wasBreakpointHit = handleBreakpointHit();
}
}
}
else if (stopReason.startsWith(s_exitedGDBStr))
{
// The debugged process exited:
_wasDebuggedProcessTerminated = true;
_wasDebuggedProcessCreated = false;
}
}
else // !rc1
{
if (_isWaitingForInternalDebuggedProcessInterrupt)
{
// Always consider a stop during a "call" that is not a SIGINT signal to be an exit / crash. This happens if the application exits normally
// during a break (e.g. closing its window) and then using the call command finalizes the exit command. Not identifying this causes a hang in the GUI:
_wasDebuggedProcessTerminated = true;
_wasDebuggedProcessCreated = false;
}
}
// If the debugged process was terminated:
if (_wasDebuggedProcessTerminated)
{
// Trigger a process terminated event:
apDebuggedProcessTerminatedEvent* pDebuggedProcessTerminationEvent = new apDebuggedProcessTerminatedEvent(0);
m_eventsToRegister.push_back(pDebuggedProcessTerminationEvent);
// Mark that the debugged process is not suspended (it is terminated):
_wasDebuggedProcessSuspended = false;
m_didDebuggedProcessReceiveFatalSignal = false;
// Mark that there is no current debugged process thread:
_debuggedProcessCurrentThreadGDBId = -1;
_debuggedProcessCurrentThreadId = OS_NO_THREAD_ID;
}
else
{
// If we caught a signal that is not a breakpoint:
if (wasSignalCaught && !wasBreakpointHit && !m_didDebuggedProcessReceiveFatalSignal)
{
// We will resume the debugged process run shortly to make the debugged process handle the _non-fatal_ signal (see pdLinuxProcessDebugger::onExceptionEvent).
// Therefore, we don't want the outside world to know that the debugged process was suspended.
}
else
{
// The debugged process should be suspended, as it got a breakpoint or a fatal signal.
// Trigger also a debugged process suspended event:
apDebuggedProcessRunSuspendedEvent* pRunSuspendedEvent = new apDebuggedProcessRunSuspendedEvent(_debuggedProcessCurrentThreadId, wasHostBreakPoint);
m_eventsToRegister.push_back(pRunSuspendedEvent);
}
}
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleStatusAsynchronousOutput
// Description: Handles GDB "status asynchronous output"
// Arguments: gdbOutputLine - The GDB output string.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 31/12/2008
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleStatusAsynchronousOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = false;
static gtASCIIString s_SharedLibAddedMsg = "=shlibs-added";
static gtASCIIString s_SharedLibRemovedMsg = "=shlibs-removed";
static gtASCIIString s_StartThreadMsg = "=thread-created,id=\"";
static gtASCIIString s_ExitThreadMsg = "=thread-exited,id=\"";
static gtASCIIString s_ThreadGroupStarted = "=thread-group-started";
// If a shared module was loaded into the debugged process address space::
if (gdbOutputLine.find(s_StartThreadMsg) != -1)
{
handleNewThreadMessage(gdbOutputLine);
retVal = true;
}
else if (gdbOutputLine.find(s_ExitThreadMsg) != -1)
{
handleExitThreadMessage(gdbOutputLine);
retVal = true;
}
else if (gdbOutputLine.find(s_SharedLibRemovedMsg) != -1)
{
// If a shared module was removed from the debugged process address space:
retVal = handleSharedModuleUnloadedMessage(gdbOutputLine);
}
else if (gdbOutputLine.find(s_ThreadGroupStarted) != -1)
{
GT_IF_WITH_ASSERT(gdbOutputLine.find("pid") != -1)
{
int pos1 = gdbOutputLine.find("pid=\"");
GT_IF_WITH_ASSERT(-1 != pos1)
{
pos1 += (int)strlen("pid=\"");
int pos2 = gdbOutputLine.find("\"", pos1);
GT_IF_WITH_ASSERT(1 < pos2)
{
gtASCIIString processId;
pos2--;
GT_IF_WITH_ASSERT(pos1 < pos2)
{
gdbOutputLine.getSubString(pos1, pos2, processId);
GT_IF_WITH_ASSERT(processId.toIntNumber(_processId))
{
retVal = true;
}
else
{
_processId = 0;
}
}
}
}
}
}
else
{
// Unknown asynchronous output - do nothing:
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleUnknownGDBOutput
// Description:
// Parses and handles a GDB output line that contains an GDB output that
// this class does not recognize.
// Arguments: gdbOutputLine - The GDB output line.
// Return Val: bool - false - iff an internal / a GDB error occured.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleUnknownGDBOutput(const gtASCIIString& gdbOutputLine)
{
bool retVal = true;
// Report this to the development team:
gtString gdbOutputLineAsUnicodeString;
gdbOutputLineAsUnicodeString.fromASCIIString(gdbOutputLine.asCharArray());
GT_ASSERT_EX(false, gdbOutputLineAsUnicodeString.asCharArray());
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::getStopReasonString
// Description:
// Inputs a GDB output line that contains a GDB "*stopped" notification
// and returns the sub string that describes the stop reason.
// Arguments: gdbOutputLine - The input GDB output line.
// stopReasonString - Will get the sub string that describes the stop reason.
// Return Val: bool - Sucess / Failure.
// Author: <NAME>
// Date: 26/12/2006
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::getStopReasonString(const gtASCIIString& gdbOutputLine,
gtASCIIString& stopReasonString)
{
bool retVal = false;
static gtASCIIString stopReasonGDBStr = "reason=\"";
// Get the stop reason:
int pos1 = gdbOutputLine.find(stopReasonGDBStr);
GT_IF_WITH_ASSERT(pos1 != -1)
{
int pos2 = pos1 + stopReasonGDBStr.length();
int pos3 = gdbOutputLine.find('\"', pos2);
GT_IF_WITH_ASSERT(pos3 != -1)
{
gdbOutputLine.getSubString(pos2, (pos3 - 1), stopReasonString);
retVal = true;
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::isAnyThreadStoppedInSpy
// Description: Returns true iff any thread is stopped in the spy
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 18/8/2010
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::isAnyThreadStoppedInSpy()
{
bool retVal = false;
// Get the debugged process threads data:
static const gtASCIIString emptyStr;
const pdGDBData* pGDBOutputData = NULL;
// On Mac, starting with Xcode 3.2.3, the "info threads" command does not give us all the data we need, so we use the machine interface "-thread-list-ids" instead.
// On Linux, the machine interface function is not implementer on all platforms, so we cannot use it as we might not get the data.
#if AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT
bool rc1 = _pGDBDriver->executeGDBCommand(PD_GET_THREADS_INFO_CMD, emptyStr, &pGDBOutputData);
#elif AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT
bool rc1 = _pGDBDriver->executeGDBCommand(PD_GET_THREADS_INFO_VIA_MI_CMD, emptyStr, &pGDBOutputData);
#else
#error Unknown Linux Variant!
#endif
GT_IF_WITH_ASSERT(rc1 && (pGDBOutputData != NULL) && (nullptr != _pGDBDriver))
{
// Sanity check:
GT_IF_WITH_ASSERT(pGDBOutputData->type() == pdGDBData::PD_GDB_THREAD_DATA_LIST)
{
// Store the threads data;
pdGDBThreadDataList* pDebuggedProcessThreadsData = (pdGDBThreadDataList*)pGDBOutputData;
const gtList<pdGDBThreadData>& debuggedProcessThreadsDataList = pDebuggedProcessThreadsData->_threadsDataList;
// Iterate all the threads:
gtList<pdGDBThreadData>::const_iterator iter = debuggedProcessThreadsDataList.begin();
gtList<pdGDBThreadData>::const_iterator endIter = debuggedProcessThreadsDataList.end();
while (iter != endIter)
{
// Set the current thread:
int currentThreadGDBIndex = (*iter)._gdbThreadId;
GT_IF_WITH_ASSERT(currentThreadGDBIndex > -1)
{
gtASCIIString currentThreadIndexAsString;
currentThreadIndexAsString.appendFormattedString("%d", currentThreadGDBIndex);
bool rcThd = _pGDBDriver->executeGDBCommand(PD_SET_ACTIVE_THREAD_CMD, currentThreadIndexAsString);
GT_IF_WITH_ASSERT(rcThd)
{
bool threadWasSuspended = true;
bool threadRunning = _pGDBDriver->IsThreadRunning(currentThreadGDBIndex);
bool rcStopThrd = true;
if (threadRunning)
{
_pGDBDriver->SuspendThread(currentThreadGDBIndex);
threadWasSuspended = false;
}
GT_IF_WITH_ASSERT(rcStopThrd)
{
// Check if this thread is in the spy:
bool isInSpy = false;
bool rcSpy = isCurrentThreadStoppedInsideSpy(isInSpy);
GT_IF_WITH_ASSERT(rcSpy)
{
// We found a thread inside the spy:
if (isInSpy)
{
// Stop looking:
retVal = true;
}
}
if (!threadWasSuspended)
{
bool rcRes = _pGDBDriver->ResumeThread(currentThreadGDBIndex);
GT_ASSERT(rcRes);
}
if (retVal)
{
break;
}
}
}
}
iter++;
}
}
}
// Clean up the threads data:
delete pGDBOutputData;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::isCurrentThreadStoppedInsideSpy
// Description: If the gdb current thread is stopped inside the spy, sets wasStoppedInSpy to true.
// Arguments: gdbOutputLine - the output line
// wasStoppedInSpy - will be filled with true iff the breakpoint came from the spy utilities module
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 18/7/2010
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::isCurrentThreadStoppedInsideSpy(bool& wasStoppedInSpy)
{
bool retVal = false;
// Get the break call stack:
osCallStack breakCallStack;
static const gtASCIIString emptyStr;
const pdGDBData* pGDBOutputData = NULL;
bool rcStack = _pGDBDriver->executeGDBCommand(PD_GET_CUR_THREAD_CALL_STACK_CMD, emptyStr, &pGDBOutputData);
GT_IF_WITH_ASSERT(rcStack && (pGDBOutputData != NULL))
{
// Sanity check:
GT_IF_WITH_ASSERT(pGDBOutputData->type() == pdGDBData::PD_GDB_CALL_STACK_DATA)
{
// Get the call stack data:
const pdGDBCallStack* pCallStackData = (const pdGDBCallStack*)pGDBOutputData;
// Get its top frame:
breakCallStack = pCallStackData->_callStack;
}
}
delete pGDBOutputData;
// Verify the stack isn't empty:
int amountOfBreakStackFrames = breakCallStack.amountOfStackFrames();
GT_IF_WITH_ASSERT(amountOfBreakStackFrames > 0)
{
// Go down the stack, looking for spy frames (we cannot assume the topmost or 2nd topmost frame is the one that called ::kill(),
// as different unix version have a different stack depth to each one:
retVal = true;
// Until proven otherwise, this break came from another module, so it is a foreign break:
wasStoppedInSpy = false;
// Iterate the stack frames
static const gtString stat_spiesUtilitiesModuleName(OS_SPY_UTILS_FILE_PREFIX);
static const gtString stat_spiesBreakpointFunctionName(OS_SPIES_BREAKPOINT_FUNCTION_NAME);
for (int i = 0; i < amountOfBreakStackFrames; i++)
{
// Get the current frame:
const osCallStackFrame* pCurrentStackFrame = breakCallStack.stackFrame(i);
if (pCurrentStackFrame != NULL)
{
// We consider the breakpoint to be triggered by the spy if:
// 1. The stack has a spy frame (i.e. a frame that the addFrameDataToCallStack function recognized as such
// 2. The stack has a frame from GRSpiesUtilities
// 3. The stack has the function suBreakpointsManager::triggerBreakpointException (this is needed for release builds, where debug info may not be available)
gtString modulePathLowerCase = pCurrentStackFrame->moduleFilePath().asString();
int spyUtilitiesFileNameInModulePath = modulePathLowerCase.toLowerCase().find(stat_spiesUtilitiesModuleName);
if (pCurrentStackFrame->isSpyFunction() || (spyUtilitiesFileNameInModulePath > -1) || (pCurrentStackFrame->functionName() == stat_spiesBreakpointFunctionName))
{
// If this is the spy utilities module:
wasStoppedInSpy = true;
break;
}
}
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleSignalOutput
// Description:
// Inputs a GDB output line that contains a GDB "signal-received" notification
// and returns the appropriate event type.
// Arguments: gdbOutputLine - The input GDB output line.
// wasBreakpointHit - Will get true iff the signal represents a breakpoint hit.
//
// Author: <NAME>
// Date: 3/1/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::handleSignalOutput(const gtASCIIString& gdbOutputLine, bool& wasBreakpointHit)
{
static gtASCIIString signalNameGDBStr = "signal-name=\"";
static int signalNameGDBStrLen = signalNameGDBStr.length();
static gtASCIIString sigThreadStopped = "0"; /// < In case stopped specific thread in non-stop GDB mode
static gtASCIIString sigHupGDBStr = "SIGHUP";
static gtASCIIString sigIntGDBStr = "SIGINT";
static gtASCIIString sigQuitGDBStr = "SIGQUIT";
static gtASCIIString sigIllGDBStr = "SIGILL";
static gtASCIIString sigTrapGDBStr = "SIGTRAP";
static gtASCIIString sigAbrtGDBStr = "SIGABRT";
static gtASCIIString sigBugGDBStr = "SIGBUS";
static gtASCIIString sigFpeGDBStr = "SIGFPE";
static gtASCIIString sigKillGDBStr = "SIGKILL";
static gtASCIIString sigSegvGDBStr = "SIGSEGV";
static gtASCIIString sigPipeGDBStr = "SIGPIPE";
static gtASCIIString sigAlrmGDBStr = "SIGALRM";
static gtASCIIString sigTermGDBStr = "SIGTERM";
static gtASCIIString sigUsr1GDBStr = "SIGUSR1";
static gtASCIIString sigUsr2GDBStr = "SIGUSR2";
static gtASCIIString sigStopGDBStr = "SIGSTOP";
static gtASCIIString sigStpGDBStr = "SIGTSTP";
static gtASCIIString sigTTInGDBStr = "SIGTTIN";
static gtASCIIString sigTTOuGDBStr = "SIGTTOU";
static gtASCIIString strSIGEMT_SIGNAL = "SIGEMT";
static gtASCIIString strSIGSYS_SIGNAL = "SIGSYS";
static gtASCIIString strSIGURG_SIGNAL = "SIGURG";
static gtASCIIString strSIGSTOP_SIGNAL = "SIGSTOP";
static gtASCIIString strSIGTSTP_SIGNAL = "SIGTSTP";
static gtASCIIString strSIGCONT_SIGNAL = "SIGCONT";
static gtASCIIString strSIGCHLD_SIGNAL = "SIGCHLD";
static gtASCIIString strSIGTTIN_SIGNAL = "SIGTTIN";
static gtASCIIString strSIGTTOU_SIGNAL = "SIGTTOU";
static gtASCIIString strSIGIO_SIGNAL = "SIGIO";
static gtASCIIString strSIGXCPU_SIGNAL = "SIGXCPU";
static gtASCIIString strSIGXFSZ_SIGNAL = "SIGXFSZ";
static gtASCIIString strSIGVTALRM_SIGNAL = "SIGVTALRM";
static gtASCIIString strSIGPROF_SIGNAL = "SIGPROF";
static gtASCIIString strSIGWINCH_SIGNAL = "SIGWINCH";
static gtASCIIString strSIGLOST_SIGNAL = "SIGLOST";
static gtASCIIString strSIGPWR_SIGNAL = "SIGPWR";
static gtASCIIString strSIGPOLL_SIGNAL = "SIGPOLL";
static gtASCIIString strSIGWIND_SIGNAL = "SIGWIND";
static gtASCIIString strSIGPHONE_SIGNAL = "SIGPHONE";
static gtASCIIString strSIGWAITING_SIGNAL = "SIGWAITING";
static gtASCIIString strSIGLWP_SIGNAL = "SIGLWP";
static gtASCIIString strSIGDANGER_SIGNAL = "SIGDANGER";
static gtASCIIString strSIGGRANT_SIGNAL = "SIGGRANT";
static gtASCIIString strSIGRETRACT_SIGNAL = "SIGRETRACT";
static gtASCIIString strSIGMSG_SIGNAL = "SIGMSG";
static gtASCIIString strSIGSOUND_SIGNAL = "SIGSOUND";
static gtASCIIString strSIGSAK_SIGNAL = "SIGSAK";
static gtASCIIString strSIGPRIO_SIGNAL = "SIGPRIO";
static gtASCIIString strSIGCANCEL_SIGNAL = "SIGCANCEL";
static gtASCIIString strEXC_BAD_ACCESS_SIGNAL = "EXC_BAD_ACCESS";
static gtASCIIString strEXC_BAD_INSTRUCTION_SIGNAL = "EXC_BAD_INSTRUCTION";
static gtASCIIString strEXC_ARITHMETIC_SIGNAL = "EXC_ARITHMETIC";
static gtASCIIString strEXC_EMULATION_SIGNAL = "EXC_EMULATION";
static gtASCIIString strEXC_SOFTWARE_SIGNAL = "EXC_SOFTWARE";
static gtASCIIString strEXC_BREAKPOINT_SIGNAL = "EXC_BREAKPOINT";
static gtASCIIString strSIG32_SIGNAL = "SIG32";
static gtASCIIString strSIG33_SIGNAL = "SIG33";
static gtASCIIString strSIG34_SIGNAL = "SIG34";
static gtASCIIString strSIG35_SIGNAL = "SIG35";
static gtASCIIString strSIG36_SIGNAL = "SIG36";
static gtASCIIString strSIG37_SIGNAL = "SIG37";
static gtASCIIString strSIG38_SIGNAL = "SIG38";
static gtASCIIString strSIG39_SIGNAL = "SIG39";
static gtASCIIString strSIG40_SIGNAL = "SIG40";
static gtASCIIString strSIG41_SIGNAL = "SIG41";
static gtASCIIString strSIG42_SIGNAL = "SIG42";
static gtASCIIString strSIG43_SIGNAL = "SIG43";
static gtASCIIString strSIG44_SIGNAL = "SIG44";
static gtASCIIString strSIG45_SIGNAL = "SIG45";
static gtASCIIString strSIG46_SIGNAL = "SIG46";
static gtASCIIString strSIG47_SIGNAL = "SIG47";
static gtASCIIString strSIG48_SIGNAL = "SIG48";
static gtASCIIString strSIG49_SIGNAL = "SIG49";
static gtASCIIString strSIG50_SIGNAL = "SIG50";
static gtASCIIString strSIG51_SIGNAL = "SIG51";
static gtASCIIString strSIG52_SIGNAL = "SIG52";
static gtASCIIString strSIG53_SIGNAL = "SIG53";
static gtASCIIString strSIG54_SIGNAL = "SIG54";
static gtASCIIString strSIG55_SIGNAL = "SIG55";
static gtASCIIString strSIG56_SIGNAL = "SIG56";
static gtASCIIString strSIG57_SIGNAL = "SIG57";
static gtASCIIString strSIG58_SIGNAL = "SIG58";
static gtASCIIString strSIG59_SIGNAL = "SIG59";
static gtASCIIString strSIG60_SIGNAL = "SIG60";
static gtASCIIString strSIG61_SIGNAL = "SIG61";
static gtASCIIString strSIG62_SIGNAL = "SIG62";
static gtASCIIString strSIG63_SIGNAL = "SIG63";
static gtASCIIString strSIG64_SIGNAL = "SIG64";
static gtASCIIString strSIG65_SIGNAL = "SIG65";
static gtASCIIString strSIG66_SIGNAL = "SIG66";
static gtASCIIString strSIG67_SIGNAL = "SIG67";
static gtASCIIString strSIG68_SIGNAL = "SIG68";
static gtASCIIString strSIG69_SIGNAL = "SIG69";
static gtASCIIString strSIG70_SIGNAL = "SIG70";
static gtASCIIString strSIG71_SIGNAL = "SIG71";
static gtASCIIString strSIG72_SIGNAL = "SIG72";
static gtASCIIString strSIG73_SIGNAL = "SIG73";
static gtASCIIString strSIG74_SIGNAL = "SIG74";
static gtASCIIString strSIG75_SIGNAL = "SIG75";
static gtASCIIString strSIG76_SIGNAL = "SIG76";
static gtASCIIString strSIG77_SIGNAL = "SIG77";
static gtASCIIString strSIG78_SIGNAL = "SIG78";
static gtASCIIString strSIG79_SIGNAL = "SIG79";
static gtASCIIString strSIG80_SIGNAL = "SIG80";
static gtASCIIString strSIG81_SIGNAL = "SIG81";
static gtASCIIString strSIG82_SIGNAL = "SIG82";
static gtASCIIString strSIG83_SIGNAL = "SIG83";
static gtASCIIString strSIG84_SIGNAL = "SIG84";
static gtASCIIString strSIG85_SIGNAL = "SIG85";
static gtASCIIString strSIG86_SIGNAL = "SIG86";
static gtASCIIString strSIG87_SIGNAL = "SIG87";
static gtASCIIString strSIG88_SIGNAL = "SIG88";
static gtASCIIString strSIG89_SIGNAL = "SIG89";
static gtASCIIString strSIG90_SIGNAL = "SIG90";
static gtASCIIString strSIG91_SIGNAL = "SIG91";
static gtASCIIString strSIG92_SIGNAL = "SIG92";
static gtASCIIString strSIG93_SIGNAL = "SIG93";
static gtASCIIString strSIG94_SIGNAL = "SIG94";
static gtASCIIString strSIG95_SIGNAL = "SIG95";
static gtASCIIString strSIG96_SIGNAL = "SIG96";
static gtASCIIString strSIG97_SIGNAL = "SIG97";
static gtASCIIString strSIG98_SIGNAL = "SIG98";
static gtASCIIString strSIG99_SIGNAL = "SIG99";
static gtASCIIString strSIG100_SIGNAL = "SIG100";
static gtASCIIString strSIG101_SIGNAL = "SIG101";
static gtASCIIString strSIG102_SIGNAL = "SIG102";
static gtASCIIString strSIG103_SIGNAL = "SIG103";
static gtASCIIString strSIG104_SIGNAL = "SIG104";
static gtASCIIString strSIG105_SIGNAL = "SIG105";
static gtASCIIString strSIG106_SIGNAL = "SIG106";
static gtASCIIString strSIG107_SIGNAL = "SIG107";
static gtASCIIString strSIG108_SIGNAL = "SIG108";
static gtASCIIString strSIG109_SIGNAL = "SIG109";
static gtASCIIString strSIG110_SIGNAL = "SIG110";
static gtASCIIString strSIG111_SIGNAL = "SIG111";
static gtASCIIString strSIG112_SIGNAL = "SIG112";
static gtASCIIString strSIG113_SIGNAL = "SIG113";
static gtASCIIString strSIG114_SIGNAL = "SIG114";
static gtASCIIString strSIG115_SIGNAL = "SIG115";
static gtASCIIString strSIG116_SIGNAL = "SIG116";
static gtASCIIString strSIG117_SIGNAL = "SIG117";
static gtASCIIString strSIG118_SIGNAL = "SIG118";
static gtASCIIString strSIG119_SIGNAL = "SIG119";
static gtASCIIString strSIG120_SIGNAL = "SIG120";
static gtASCIIString strSIG121_SIGNAL = "SIG121";
static gtASCIIString strSIG122_SIGNAL = "SIG122";
static gtASCIIString strSIG123_SIGNAL = "SIG123";
static gtASCIIString strSIG124_SIGNAL = "SIG124";
static gtASCIIString strSIG125_SIGNAL = "SIG125";
static gtASCIIString strSIG126_SIGNAL = "SIG126";
static gtASCIIString strSIG127_SIGNAL = "SIG127";
static gtASCIIString strSIGINFO_SIGNAL = "SIGINFO";
if (nullptr != _pGDBCommunicationPipe && nullptr != _pGDBDriver)
{
std::string cmd = "-exec-interrupt --all\n";
_wasGDBPrompt = false;
_pGDBCommunicationPipe->write(cmd.c_str(), cmd.length());
do
{
gtASCIIString output;
readGDBOutputLine(output);
if (output.find(s_gdbPromtStr) != -1)
{
_wasGDBPrompt = true;
}
GetStoppedThreadGDBId(output);
}
while (!_pGDBDriver->IsAllThreadsStopped() || !_wasGDBPrompt);
_wasGDBPrompt = false;
}
// Will get true iff the signal represents a breakpoint hit:
wasBreakpointHit = false;
// Will get the exception reason, if exists:
int exceptionReason = -1;
// If the debugged process got a signal:
int pos1 = gdbOutputLine.find(signalNameGDBStr);
if (pos1 != -1)
{
int pos2 = pos1 + signalNameGDBStrLen;
int pos3 = gdbOutputLine.find("\"", pos2);
GT_IF_WITH_ASSERT(pos3 != -1)
{
// Get the signal name:
gtASCIIString signalNameStr;
gdbOutputLine.getSubString(pos2, pos3 - 1, signalNameStr);
// If we got a breakpoint hit:
if (signalNameStr == sigTrapGDBStr)
{
// If this breakpoint came from the spy, report it to the application. Otherwise,
// treat it as a non-fatal signal (SIGTRAP is non-fatal):
bool wasStoppedInSpy = false;
bool rcLoc = isCurrentThreadStoppedInsideSpy(wasStoppedInSpy);
GT_ASSERT(rcLoc);
// Some applications (l3com case 7852, OpenSceneGraph) have a thread that sits in pthread_cond_wait, which is the same as the
// breakpoint triggering thread.
// This sometimes confuses gdb making it think that a different thread triggered the signal, causing spy breakpoints to be considered
// as foreign breaks, and making the app become stuck. So, to be on the safe side, before deciding a SIGTRAP is a foreign break, we
// check all threads to make sure none of them is inside the spy.
if (!wasStoppedInSpy)
{
wasStoppedInSpy = isAnyThreadStoppedInSpy();
}
wasBreakpointHit = wasStoppedInSpy;
if (wasBreakpointHit)
{
int triggeringThreadsId = GetStoppedThreadGDBId(gdbOutputLine);
/*
if (nullptr != _pGDBCommunicationPipe && nullptr != _pGDBDriver)
{
std::string cmd = "-exec-interrupt --all\n";
_pGDBCommunicationPipe->write(cmd.c_str(), cmd.length());
do
{
gtASCIIString output;
readGDBOutputLine(output);
GetStoppedThreadId(output);
} while (!_pGDBDriver->IsAllThreadsStopped());
}
*/
_debuggedProcessCurrentThreadGDBId = triggeringThreadsId;
_debuggedProcessCurrentThreadId = threadIdFromGDBId(_debuggedProcessCurrentThreadGDBId);
wasBreakpointHit = handleBreakpointHit();
}
else // !wasBreakpointHit
{
// This is a foreign breakpoint, so just treat it as a normal SIGTRAP signal:
exceptionReason = OS_SIGTRAP_SIGNAL;
}
}
else if (signalNameStr == sigStopGDBStr)
{
// Stop signal, a foreign breakpoint:
exceptionReason = OS_SIGSTOP_SIGNAL;
}
else if (signalNameStr == sigTTInGDBStr)
{
// Background read attempted from control terminal signal, a foreign breakpoint:
exceptionReason = OS_SIGTTIN_SIGNAL;
}
else if (signalNameStr == sigTTOuGDBStr)
{
// Background write attempted from control terminal signal, a foreign breakpoint:
exceptionReason = OS_SIGTTOU_SIGNAL;
}
else if (signalNameStr == sigStpGDBStr)
{
// Keyboard stop signal, a foreign breakpoint:
exceptionReason = OS_SIGTSTP_SIGNAL;
}
else if (signalNameStr == sigHupGDBStr)
{
// Hangup detected on controlling terminal or death of controlling process:
exceptionReason = OS_SIGHUP_SIGNAL;
}
else if (signalNameStr == sigQuitGDBStr)
{
// Quit from keyboard:
exceptionReason = OS_SIGQUIT_SIGNAL;
}
else if (signalNameStr == sigIllGDBStr)
{
// Illegal Instruction:
exceptionReason = OS_SIGILL_SIGNAL;
}
else if (signalNameStr == sigAbrtGDBStr)
{
// Abort signal from abort(3):
exceptionReason = OS_SIGABRT_SIGNAL;
}
else if (signalNameStr == sigBugGDBStr)
{
// Bus error:
exceptionReason = OS_SIGBUS_SIGNAL;
}
else if (signalNameStr == sigFpeGDBStr)
{
// Floating point exception:
exceptionReason = OS_SIGFPE_SIGNAL;
}
else if (signalNameStr == sigKillGDBStr)
{
// Kill signal:
exceptionReason = OS_SIGKILL_SIGNAL;
}
else if (signalNameStr == sigSegvGDBStr)
{
// Invalid memory reference:
exceptionReason = OS_SIGSEGV_SIGNAL;
}
else if (signalNameStr == sigPipeGDBStr)
{
// Broken pipe: write to pipe with no readers:
exceptionReason = OS_SIGPIPE_SIGNAL;
}
else if (signalNameStr == sigAlrmGDBStr)
{
// Timer signal from alarm(2):
exceptionReason = OS_SIGALRM_SIGNAL;
}
else if (signalNameStr == sigTermGDBStr)
{
// Termination signal:
exceptionReason = OS_SIGTERM_SIGNAL;
}
else if (signalNameStr == sigUsr1GDBStr)
{
// User-defined signal 1:
exceptionReason = OS_SIGUSR1_SIGNAL;
}
else if (signalNameStr == sigUsr2GDBStr)
{
// User-defined signal 2:
exceptionReason = OS_SIGUSR2_SIGNAL;
}
else if (signalNameStr == sigUsr2GDBStr)
{
// User-defined signal 2:
exceptionReason = OS_SIGUSR2_SIGNAL;
}
else if (signalNameStr == strSIGEMT_SIGNAL)
{
// Emulation trap
exceptionReason = OS_SIGEMT_SIGNAL;
}
else if (signalNameStr == strSIGSYS_SIGNAL)
{
// Bad system call
exceptionReason = OS_SIGSYS_SIGNAL;
}
else if (signalNameStr == strSIGURG_SIGNAL)
{
// Urgent I/O condition
exceptionReason = OS_SIGURG_SIGNAL;
}
else if (signalNameStr == strSIGSTOP_SIGNAL)
{
// Stopped (signal)
exceptionReason = OS_SIGSTOP_SIGNAL;
}
else if (signalNameStr == strSIGTSTP_SIGNAL)
{
// Stopped (user)
exceptionReason = OS_SIGTSTP_SIGNAL;
}
else if (signalNameStr == strSIGCONT_SIGNAL)
{
// Continued
exceptionReason = OS_SIGCONT_SIGNAL;
}
else if (signalNameStr == strSIGCHLD_SIGNAL)
{
// Child status changed
exceptionReason = OS_SIGCHLD_SIGNAL;
}
else if (signalNameStr == strSIGTTIN_SIGNAL)
{
// Stopped (tty input)
exceptionReason = OS_SIGTTIN_SIGNAL;
}
else if (signalNameStr == strSIGTTOU_SIGNAL)
{
// Stopped (tty output)
exceptionReason = OS_SIGTTOU_SIGNAL;
}
else if (signalNameStr == strSIGIO_SIGNAL)
{
// I/O possible
exceptionReason = OS_SIGIO_SIGNAL;
}
else if (signalNameStr == strSIGXCPU_SIGNAL)
{
// CPU time limit exceeded
exceptionReason = OS_SIGXCPU_SIGNAL;
}
else if (signalNameStr == strSIGXFSZ_SIGNAL)
{
// File size limit exceeded
exceptionReason = OS_SIGXFSZ_SIGNAL;
}
else if (signalNameStr == strSIGVTALRM_SIGNAL)
{
// Virtual timer expired
exceptionReason = OS_SIGVTALRM_SIGNAL;
}
else if (signalNameStr == strSIGPROF_SIGNAL)
{
// Profiling timer expired
exceptionReason = OS_SIGPROF_SIGNAL;
}
else if (signalNameStr == strSIGWINCH_SIGNAL)
{
// Window size changed
exceptionReason = OS_SIGWINCH_SIGNAL;
}
else if (signalNameStr == strSIGLOST_SIGNAL)
{
// Resource lost
exceptionReason = OS_SIGLOST_SIGNAL;
}
else if (signalNameStr == strSIGPWR_SIGNAL)
{
// Power fail/restart
exceptionReason = OS_SIGPWR_SIGNAL;
}
else if (signalNameStr == strSIGPOLL_SIGNAL)
{
// Pollable event occurred
exceptionReason = OS_SIGPOLL_SIGNAL;
}
else if (signalNameStr == strSIGWIND_SIGNAL)
{
// SIGWIND
exceptionReason = OS_SIGWIND_SIGNAL;
}
else if (signalNameStr == strSIGPHONE_SIGNAL)
{
// SIGPHONE
exceptionReason = OS_SIGPHONE_SIGNAL;
}
else if (signalNameStr == strSIGWAITING_SIGNAL)
{
// Process's LWPs are blocked
exceptionReason = OS_SIGWAITING_SIGNAL;
}
else if (signalNameStr == strSIGLWP_SIGNAL)
{
// Signal LWP
exceptionReason = OS_SIGLWP_SIGNAL;
}
else if (signalNameStr == strSIGDANGER_SIGNAL)
{
// Swap space dangerously low
exceptionReason = OS_SIGDANGER_SIGNAL;
}
else if (signalNameStr == strSIGGRANT_SIGNAL)
{
// Monitor mode granted
exceptionReason = OS_SIGGRANT_SIGNAL;
}
else if (signalNameStr == strSIGRETRACT_SIGNAL)
{
// Need to relinquish monitor mode
exceptionReason = OS_SIGRETRACT_SIGNAL;
}
else if (signalNameStr == strSIGMSG_SIGNAL)
{
// Monitor mode data available
exceptionReason = OS_SIGMSG_SIGNAL;
}
else if (signalNameStr == strSIGSOUND_SIGNAL)
{
// Sound completed
exceptionReason = OS_SIGSOUND_SIGNAL;
}
else if (signalNameStr == strSIGSAK_SIGNAL)
{
// Secure attention
exceptionReason = OS_SIGSAK_SIGNAL;
}
else if (signalNameStr == strSIGPRIO_SIGNAL)
{
// SIGPRIO
exceptionReason = OS_SIGPRIO_SIGNAL;
}
else if (signalNameStr == strSIGCANCEL_SIGNAL)
{
// LWP internal signal
exceptionReason = OS_SIGCANCEL_SIGNAL;
}
else if (signalNameStr == strEXC_BAD_ACCESS_SIGNAL)
{
// Could not access memory
exceptionReason = OS_EXC_BAD_ACCESS_SIGNAL;
}
else if (signalNameStr == strEXC_BAD_INSTRUCTION_SIGNAL)
{
// Illegal instruction/operand
exceptionReason = OS_EXC_BAD_INSTRUCTION_SIGNAL;
}
else if (signalNameStr == strEXC_ARITHMETIC_SIGNAL)
{
// Arithmetic exception
exceptionReason = OS_EXC_ARITHMETIC_SIGNAL;
}
else if (signalNameStr == strEXC_EMULATION_SIGNAL)
{
// Emulation instruction
exceptionReason = OS_EXC_EMULATION_SIGNAL;
}
else if (signalNameStr == strEXC_SOFTWARE_SIGNAL)
{
// Software generated exception
exceptionReason = OS_EXC_SOFTWARE_SIGNAL;
}
else if (signalNameStr == strEXC_BREAKPOINT_SIGNAL)
{
// Breakpoint
exceptionReason = OS_EXC_BREAKPOINT_SIGNAL;
}
else if (signalNameStr == strSIG32_SIGNAL)
{
// Real-time event 32
exceptionReason = OS_SIG32_SIGNAL;
}
else if (signalNameStr == strSIG33_SIGNAL)
{
// Real-time event 33
exceptionReason = OS_SIG33_SIGNAL;
}
else if (signalNameStr == strSIG34_SIGNAL)
{
// Real-time event 34
exceptionReason = OS_SIG34_SIGNAL;
}
else if (signalNameStr == strSIG35_SIGNAL)
{
// Real-time event 35
exceptionReason = OS_SIG35_SIGNAL;
}
else if (signalNameStr == strSIG36_SIGNAL)
{
// Real-time event 36
exceptionReason = OS_SIG36_SIGNAL;
}
else if (signalNameStr == strSIG37_SIGNAL)
{
// Real-time event 37
exceptionReason = OS_SIG37_SIGNAL;
}
else if (signalNameStr == strSIG38_SIGNAL)
{
// Real-time event 38
exceptionReason = OS_SIG38_SIGNAL;
}
else if (signalNameStr == strSIG39_SIGNAL)
{
// Real-time event 39
exceptionReason = OS_SIG39_SIGNAL;
}
else if (signalNameStr == strSIG40_SIGNAL)
{
// Real-time event 40
exceptionReason = OS_SIG40_SIGNAL;
}
else if (signalNameStr == strSIG41_SIGNAL)
{
// Real-time event 41
exceptionReason = OS_SIG41_SIGNAL;
}
else if (signalNameStr == strSIG42_SIGNAL)
{
// Real-time event 42
exceptionReason = OS_SIG42_SIGNAL;
}
else if (signalNameStr == strSIG43_SIGNAL)
{
// Real-time event 43
exceptionReason = OS_SIG43_SIGNAL;
}
else if (signalNameStr == strSIG44_SIGNAL)
{
// Real-time event 44
exceptionReason = OS_SIG44_SIGNAL;
}
else if (signalNameStr == strSIG45_SIGNAL)
{
// Real-time event 45
exceptionReason = OS_SIG45_SIGNAL;
}
else if (signalNameStr == strSIG46_SIGNAL)
{
// Real-time event 46
exceptionReason = OS_SIG46_SIGNAL;
}
else if (signalNameStr == strSIG47_SIGNAL)
{
// Real-time event 47
exceptionReason = OS_SIG47_SIGNAL;
}
else if (signalNameStr == strSIG48_SIGNAL)
{
// Real-time event 48
exceptionReason = OS_SIG48_SIGNAL;
}
else if (signalNameStr == strSIG49_SIGNAL)
{
// Real-time event 49
exceptionReason = OS_SIG49_SIGNAL;
}
else if (signalNameStr == strSIG50_SIGNAL)
{
// Real-time event 50
exceptionReason = OS_SIG50_SIGNAL;
}
else if (signalNameStr == strSIG51_SIGNAL)
{
// Real-time event 51
exceptionReason = OS_SIG51_SIGNAL;
}
else if (signalNameStr == strSIG52_SIGNAL)
{
// Real-time event 52
exceptionReason = OS_SIG52_SIGNAL;
}
else if (signalNameStr == strSIG53_SIGNAL)
{
// Real-time event 53
exceptionReason = OS_SIG53_SIGNAL;
}
else if (signalNameStr == strSIG54_SIGNAL)
{
// Real-time event 54
exceptionReason = OS_SIG54_SIGNAL;
}
else if (signalNameStr == strSIG55_SIGNAL)
{
// Real-time event 55
exceptionReason = OS_SIG55_SIGNAL;
}
else if (signalNameStr == strSIG56_SIGNAL)
{
// Real-time event 56
exceptionReason = OS_SIG56_SIGNAL;
}
else if (signalNameStr == strSIG57_SIGNAL)
{
// Real-time event 57
exceptionReason = OS_SIG57_SIGNAL;
}
else if (signalNameStr == strSIG58_SIGNAL)
{
// Real-time event 58
exceptionReason = OS_SIG58_SIGNAL;
}
else if (signalNameStr == strSIG59_SIGNAL)
{
// Real-time event 59
exceptionReason = OS_SIG59_SIGNAL;
}
else if (signalNameStr == strSIG60_SIGNAL)
{
// Real-time event 60
exceptionReason = OS_SIG60_SIGNAL;
}
else if (signalNameStr == strSIG61_SIGNAL)
{
// Real-time event 61
exceptionReason = OS_SIG61_SIGNAL;
}
else if (signalNameStr == strSIG62_SIGNAL)
{
// Real-time event 62
exceptionReason = OS_SIG62_SIGNAL;
}
else if (signalNameStr == strSIG63_SIGNAL)
{
// Real-time event 63
exceptionReason = OS_SIG63_SIGNAL;
}
else if (signalNameStr == strSIG64_SIGNAL)
{
// Real-time event 64
exceptionReason = OS_SIG64_SIGNAL;
}
else if (signalNameStr == strSIG65_SIGNAL)
{
// Real-time event 65
exceptionReason = OS_SIG65_SIGNAL;
}
else if (signalNameStr == strSIG66_SIGNAL)
{
// Real-time event 66
exceptionReason = OS_SIG66_SIGNAL;
}
else if (signalNameStr == strSIG67_SIGNAL)
{
// Real-time event 67
exceptionReason = OS_SIG67_SIGNAL;
}
else if (signalNameStr == strSIG68_SIGNAL)
{
// Real-time event 68
exceptionReason = OS_SIG68_SIGNAL;
}
else if (signalNameStr == strSIG69_SIGNAL)
{
// Real-time event 69
exceptionReason = OS_SIG69_SIGNAL;
}
else if (signalNameStr == strSIG70_SIGNAL)
{
// Real-time event 70
exceptionReason = OS_SIG70_SIGNAL;
}
else if (signalNameStr == strSIG71_SIGNAL)
{
// Real-time event 71
exceptionReason = OS_SIG71_SIGNAL;
}
else if (signalNameStr == strSIG72_SIGNAL)
{
// Real-time event 72
exceptionReason = OS_SIG72_SIGNAL;
}
else if (signalNameStr == strSIG73_SIGNAL)
{
// Real-time event 73
exceptionReason = OS_SIG73_SIGNAL;
}
else if (signalNameStr == strSIG74_SIGNAL)
{
// Real-time event 74
exceptionReason = OS_SIG74_SIGNAL;
}
else if (signalNameStr == strSIG75_SIGNAL)
{
// Real-time event 75
exceptionReason = OS_SIG75_SIGNAL;
}
else if (signalNameStr == strSIG76_SIGNAL)
{
// Real-time event 76
exceptionReason = OS_SIG76_SIGNAL;
}
else if (signalNameStr == strSIG77_SIGNAL)
{
// Real-time event 77
exceptionReason = OS_SIG77_SIGNAL;
}
else if (signalNameStr == strSIG78_SIGNAL)
{
// Real-time event 78
exceptionReason = OS_SIG78_SIGNAL;
}
else if (signalNameStr == strSIG79_SIGNAL)
{
// Real-time event 79
exceptionReason = OS_SIG79_SIGNAL;
}
else if (signalNameStr == strSIG80_SIGNAL)
{
// Real-time event 80
exceptionReason = OS_SIG80_SIGNAL;
}
else if (signalNameStr == strSIG81_SIGNAL)
{
// Real-time event 81
exceptionReason = OS_SIG81_SIGNAL;
}
else if (signalNameStr == strSIG82_SIGNAL)
{
// Real-time event 82
exceptionReason = OS_SIG82_SIGNAL;
}
else if (signalNameStr == strSIG83_SIGNAL)
{
// Real-time event 83
exceptionReason = OS_SIG83_SIGNAL;
}
else if (signalNameStr == strSIG84_SIGNAL)
{
// Real-time event 84
exceptionReason = OS_SIG84_SIGNAL;
}
else if (signalNameStr == strSIG85_SIGNAL)
{
// Real-time event 85
exceptionReason = OS_SIG85_SIGNAL;
}
else if (signalNameStr == strSIG86_SIGNAL)
{
// Real-time event 86
exceptionReason = OS_SIG86_SIGNAL;
}
else if (signalNameStr == strSIG87_SIGNAL)
{
// Real-time event 87
exceptionReason = OS_SIG87_SIGNAL;
}
else if (signalNameStr == strSIG88_SIGNAL)
{
// Real-time event 88
exceptionReason = OS_SIG88_SIGNAL;
}
else if (signalNameStr == strSIG89_SIGNAL)
{
// Real-time event 89
exceptionReason = OS_SIG89_SIGNAL;
}
else if (signalNameStr == strSIG90_SIGNAL)
{
// Real-time event 90
exceptionReason = OS_SIG90_SIGNAL;
}
else if (signalNameStr == strSIG91_SIGNAL)
{
// Real-time event 91
exceptionReason = OS_SIG91_SIGNAL;
}
else if (signalNameStr == strSIG92_SIGNAL)
{
// Real-time event 92
exceptionReason = OS_SIG92_SIGNAL;
}
else if (signalNameStr == strSIG93_SIGNAL)
{
// Real-time event 93
exceptionReason = OS_SIG93_SIGNAL;
}
else if (signalNameStr == strSIG94_SIGNAL)
{
// Real-time event 94
exceptionReason = OS_SIG94_SIGNAL;
}
else if (signalNameStr == strSIG95_SIGNAL)
{
// Real-time event 95
exceptionReason = OS_SIG95_SIGNAL;
}
else if (signalNameStr == strSIG96_SIGNAL)
{
// Real-time event 96
exceptionReason = OS_SIG96_SIGNAL;
}
else if (signalNameStr == strSIG97_SIGNAL)
{
// Real-time event 97
exceptionReason = OS_SIG97_SIGNAL;
}
else if (signalNameStr == strSIG98_SIGNAL)
{
// Real-time event 98
exceptionReason = OS_SIG98_SIGNAL;
}
else if (signalNameStr == strSIG99_SIGNAL)
{
// Real-time event 99
exceptionReason = OS_SIG99_SIGNAL;
}
else if (signalNameStr == strSIG100_SIGNAL)
{
// Real-time event 100
exceptionReason = OS_SIG100_SIGNAL;
}
else if (signalNameStr == strSIG101_SIGNAL)
{
// Real-time event 101
exceptionReason = OS_SIG101_SIGNAL;
}
else if (signalNameStr == strSIG102_SIGNAL)
{
// Real-time event 102
exceptionReason = OS_SIG102_SIGNAL;
}
else if (signalNameStr == strSIG103_SIGNAL)
{
// Real-time event 103
exceptionReason = OS_SIG103_SIGNAL;
}
else if (signalNameStr == strSIG104_SIGNAL)
{
// Real-time event 104
exceptionReason = OS_SIG104_SIGNAL;
}
else if (signalNameStr == strSIG105_SIGNAL)
{
// Real-time event 105
exceptionReason = OS_SIG105_SIGNAL;
}
else if (signalNameStr == strSIG106_SIGNAL)
{
// Real-time event 106
exceptionReason = OS_SIG106_SIGNAL;
}
else if (signalNameStr == strSIG107_SIGNAL)
{
// Real-time event 107
exceptionReason = OS_SIG107_SIGNAL;
}
else if (signalNameStr == strSIG108_SIGNAL)
{
// Real-time event 108
exceptionReason = OS_SIG108_SIGNAL;
}
else if (signalNameStr == strSIG109_SIGNAL)
{
// Real-time event 109
exceptionReason = OS_SIG109_SIGNAL;
}
else if (signalNameStr == strSIG110_SIGNAL)
{
// Real-time event 110
exceptionReason = OS_SIG110_SIGNAL;
}
else if (signalNameStr == strSIG111_SIGNAL)
{
// Real-time event 111
exceptionReason = OS_SIG111_SIGNAL;
}
else if (signalNameStr == strSIG112_SIGNAL)
{
// Real-time event 112
exceptionReason = OS_SIG112_SIGNAL;
}
else if (signalNameStr == strSIG113_SIGNAL)
{
// Real-time event 113
exceptionReason = OS_SIG113_SIGNAL;
}
else if (signalNameStr == strSIG114_SIGNAL)
{
// Real-time event 114
exceptionReason = OS_SIG114_SIGNAL;
}
else if (signalNameStr == strSIG115_SIGNAL)
{
// Real-time event 115
exceptionReason = OS_SIG115_SIGNAL;
}
else if (signalNameStr == strSIG116_SIGNAL)
{
// Real-time event 116
exceptionReason = OS_SIG116_SIGNAL;
}
else if (signalNameStr == strSIG117_SIGNAL)
{
// Real-time event 117
exceptionReason = OS_SIG117_SIGNAL;
}
else if (signalNameStr == strSIG118_SIGNAL)
{
// Real-time event 118
exceptionReason = OS_SIG118_SIGNAL;
}
else if (signalNameStr == strSIG119_SIGNAL)
{
// Real-time event 119
exceptionReason = OS_SIG119_SIGNAL;
}
else if (signalNameStr == strSIG120_SIGNAL)
{
// Real-time event 120
exceptionReason = OS_SIG120_SIGNAL;
}
else if (signalNameStr == strSIG121_SIGNAL)
{
// Real-time event 121
exceptionReason = OS_SIG121_SIGNAL;
}
else if (signalNameStr == strSIG122_SIGNAL)
{
// Real-time event 122
exceptionReason = OS_SIG122_SIGNAL;
}
else if (signalNameStr == strSIG123_SIGNAL)
{
// Real-time event 123
exceptionReason = OS_SIG123_SIGNAL;
}
else if (signalNameStr == strSIG124_SIGNAL)
{
// Real-time event 124
exceptionReason = OS_SIG124_SIGNAL;
}
else if (signalNameStr == strSIG125_SIGNAL)
{
// Real-time event 125
exceptionReason = OS_SIG125_SIGNAL;
}
else if (signalNameStr == strSIG126_SIGNAL)
{
// Real-time event 126
exceptionReason = OS_SIG126_SIGNAL;
}
else if (signalNameStr == strSIG127_SIGNAL)
{
// Real-time event 127
exceptionReason = OS_SIG127_SIGNAL;
}
else if (signalNameStr == strSIGINFO_SIGNAL)
{
// Information request
exceptionReason = OS_SIGINFO_SIGNAL;
}
else if ((signalNameStr == sigThreadStopped) || (signalNameStr == sigIntGDBStr))
{
int threadId = GetStoppedThreadGDBId(gdbOutputLine);
if (threadId == -1)
{
_wasDebuggedProcessSuspended = _pGDBDriver->IsAllThreadsStopped();
}
else
{
_wasDebuggedProcessSuspended = true;
}
exceptionReason = (signalNameStr == sigThreadStopped) ? OS_STANDALONE_THREAD_STOPPED : OS_SIGINT_SIGNAL;
}
else
{
// An unknown signal was received by the debugged process:
exceptionReason = OS_UNKNOWN_EXCEPTION_REASON;
// Assert:
gtString errorMsg; errorMsg.fromASCIIString(signalNameStr.asCharArray());
errorMsg.prepend(L": ").prepend(PD_STR_unknownSignalReceived);
GT_ASSERT_EX(false, errorMsg.asCharArray());
}
// If the debugged process encountered an exception:
if ((-1 != exceptionReason) && (OS_STANDALONE_THREAD_STOPPED != exceptionReason) && (OS_SIGINT_SIGNAL != exceptionReason))
{
handleException(exceptionReason);
}
}
}
}
//////////////////////////////////////////////////////////////////
/// \brief Parsing "*stopped..." gdb output line and find a stopped thread id
///
/// \param gdbOutputLine a line readed from gdb output pipe
///
/// \return stoped thread Id, 0 - in case all threads stopped, -1 in case error
///
/// \author <NAME>
/// \date 14/1/2016
int pdGDBOutputReader::GetStoppedThreadGDBId(const gtASCIIString& gdbOutputLine)
{
int result = -1;
GT_IF_WITH_ASSERT(_pGDBDriver)
{
int pos1 = gdbOutputLine.find(s_stoppedThreads);
while (-1 != pos1)
{
int length = s_stoppedThreads.length();
int pos2 = gdbOutputLine.find("\"]", pos1 + length);
GT_IF_WITH_ASSERT(-1 != pos2)
{
gtASCIIString strThreadId;
gdbOutputLine.getSubString(pos1 + length, pos2 - 1, strThreadId);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(strThreadId.toIntNumber(threadGDBId))
{
_pGDBDriver->OnThreadGDBStopped(threadGDBId);
result = threadGDBId;
}
}
pos1 = gdbOutputLine.find(s_stoppedThreads, pos2);
}
pos1 = gdbOutputLine.find(s_exitingThread);
while (-1 != pos1)
{
int length = s_exitingThread.length();
int pos2 = gdbOutputLine.find("\"", pos1 + length);
GT_IF_WITH_ASSERT(-1 != pos2)
{
gtASCIIString strThreadId;
gdbOutputLine.getSubString(pos1 + length, pos2 - 1, strThreadId);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(strThreadId.toIntNumber(threadGDBId))
{
_pGDBDriver->OnThreadExit(threadGDBId);
result = threadGDBId;
}
}
pos1 = gdbOutputLine.find(s_exitingThread, pos2);
}
pos1 = gdbOutputLine.find("bkptno");
while (pos1 != -1)
{
// Host breakpoint
pos1 = gdbOutputLine.find("thread-id=\"", pos1);
if (-1 != pos1)
{
int length = ::strlen("thread-id=\"");
int pos2 = gdbOutputLine.find("\"", pos1 + length);
GT_IF_WITH_ASSERT(-1 != pos2)
{
gtASCIIString strThreadId;
gdbOutputLine.getSubString(pos1 + length, pos2 - 1, strThreadId);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(strThreadId.toIntNumber(threadGDBId))
{
_pGDBDriver->OnThreadGDBStopped(threadGDBId);
}
}
pos1 = gdbOutputLine.find("bkptno", pos2);
}
}
}
return result;
}
/////////////////////////////////////////////////////////////////
/// \brief Parse "*running, thread-id="... " message
///
/// \param gdbOutputLine a parsing gdb output string
/// \return threadId or -1
///
/// \author <NAME>
/// \date 18/01/2016
int pdGDBOutputReader::GetRunningThreadGDBId(const gtASCIIString& gdbOutputLine)
{
int result = -1;
GT_IF_WITH_ASSERT(_pGDBDriver)
{
int pos1 = gdbOutputLine.find(s_runningThreadMsg);
while (-1 != pos1)
{
int length = s_runningThreadMsg.length();
int pos2 = gdbOutputLine.find("\"", pos1 + length);
GT_IF_WITH_ASSERT(-1 != pos2)
{
gtASCIIString strThreadId;
gdbOutputLine.getSubString(pos1 + length, pos2 - 1, strThreadId);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(strThreadId.toIntNumber(threadGDBId))
{
_pGDBDriver->OnThreadGDBResumed(threadGDBId);
result = threadGDBId;
}
}
pos1 = gdbOutputLine.find(s_runningThreadMsg, pos2);
}
pos1 = gdbOutputLine.find("bkptno");
while (pos1 != -1)
{
// Host breakpoint
pos1 = gdbOutputLine.find("thread-id=\"", pos1);
if (-1 != pos1)
{
int length = ::strlen("thread-id=\"");
int pos2 = gdbOutputLine.find("\"", pos1 + length);
GT_IF_WITH_ASSERT(-1 != pos2)
{
gtASCIIString strThreadId;
gdbOutputLine.getSubString(pos1 + length, pos2 - 1, strThreadId);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(strThreadId.toIntNumber(threadGDBId))
{
_pGDBDriver->OnThreadGDBStopped(threadGDBId);
}
}
pos1 = gdbOutputLine.find("bkptno", pos2);
}
}
}
return result;
}
////////////////////////////////////////////////////////////////////
/// \brief Parsing "thread exited" message
/// \param gdbOutputLine - GDB's output line.
///
/// \author <NAME>
/// \date 01/02/2016
void pdGDBOutputReader::handleExitThreadMessage(const gtASCIIString& gdbOutputLine)
{
static gtASCIIString s_StartStr = "=thread-exited,id=\"";
// Get the OS LWP id
unsigned long gdbThreadId = 0;
int pos1 = gdbOutputLine.find(s_StartStr);
if (pos1 != -1 && nullptr != _pGDBDriver)
{
int pos2 = pos1 + s_StartStr.length();
int pos3 = gdbOutputLine.find("\"", pos2);
if (pos3 != -1)
{
gtASCIIString idString;
gdbOutputLine.getSubString(pos2, pos3, idString);
bool rc1 = idString.toUnsignedLongNumber(gdbThreadId);
GT_ASSERT(rc1);
_pGDBDriver->OnThreadExit(gdbThreadId);
if (0 == _pGDBDriver->GetRunnungThreadsCount())
{
_wasDebuggedProcessCreated = false;
_wasDebuggedProcessSuspended = false;
_wasDebuggedProcessTerminated = true;
m_didDebuggedProcessReceiveFatalSignal = false;
_debuggedProcessCurrentThreadGDBId = -1;
_debuggedProcessCurrentThreadId = OS_NO_THREAD_ID;
_processId = 0;
// Trigger a process terminated event:
apDebuggedProcessTerminatedEvent* pDebuggedProcessTerminationEvent = new apDebuggedProcessTerminatedEvent(0);
m_eventsToRegister.push_back(pDebuggedProcessTerminationEvent);
}
}
}
}
bool pdGDBOutputReader::handleHostSteps(const gtASCIIString& gdbOutputLine, const pdGDBData** ppGDBOutputData)
{
GT_UNREFERENCED_PARAMETER(ppGDBOutputData);
bool retVal = true;
if (gdbOutputLine.find("*running") != -1)
{
if (gdbOutputLine.find("*stopped") == -1)
{
GetRunningThreadGDBId(gdbOutputLine);
}
else
{
gtASCIIString stoppedStr = "";
gdbOutputLine.getSubString(gdbOutputLine.find("*stopped"), gdbOutputLine.length() - 1, stoppedStr);
retVal = handleAsynchronousOutput(gdbOutputLine);
}
}
else if (gdbOutputLine.find("*stopped") != -1)
{
gtASCIIString stoppedStr = "";
gdbOutputLine.getSubString(gdbOutputLine.find("*stopped"), gdbOutputLine.length() - 1, stoppedStr);
retVal = handleAsynchronousOutput(gdbOutputLine);
}
else if (gdbOutputLine.find("^error") != -1)
{
/// Step Out from main. gdb can't proceed "-exec-finish" from main frame and
/// print error: not meaningful in the outermost frame
/// Application have to catch this issue and just resume continue.
GT_IF_WITH_ASSERT(ppGDBOutputData)
{
*ppGDBOutputData = new pdGDBHostStepErrorInfoIndex(gdbOutputLine);
if (gdbOutputLine.find("not meaningful in the outermost frame") == -1)
{
retVal = false;
}
}
else
{
retVal = false;
}
}
return retVal;
}
bool pdGDBOutputReader::handleGetVariableTypeGDBOutput(const gtASCIIString& gdbOutputLine, const pdGDBData** ppGDBOutputData)
{
bool result = false;
const gtASCIIString startTypeAnswer = "type = ";
int posStart = gdbOutputLine.find(startTypeAnswer);
if (-1 != posStart)
{
posStart += startTypeAnswer.length();
int posEnd = gdbOutputLine.find("\n", posStart);
GT_IF_WITH_ASSERT(-1 != posEnd)
{
gtASCIIString variableType = "";
posEnd -= 4;
gdbOutputLine.getSubString(posStart, posEnd, variableType);
GT_IF_WITH_ASSERT(nullptr != ppGDBOutputData)
{
gtString vType;
vType.fromASCIIString(variableType.asCharArray());
*ppGDBOutputData = new pdGDBFVariableType(vType);
result = true;
}
}
}
else
{
if (gdbOutputLine.find("^error") != -1)
{
GT_IF_WITH_ASSERT(gdbOutputLine.find("No symbol") != -1 && gdbOutputLine.find("in current context") != -1)
{
// Legal situation. Symbol type not found in release build
*ppGDBOutputData = new pdGDBFVariableType(L"No symbol in current context");
result = true;
}
}
}
return result;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleNewThreadMessage
// Description: Is called when GDB outputs the ""[New Thread..."
// message.
// Arguments: gdbOutputLine - GDB's output line.
// Author: <NAME>
// Date: 8/7/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::handleNewThreadMessage(const gtASCIIString& gdbOutputLine)
{
#if AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT
{
// Uri, 8/3/09: The Mac version of gdb does not currently report thread created
// events at all, so we do not need to translate these output strings to debugged
// process events. We leave this #ifdef-ed out, since if the Mac gdb would at some
// point report these events, they would probably not be in the same form (LWP
// does not exist in Mac, for one)
OS_OUTPUT_DEBUG_LOG(L"Ignoring thread creation output", OS_DEBUG_LOG_DEBUG);
}
#else
{
static gtASCIIString s_gdbfindLwpIdStr = "(LWP ";
static gtASCIIString s_gdbfindThreadIdStr1 = "[New Thread ";
static gtASCIIString s_gdbfindThreadIdStr2 = "=thread-created,id=\"";
// Get the OS LWP id
osThreadId lwpOSId = OS_NO_THREAD_ID;
int pos1 = gdbOutputLine.find(s_gdbfindLwpIdStr);
if (pos1 != -1)
{
int pos2 = pos1 + s_gdbfindLwpIdStr.length();
int pos3 = gdbOutputLine.find(')', pos2);
if (pos3 != -1)
{
gtASCIIString lwpIdString;
gdbOutputLine.getSubString(pos2, pos3, lwpIdString);
bool rc1 = lwpIdString.toUnsignedLongNumber(lwpOSId);
GT_ASSERT(rc1);
}
}
// Get the OS thread id
osThreadId threadOSId = OS_NO_THREAD_ID;
int pos11 = gdbOutputLine.find(s_gdbfindThreadIdStr1);
if (pos11 != -1)
{
int pos12 = pos11 + s_gdbfindThreadIdStr1.length();
int pos13 = gdbOutputLine.find(" (", pos12);
if (pos13 != -1)
{
gtASCIIString threadIdString;
gdbOutputLine.getSubString(pos12, pos13, threadIdString);
bool rc1 = threadIdString.toUnsignedLongNumber(threadOSId);
GT_ASSERT(rc1);
}
}
else
{
pos11 = gdbOutputLine.find(s_gdbfindThreadIdStr2);
if (pos11 != -1)
{
int pos12 = pos11 + s_gdbfindThreadIdStr2.length();
int pos13 = gdbOutputLine.find("\"", pos12);
if (pos13 != -1)
{
gtASCIIString threadIdString;
gdbOutputLine.getSubString(pos12, pos13 - 1, threadIdString);
int threadGDBId = 0;
GT_IF_WITH_ASSERT(threadIdString.toIntNumber(threadGDBId))
{
GT_IF_WITH_ASSERT(_pGDBDriver)
{
_pGDBDriver->OnThreadCreated(threadGDBId);
}
}
}
}
return;
}
// Get the OS thread start address:
osInstructionPointer threadStartAddress = NULL;
int pos4 = s_newThreadMsg.length();
int pos5 = gdbOutputLine.find(' ', pos4);
if (pos5 != -1)
{
gtASCIIString threadStartAddressStr;
gdbOutputLine.getSubString(pos4, pos5, threadStartAddressStr);
#if ((AMDT_BUILD_TARGET == AMDT_LINUX_OS) && (AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT))
int rc1 = 0;
if (_debuggedExecutableArchitecture == OS_I386_ARCHITECTURE)
{
rc1 = ::sscanf(threadStartAddressStr.asCharArray(), "%p", &threadStartAddress);
}
else if (_debuggedExecutableArchitecture == OS_X86_64_ARCHITECTURE)
{
rc1 = ::sscanf(threadStartAddressStr.asCharArray(), "0x%llx", &threadStartAddress);
}
else
{
// Unsupported or unknown architecture, we should not get here!
GT_ASSERT(false);
}
#else
int rc1 = ::sscanf(threadStartAddressStr.asCharArray(), "%p", &threadStartAddress);
#endif
GT_ASSERT(rc1 == 1);
}
// Get the current time:
osTime threadCreationTime;
threadCreationTime.setFromCurrentTime();
// Raise an appropriate event:
apThreadCreatedEvent* pThreadCreatedEvent = new apThreadCreatedEvent(threadOSId, lwpOSId, threadCreationTime, threadStartAddress);
m_eventsToRegister.push_back(pThreadCreatedEvent);
}
#endif
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleSwitchingToThreadMessage
// Description: Is called when GDB outputs the "[Switching to Thread..."
// message.
// Arguments: gdbOutputLine - GDB's output line.
// Author: <NAME>
// Date: 8/7/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::handleSwitchingToThreadMessage(const gtASCIIString& gdbOutputLine)
{
static int sizeOfSwitchingThreadMgs = s_switchingToThreadMsg.length();
// Look for the position of the "[Switching to Thread..." message:
int switchingThreadMsgPos = gdbOutputLine.find(s_switchingToThreadMsg);
GT_IF_WITH_ASSERT(switchingThreadMsgPos != -1)
{
// Look for the space that ends the thread id:
int pos1 = gdbOutputLine.find(' ', switchingThreadMsgPos + sizeOfSwitchingThreadMgs + 1);
GT_IF_WITH_ASSERT(pos1 != -1)
{
// Get the thread id string:
gtASCIIString threadIdAsString;
gdbOutputLine.getSubString(switchingThreadMsgPos + sizeOfSwitchingThreadMgs + 1, pos1 - 1, threadIdAsString);
// Translate it to osThreadId:
int threadGDBId = 0;
bool rc1 = threadIdAsString.toIntNumber(threadGDBId);
GT_IF_WITH_ASSERT(rc1)
{
_debuggedProcessCurrentThreadGDBId = threadGDBId;
_debuggedProcessCurrentThreadId = threadIdFromGDBId(_debuggedProcessCurrentThreadGDBId);
}
}
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleSwitchingToProcessMessage
// Description: Is called when GDB outputs the "[Switching to process..."
// message.
// Arguments: gdbOutputLine - GDB's output line.
// Author: <NAME>ka
// Date: 17/12/2008
// Implementation notes:
// On Leopard and Linux, the message format is: ~[Switching to process 15109 local thread 0x2e03]\n
// On Snow Leopard, the message format is: ~[Switching to process]\n
// ---------------------------------------------------------------------------
void pdGDBOutputReader::handleSwitchingToProcessMessage(const gtASCIIString& gdbOutputLine)
{
static int sizeOfSwitchingToProcessMgs = s_switchingToProcessMsg.length();
// Look for the position of the "[Switching to process..." message:
int switchingToProcessMsgPos = gdbOutputLine.find(s_switchingToProcessMsg);
GT_IF_WITH_ASSERT(switchingToProcessMsgPos != -1)
{
// Look for the space that ends the process id:
int pos1 = gdbOutputLine.find(' ', switchingToProcessMsgPos + sizeOfSwitchingToProcessMgs + 1);
if (pos1 == -1)
{
// On Snow leopard, we need to look for the ] that ends the process id:
pos1 = gdbOutputLine.find(']', switchingToProcessMsgPos + sizeOfSwitchingToProcessMgs + 1);
}
GT_IF_WITH_ASSERT(pos1 != -1)
{
// Get the process id string:
gtASCIIString processIdAsString;
gdbOutputLine.getSubString(switchingToProcessMsgPos + sizeOfSwitchingToProcessMgs + 1, pos1 - 1, processIdAsString);
// Translate it to osProcessId:
long debuggedProcessId = 0;
bool rc1 = processIdAsString.toLongNumber(debuggedProcessId);
GT_IF_WITH_ASSERT(rc1)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
// Output a debug string:
gtString dbgMsg = PD_STR_debuggedProcessPID;
dbgMsg.appendFormattedString(L"%d", debuggedProcessId);
OS_OUTPUT_DEBUG_LOG(dbgMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
// Don't notify this more than once (Apple's gdb V. 1344 - 6.3.50 shows "switch to process" for every break)
if (!_wasDebuggedProcessCreated)
{
_wasDebuggedProcessCreated = true;
// Notify that the debugged process run started:
osTime processRunStartedTime;
processRunStartedTime.setFromCurrentTime();
apDebuggedProcessRunStartedEvent* pProcessRunStartedEvent = new apDebuggedProcessRunStartedEvent(debuggedProcessId, processRunStartedTime);
m_eventsToRegister.push_back(pProcessRunStartedEvent);
}
}
}
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleSwitchingToProcessAndThreadMessage
// Description: Handle the output of thread changing in Mac (which also reports
// the process name)
// Author: <NAME>
// Date: 25/2/2009
// ---------------------------------------------------------------------------
void pdGDBOutputReader::handleSwitchingToProcessAndThreadMessage(const gtASCIIString& gdbOutputLine)
{
static const gtASCIIString processIndicator = "process";
static const gtASCIIString threadIndicator = "thread";
static const gtASCIIString localIndicator = "local";
unsigned long processId = 0;
int threadGDBId = 0;
bool isLocal = false;
gtASCIIStringTokenizer strTokenizer(gdbOutputLine, " ");
gtASCIIString currentToken;
while (strTokenizer.getNextToken(currentToken))
{
if (currentToken.compareNoCase(processIndicator) == 0)
{
// This is the process ID:
bool rcToken = strTokenizer.getNextToken(currentToken);
GT_IF_WITH_ASSERT(rcToken)
{
bool rcNum = currentToken.toUnsignedLongNumber(processId);
if (!rcNum)
{
GT_ASSERT(rcNum);
processId = 0;
}
}
}
else if (currentToken.compareNoCase(threadIndicator) == 0)
{
bool rcToken = strTokenizer.getNextToken(currentToken);
GT_IF_WITH_ASSERT(rcToken)
{
bool rcNum = currentToken.toIntNumber(threadGDBId);
if (!rcNum)
{
GT_ASSERT(rcNum);
threadGDBId = -1;
}
}
}
else if (currentToken.compareNoCase(localIndicator) == 0)
{
bool rcToken = strTokenizer.getNextToken(currentToken);
GT_IF_WITH_ASSERT(rcToken)
{
// Verify the next token is the "thread", then skip it:
GT_IF_WITH_ASSERT(currentToken.compareNoCase(threadIndicator) == 0)
{
rcToken = strTokenizer.getNextToken(currentToken);
GT_IF_WITH_ASSERT(rcToken)
{
threadGDBId = -1;
isLocal = true;
bool rcNum = currentToken.toIntNumber(threadGDBId);
if (!rcNum)
{
GT_ASSERT(rcNum);
threadGDBId = -1;
}
}
}
}
}
}
GT_IF_WITH_ASSERT((processId != 0) && (threadGDBId != 0))
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
// Output a debug string:
gtString dbgMsg = PD_STR_debuggedProcessPID;
dbgMsg.appendFormattedString(L"%d", processId);
dbgMsg.appendFormattedString(PD_STR_debuggedProcessCurrentTID, threadGDBId);
OS_OUTPUT_DEBUG_LOG(dbgMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
// We have no way to handle local thread ids, so we only register if the thread
// is not local (this event is pretty much ignored anyway)
if (!isLocal)
{
_debuggedProcessCurrentThreadGDBId = threadGDBId;
_debuggedProcessCurrentThreadId = threadIdFromGDBId(_debuggedProcessCurrentThreadGDBId);
}
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleBreakpointHit
// Description: Is called when the debugged process hits a breakpoint
// Author: <NAME>
// Date: 27/6/2007
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleBreakpointHit(bool isGDBBreakpoint, bool isStep)
{
// Will get true iff we want to consider this breakpoint as a real breakpoint:
bool retVal = true;
bool sendEvent = true;
// Ignore the breakpoints used to synchronize the beginning and end of kernel debugging:
apBreakReason breakReason = AP_FOREIGN_BREAK_HIT;
if (_isKernelDebuggingAboutToStart)
{
retVal = false;
_isKernelDebuggingAboutToStart = false;
breakReason = AP_BEFORE_KERNEL_DEBUGGING_HIT;
}
else if (_isKernelDebuggingJustFinished)
{
retVal = false;
_isKernelDebuggingJustFinished = false;
breakReason = AP_AFTER_KERNEL_DEBUGGING_HIT;
}
else if (isGDBBreakpoint)
{
breakReason = AP_HOST_BREAKPOINT_HIT;
}
else if (isStep)
{
// TO_DO:
// breakReason = m_lastStepKind;
breakReason = AP_STEP_OVER_BREAKPOINT_HIT;
}
// If this is a breakpoint we want to report:
if (sendEvent)
{
// Trigger a breakpoint hit event:
apBreakpointHitEvent* pBreakpointHitEvent = new apBreakpointHitEvent(_debuggedProcessCurrentThreadId, NULL);
if (breakReason != AP_FOREIGN_BREAK_HIT)
{
pBreakpointHitEvent->setBreakReason(breakReason);
}
m_eventsToRegister.push_back(pBreakpointHitEvent);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleException
// Description: Is called when the debugged process gets an exception (=signal)
// Arguments: excetionReason - The exception reason in osExceptionReason values.
// Author: <NAME>
// Date: 27/6/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::handleException(int excetionReason)
{
// Trigger a "first chance" exception event:
apExceptionEvent* pExceptionEvent = new apExceptionEvent(_debuggedProcessCurrentThreadId, (osExceptionReason)excetionReason, NULL, false);
m_didDebuggedProcessReceiveFatalSignal = pExceptionEvent->isFatalLinuxSignal();
m_eventsToRegister.push_back(pExceptionEvent);
// If this is a crash signal, note that the debugged process is suspended before crashing:
if (m_didDebuggedProcessReceiveFatalSignal)
{
_wasDebuggedProcessSuspended = true;
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleSharedModuleLoadedMessage
// Description: Is called when a module is loaded into the debugged process address space.
// Arguments: gdbOutputLine - GDB's output line.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 1/1/2009
// Implementation notes:
// Below are example module loaded GDB output:
// =shlibs-added,shlib-info=[num="3",name="Carbon",kind="F",dyld-addr="0x940fd000",reason="dyld",requested-state="Y",state="Y",path="/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon",description="/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon",loaded_addr="0x940fd000",slide="-0x6bf03000",prefix=""]
// =shlibs-added,shlib-info=[num="5",name="libfreeimage-3.9.3.dylib",kind="-",dyld-addr="0x61e000",reason="dyld",requested-state="Y",state="Y",path="/Users/team/work/driveo/debug/bin/libfreeimage-3.9.3.dylib",description="/Users/team/work/driveo/debug/bin/libfreeimage-3.9.3.dylib",loaded_addr="0x61e000",slide="0x61e000",prefix=""]
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleSharedModuleLoadedMessage(const gtASCIIString& gdbOutputLine)
{
bool retVal = false;
static gtASCIIString s_pathPrefix = "path=\"";
static int s_pathPrefixLength = s_pathPrefix.length();
static gtASCIIString s_loadedAddressPrefix = "loaded_addr=\"";
static int s_loadedAddressPrefixLength = s_loadedAddressPrefix.length();
static gtASCIIString s_dataSuffix = "\"";
// Will get the loaded module path and load address:
gtASCIIString loadedModulePath;
osInstructionPointer moduleLoadAddress = 0;
// Get the position in which the "path=" appears:
int pos1 = gdbOutputLine.find(s_pathPrefix);
GT_IF_WITH_ASSERT(pos1 != -1)
{
// Look for the " that ends the path:
int pos2 = pos1 + s_pathPrefixLength;
int pos3 = gdbOutputLine.find(s_dataSuffix, pos2);
GT_IF_WITH_ASSERT(pos3 != -1)
{
// Get the loaded module path:
gdbOutputLine.getSubString(pos2, pos3 - 1, loadedModulePath);
}
}
// Get the position in which the "loaded_addr=" appears:
int pos4 = gdbOutputLine.find(s_loadedAddressPrefix);
GT_IF_WITH_ASSERT(pos4 != -1)
{
// Look for the " that ends the loaded address:
int pos5 = pos4 + s_loadedAddressPrefixLength;
int pos6 = gdbOutputLine.find(s_dataSuffix, pos5);
if ((pos6 != -1) && (pos5 < pos6))
{
// Get the module loaded address as string:
gtASCIIString moduleLoadedAddressAsStr;
gdbOutputLine.getSubString(pos5, pos6 - 1, moduleLoadedAddressAsStr);
// Translate it to a void*:
unsigned long long moduleLoadedAddressAsULongLong = 0;
bool rc1 = moduleLoadedAddressAsStr.toUnsignedLongLongNumber(moduleLoadedAddressAsULongLong);
GT_IF_WITH_ASSERT(rc1)
{
moduleLoadAddress = (osInstructionPointer)moduleLoadedAddressAsULongLong;
}
}
}
// Trigger a "module loaded" event:
gtString modulePathAsUnicodeString;
modulePathAsUnicodeString.fromASCIIString(loadedModulePath.asCharArray());
apModuleLoadedEvent* pModuleLoadedEvent = new apModuleLoadedEvent(0, modulePathAsUnicodeString, moduleLoadAddress);
m_eventsToRegister.push_back(pModuleLoadedEvent);
// Check success status:
if (!loadedModulePath.isEmpty())
{
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::handleSharedModuleUnloadedMessage
// Description: Is called when a module is unloaded from the debugged process address space.
// Arguments: gdbOutputLine - GDB's output line.
// Return Val: bool - Success / failure.
// Author: <NAME>
// Date: 1/1/2009
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::handleSharedModuleUnloadedMessage(const gtASCIIString& gdbOutputLine)
{
bool retVal = false;
static gtASCIIString s_pathPrefix = "path=\"";
static int s_pathPrefixLength = s_pathPrefix.length();
static gtASCIIString s_dataSuffix = "\"";
// Will get the unloaded module path and load address:
gtASCIIString unloadedModulePath;
// Get the position in which the "path=" appears:
int pos1 = gdbOutputLine.find(s_pathPrefix);
GT_IF_WITH_ASSERT(pos1 != -1)
{
// Look for the " that ends the path:
int pos2 = pos1 + s_pathPrefixLength;
int pos3 = gdbOutputLine.find(s_dataSuffix, pos2);
GT_IF_WITH_ASSERT(pos3 != -1)
{
// Get the unloaded module path:
gdbOutputLine.getSubString(pos2, pos3, unloadedModulePath);
}
}
// Trigger a "module unloaded" event:
gtString modulePathAsUnicodeString;
modulePathAsUnicodeString.fromASCIIString(unloadedModulePath.asCharArray());
apModuleUnloadedEvent* pModuleUnloadedEvent = new apModuleUnloadedEvent(0, modulePathAsUnicodeString);
m_eventsToRegister.push_back(pModuleUnloadedEvent);
// Check success status:
if (!unloadedModulePath.isEmpty())
{
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::outputParsingGDBOutputLogMessage
// Description: If under debug log severity, output a "parsing GDB output..."
// debug log message.
// Arguments: executedGDBCommandId - The executed GDB command id.
// gdbOutputString - GDB's output string.
// Author: <NAME>
// Date: 17/4/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::outputParsingGDBOutputLogMessage(pdGDBCommandId executedGDBCommandId, const gtASCIIString& gdbOutputString)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
// Will contain the debug message:
gtString debugMsg;
// Get the executed command information:
const pdGDBCommandInfo* pCommandInfo = pdGetGDBCommandInfo(executedGDBCommandId);
GT_IF_WITH_ASSERT(pCommandInfo)
{
// Add GDB's command string to the debug message:
debugMsg.fromASCIIString(pCommandInfo->_commandExecutionString);
}
debugMsg.prepend(PD_STR_executedGDBCommand);
// Add the parsed test to the debug message:
debugMsg += PD_STR_parsingGDBOutput;
gtString gdbOutputAsUnicodeString;
gdbOutputAsUnicodeString.fromASCIIString(gdbOutputString.asCharArray());
debugMsg += gdbOutputAsUnicodeString;
// Output the debug message:
OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::outputEndedParsingGDBOutputLogMessage
// Description: If under debug log severity, output a "Finished parsing GDB output..."
// debug log message.
// Arguments: gdbOutputString - GDB's output string.
// Author: <NAME>
// Date: 18/12/2008
// ---------------------------------------------------------------------------
void pdGDBOutputReader::outputEndedParsingGDBOutputLogMessage(const gtASCIIString& gdbOutputString)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
// Add the parsed test to the debug message:
gtString debugMsg;
debugMsg.fromASCIIString(gdbOutputString.asCharArray());
debugMsg.prepend(PD_STR_endedParsingGDBOutput);
// Output the debug message:
OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::outputGeneralLineLogMessage
// Description: If under debug log severity, output a "parsing general GDB output line ..."
// debug log message.
// Arguments: gdbOutputLine - The parsed output line.
// Author: <NAME>
// Date: 17/4/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::outputGeneralLineLogMessage(const gtASCIIString& gdbOutputLine)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
gtString debugMsg;
debugMsg.fromASCIIString(gdbOutputLine.asCharArray());
debugMsg.prepend(PD_STR_parsingGDBOutputLine);
OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::outputThreadLineLogMessage
// Description: If under debug log severity, output a "Parsing thread line ..."
// debug log message.
// Arguments: gdbOutputString - The read GDB output output line.
// Author: <NAME>
// Date: 17/4/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::outputThreadLineLogMessage(const gtASCIIString& gdbOutputLine)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
gtString debugMsg;
debugMsg.fromASCIIString(gdbOutputLine.asCharArray());
debugMsg.prepend(PD_STR_parsingThreadLine);
OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::outputCallStackLogMessage
// Description: If under debug log severity, output a "Parsing call stack ..."
// debug log message.
// Arguments: gdbOutputString - The read GDB output output line.
// Author: <NAME>
// Date: 17/4/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::outputCallStackLogMessage(const gtASCIIString& gdbOutputString)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
gtString debugMsg;
debugMsg.fromASCIIString(gdbOutputString.asCharArray());
debugMsg.prepend(PD_STR_parsingCallStack);
OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::outputCallStackLineLogMessage
// Description: If under debug log severity, output a "Parsing call stack line ..."
// debug log message.
// Arguments: gdbOutputString - The read GDB output output line.
// Author: <NAME>
// Date: 17/4/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::outputCallStackLineLogMessage(const gtASCIIString& gdbOutputString)
{
// If under debug log severity:
if (OS_DEBUG_LOG_DEBUG <= osDebugLog::instance().loggedSeverity())
{
gtString debugMsg;
debugMsg.fromASCIIString(gdbOutputString.asCharArray());
debugMsg.prepend(PD_STR_parsingCallStackLine);
OS_OUTPUT_DEBUG_LOG(debugMsg.asCharArray(), OS_DEBUG_LOG_DEBUG);
}
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::isExecutingSynchronousCommand
// Description:
// Returns true iff we are reading the output of a GDB synchronous command.
// Author: <NAME>
// Date: 29/8/2007
// ---------------------------------------------------------------------------
bool pdGDBOutputReader::isExecutingSynchronousCommand() const
{
bool retVal = false;
// Get the executed command information:
const pdGDBCommandInfo* pCommandInfo = pdGetGDBCommandInfo(_executedGDBCommandId);
GT_IF_WITH_ASSERT(pCommandInfo)
{
if (pCommandInfo->_commandType == PD_GDB_SYNCHRONOUS_CMD)
{
retVal = true;
}
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::initMembers
// Description: Initialize this class internal members.
// Author: <NAME>
// Date: 8/7/2007
// ---------------------------------------------------------------------------
void pdGDBOutputReader::initMembers()
{
_executedGDBCommandId = PD_GDB_NULL_CMD;
_executedGDBCommandRequiresFlush = false;
_pGDBCommunicationPipe = NULL;
_gdbErrorString.makeEmpty();
_wasDebuggedProcessSuspended = false;
m_didDebuggedProcessReceiveFatalSignal = false;
_wasDebuggedProcessTerminated = false;
//_wasGDBPrompt = false;
_debuggedProcessCurrentThreadGDBId = -1;
_debuggedProcessCurrentThreadId = OS_NO_THREAD_ID;
m_eventsToRegister.deleteElementsAndClear();
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::threadIdFromGDBId
// Description: Translates a thread's GDB index to an OS thread ID
// Author: <NAME>
// Date: 29/3/2016
// ---------------------------------------------------------------------------
osThreadId pdGDBOutputReader::threadIdFromGDBId(int threadGDBId)
{
osThreadId retVal = OS_NO_THREAD_ID;
if (0 < threadGDBId)
{
// Get the debugged process threads data:
static const gtASCIIString emptyStr;
const pdGDBData* pGDBOutputData = NULL;
// On Mac, starting with Xcode 3.2.3, the "info threads" command does not give us all the data we need, so we use the machine interface "-thread-list-ids" instead.
// On Linux, the machine interface function is not implementer on all platforms, so we cannot use it as we might not get the data.
#if AMDT_LINUX_VARIANT == AMDT_GENERIC_LINUX_VARIANT
bool rc1 = _pGDBDriver->executeGDBCommand(PD_GET_THREADS_INFO_CMD, emptyStr, &pGDBOutputData);
#elif AMDT_LINUX_VARIANT == AMDT_MAC_OS_X_LINUX_VARIANT
bool rc1 = _pGDBDriver->executeGDBCommand(PD_GET_THREADS_INFO_VIA_MI_CMD, emptyStr, &pGDBOutputData);
#else
#error Unknown Linux Variant!
#endif
GT_IF_WITH_ASSERT(rc1 && (pGDBOutputData != NULL))
{
// Sanity check:
GT_IF_WITH_ASSERT(pGDBOutputData->type() == pdGDBData::PD_GDB_THREAD_DATA_LIST)
{
// Store the threads data;
pdGDBThreadDataList* pDebuggedProcessThreadsData = (pdGDBThreadDataList*)pGDBOutputData;
const gtList<pdGDBThreadData>& debuggedProcessThreadsDataList = pDebuggedProcessThreadsData->_threadsDataList;
for (const auto& t : debuggedProcessThreadsDataList)
{
if (t._gdbThreadId == threadGDBId)
{
retVal = t._OSThreadId;
break;
}
}
}
}
// Clean up the threads data:
delete pGDBOutputData;
return retVal;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: pdGDBOutputReader::initialize
// Description: Initializes the GDB output reader
// Return Val: void
// Author: <NAME>
// Date: 13/12/2010
// ---------------------------------------------------------------------------
void pdGDBOutputReader::initialize()
{
_amountOfGDBStringPrintouts = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on suspend process command
///
/// \param[in] gdbOutputString a GDB answer
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleSuspendProcess(const gtASCIIString& gdbOutputString)
{
std::vector<std::string> tokens;
std::stringstream ss(gdbOutputString.asCharArray());
std::string item;
while (std::getline(ss, item, '\n'))
{
tokens.push_back(item);
}
for (std::string& it : tokens)
{
if (it.find("signal-name=\"0\"") != std::string::npos)
{
std::string::size_type pos = it.find("stopped-threads");
if (std::string::npos != pos)
{
std::string::size_type pos2 = it.find("\"]", pos + strlen("stopped-threads=[\"") + 1);
if (std::string::npos != pos2)
{
std::string::iterator iterStart = it.begin();
iterStart += pos;
iterStart += strlen("stopped-threads=[\"");
std::string::iterator iterEnd = it.begin();
iterEnd += pos2;
std::string threadNum(iterStart, iterEnd);
int threadGDBId = std::atoi(threadNum.c_str());
if (_pGDBDriver)
{
_pGDBDriver->OnThreadGDBStopped(threadGDBId);
_wasDebuggedProcessSuspended = _pGDBDriver->IsAllThreadsStopped();
}
}
}
}
}
return true;
};
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on resume process command
///
/// \param[in] gdbOutputString a GDB answer
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleResumeProcess(const gtASCIIString& gdbOutputString)
{
GT_UNREFERENCED_PARAMETER(gdbOutputString);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on switch to thread command
///
/// \param[in] gdbOutputString a GDB answer
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleSwitchToThread(const gtASCIIString& gdbOutputString)
{
GT_UNREFERENCED_PARAMETER(gdbOutputString);
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on switch to frame command
///
/// \param[in] gdbOutputString a GDB answer
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleSwitchToFrame(const gtASCIIString& gdbOutputString)
{
return gdbOutputString.find("^error") == -1;
}
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on get frame locals variables
///
/// \param[in] gdbOutputString a GDB answer
/// \param[out] ppGDBOutputData a pointer to
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleGetLocalsFrame(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool result = false;
gtVector<apExpression> variablesList;
GT_IF_WITH_ASSERT(nullptr != ppGDBOutputData)
{
std::string gdbString = std::string(gdbOutputString.asCharArray());
std::string::size_type pos_start = gdbString.find("[");
std::string::size_type pos_end = gdbString.rfind("]");
if (pos_start != std::string::npos && pos_end != std::string::npos)
{
size_t open_bracket_count = 0;
size_t close_bracket_count = 0;
std::string::size_type open_bracket_count_pos = std::string::npos;
std::string::size_type close_bracket_count_pos = std::string::npos;
for (std::string::size_type it = pos_start; it < pos_end; it++)
{
if ('{' == gdbString[it])
{
open_bracket_count++;
if (open_bracket_count == 1)
{
open_bracket_count_pos = it;
}
}
else
{
if ('}' == gdbString[it])
{
close_bracket_count++;
close_bracket_count_pos = it;
}
}
if (open_bracket_count == close_bracket_count && open_bracket_count != 0)
{
std::string token(std::begin(gdbString) + open_bracket_count_pos, std::begin(gdbString) + close_bracket_count_pos);
std::string::size_type name_begin = token.find("name=\"");
std::string::size_type value_begin = token.find("value=\"");
if (std::string::npos != name_begin && std::string::npos != value_begin)
{
name_begin += strlen("name=\"");
value_begin += strlen("value=\"");
std::string::size_type name_end = token.find("\"", name_begin);
std::string::size_type value_end = token.rfind("\"");
if (std::string::npos != name_end && std::string::npos != value_end)
{
std::string name(std::begin(token) + name_begin, std::begin(token) + name_end);
std::string value(std::begin(token) + value_begin, std::begin(token) + value_end);
gtString gtVariableName = L"";
gtString gtVariableValue = L"";
gtVariableValue.fromASCIIString(value.c_str());
gtVariableName.fromASCIIString(name.c_str());
apExpression valueToken;
valueToken.m_name = gtVariableName;
valueToken.m_value = gtVariableValue;
std::vector<apExpression> childs = parseVariableValueChilds(value);
for (auto child: childs)
{
*valueToken.addChild() = child;
}
variablesList.push_back(valueToken);
}
}
open_bracket_count = 0;
close_bracket_count = 0;
open_bracket_count_pos = std::string::npos;
close_bracket_count_pos = std::string::npos;
}
}
}
*ppGDBOutputData = new pdGDBFrameLocalsData(variablesList);
GT_IF_WITH_ASSERT(nullptr != *ppGDBOutputData)
{
result = true;
}
}
return result;
}
bool pdGDBOutputReader::findValueName(const std::string& str, size_t & start_position)
{
bool ret = false;
if (str.length() <= start_position)
{
return false;
}
auto end_position = str.find(" = ", start_position);
if (std::string::npos != end_position)
{
start_position = end_position;
ret = true;
}
return ret;
}
void pdGDBOutputReader::parseChildValue(const std::string& str, size_t & start_position, apExpression& parent)
{
start_position += strlen(" = ");
if (str.length() <= start_position)
{
return;
}
bool miss_data = false;
size_t brackets_count = 0;
size_t eq_count = 0;
for (size_t i = start_position; i < str.length(); i++)
{
if (str[i] == 'L')
{
if (i + strlen("\\\"") < str.length())
{
if (str[i + 1] == '\\' && str[i + 2] == '\"')
{
miss_data = true;
i += strlen("\\\"");
}
}
}
if (str[i] == '\\')
{
if (i + 1 < str.length())
{
if (str[i + 1] == '\"')
{
if (miss_data)
{
if (i + 2 < str.length())
{
if (str[i + 2] == ',')
{
if (i + 1 + strlen(", 'x' <repeats") < str.length())
{
if (!(str[i + 2] == ',' && str[i + 4] == '\'' && str[i + 6] == '\'' && str[i + 8] == '<'))
{
miss_data = false;
}
else
{
i = str.find("\\\"", i) + 1;
}
}
}
else
{
if (i + 5 < str.length())
{
if (str[i + 2] == '.' && str[i + 3] == '.' && str[i + 4] == '.' && str[i + 5] == ',')
{
miss_data = false;
}
}
}
}
}
else
{
miss_data = true;
}
}
}
}
if (str[i] == '{' && !miss_data)
{
brackets_count++;
}
if (str[i] == '}' && !miss_data)
{
brackets_count--;
}
if (str[i] == '<' && !miss_data)
{
eq_count++;
}
if (str[i] == '>' && !miss_data)
{
eq_count--;
}
if ((str[i] == ',' && !miss_data && 0 == brackets_count && 0 == eq_count) || i == str.length() - 1)
{
std::string value(std::begin(str) + start_position, std::begin(str) + i);
std::vector<apExpression> childs = parseVariableValueChilds(value);
parent.m_value.fromASCIIString(value.c_str());
for (auto child: childs)
{
*parent.addChild() = child;
}
start_position = i;
break;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Parse nested gdb values
///
/// \param[in] current value string
///
/// \return vector of found childs
std::vector<apExpression> pdGDBOutputReader::parseVariableValueChilds(const std::string& value_str)
{
std::vector<apExpression> result;
if (value_str.size())
{
size_t current_position = 0;
if (value_str[0] == '{')
{
current_position++;
size_t end_value_name_position = current_position;
while(findValueName(value_str, end_value_name_position))
{
apExpression currentValue;
std::string name(std::begin(value_str) + current_position, std::begin(value_str) + end_value_name_position);
currentValue.m_name.fromASCIIString(name.c_str());
parseChildValue(value_str, end_value_name_position, currentValue);
current_position = end_value_name_position + 1;
result.push_back(currentValue);
}
}
}
return result;
}
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on get variable value
///
/// \param[in] gdbOutputString a GDB answer
/// \param[out] ppGDBOutputData a pointer to
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleGetVariable(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool result = false;
GT_UNREFERENCED_PARAMETER(gdbOutputString);
GT_UNREFERENCED_PARAMETER(ppGDBOutputData);
apExpression localValue;
GT_IF_WITH_ASSERT(nullptr != ppGDBOutputData)
{
std::string gdbString = std::string(gdbOutputString.asCharArray());
std::string::size_type pos_start = gdbString.find("^done,value=\"");
if (0 == pos_start)
{
std::string::size_type pos_end = gdbString.rfind("\"");
if (std::string::npos != pos_end)
{
std::string value(std::begin(gdbString) + strlen("^done,value=\""), std::begin(gdbString) + pos_end);
localValue.m_value.fromASCIIString(value.c_str());
std::vector<apExpression> childs = parseVariableValueChilds(value);
for (auto child: childs)
{
*localValue.addChild() = child;
}
}
}
*ppGDBOutputData = new pdGDBFrameLocalVariableValue(localValue);
GT_IF_WITH_ASSERT(nullptr != *ppGDBOutputData)
{
result = true;
}
}
return result;
};
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on set breakpoint
///
/// \param[in] gdbOutputString a GDB answer
/// \param[out] ppGDBOutputData a pointer to
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleSetBreakpointOutput(const gtASCIIString& gdbOutputString, const pdGDBData** ppGDBOutputData)
{
bool result = gdbOutputString.find("^error") < 0;
if (result)
{
const gtASCIIString bpNumberStart = "bkpt={number=\"";
int pos1 = gdbOutputString.find(bpNumberStart);
GT_IF_WITH_ASSERT(pos1 != -1)
{
int pos2 = pos1 + bpNumberStart.length();
int pos3 = gdbOutputString.find('\"', pos2);
GT_IF_WITH_ASSERT(pos3 != -1)
{
gtASCIIString numberString = "";
gdbOutputString.getSubString(pos2, (pos3 - 1), numberString);
int index = -1;
GT_IF_WITH_ASSERT(numberString.toIntNumber(index))
{
*ppGDBOutputData = new pdGDBBreakpointIndex(index);
result = true;
}
}
}
}
return result;
};
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on "step in" command
///
/// \param[in] gdbOutputString a GDB answer
/// \param[out] ppGDBOutputData a pointer to
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleStepIn(const gtASCIIString& gdbOutputString)
{
return gdbOutputString.find("^error") < 0;
};
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on "step over" command
///
/// \param[in] gdbOutputString a GDB answer
/// \param[out] ppGDBOutputData a pointer to
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleStepOver(const gtASCIIString& gdbOutputString)
{
return gdbOutputString.find("^error") < 0;
};
/////////////////////////////////////////////////////////////////////////////////////////
/// \brief Process GDB's output on "step out" command
///
/// \param[in] gdbOutputString a GDB answer
///
/// \return true - command success/false - GDB return error
bool pdGDBOutputReader::handleStepOut(const gtASCIIString& gdbOutputString)
{
return gdbOutputString.find("^error") < 0;
};
//////////////////////////////////////////////////////////////////////////////////////
/// \brief Flush GDB prompt
///
/// \return true - success, false - fail
/// \author <NAME>
/// \date 10/02/2016
bool pdGDBOutputReader::flushGDBPrompt()
{
bool result = false;
gtASCIIString gdbOutput;
if (!_wasGDBPrompt)
{
readSynchronousCommandGDBOutput(gdbOutput);
result = (gdbOutput.find("(gdb)") != -1);
}
else
{
result = true;
}
return result;
}
| 117,370 |
472 | <reponame>WithToken/TTPatch
//
// TaoBaoHome.h
// Example
//
// Created by tianyubing on 2020/3/27.
// Copyright © 2020 TianyuBing. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface TaoBaoHome : UIViewController
@end
NS_ASSUME_NONNULL_END
| 118 |
530 | import pytest
from tests.functional.coercers.common import resolve_list_field
@pytest.mark.asyncio
@pytest.mark.ttftt_engine(
name="coercion", resolvers={"Query.listFloatField": resolve_list_field}
)
@pytest.mark.parametrize(
"query,variables,expected",
[
(
"""query { listFloatField }""",
None,
{"data": {"listFloatField": "SUCCESS"}},
),
(
"""query { listFloatField(param: null) }""",
None,
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query { listFloatField(param: [null]) }""",
None,
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query { listFloatField(param: 23456.789e2) }""",
None,
{"data": {"listFloatField": "SUCCESS-[2345681.9]"}},
),
(
"""query { listFloatField(param: [23456.789e2]) }""",
None,
{"data": {"listFloatField": "SUCCESS-[2345681.9]"}},
),
(
"""query { listFloatField(param: [23456.789e2, null]) }""",
None,
{"data": {"listFloatField": "SUCCESS-[2345681.9-None]"}},
),
(
"""query ($param: [Float]) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS"}},
),
(
"""query ($param: [Float]) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float]) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float]) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float]) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float]) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float] = null) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = null) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = null) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = null) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = null) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = null) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float] = [null]) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [null]) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [null]) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [null]) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = [null]) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = [null]) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float] = 456.789e2) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS-[45681.9]"}},
),
(
"""query ($param: [Float] = 456.789e2) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = 456.789e2) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = 456.789e2) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = 456.789e2) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = 456.789e2) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float] = [456.789e2]) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS-[45681.9]"}},
),
(
"""query ($param: [Float] = [456.789e2]) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [456.789e2]) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [456.789e2]) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = [456.789e2]) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = [456.789e2]) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float] = [456.789e2, null]) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS-[45681.9-None]"}},
),
(
"""query ($param: [Float] = [456.789e2, null]) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [456.789e2, null]) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float] = [456.789e2, null]) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = [456.789e2, null]) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float] = [456.789e2, null]) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float]!) { listFloatField(param: $param) }""",
None,
{
"data": None,
"errors": [
{
"message": "Variable < $param > of required type < [Float]! > was not provided.",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float]!) { listFloatField(param: $param) }""",
{"param": None},
{
"data": None,
"errors": [
{
"message": "Variable < $param > of non-null type < [Float]! > must not be null.",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float]!) { listFloatField(param: $param) }""",
{"param": [None]},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float]!) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float]!) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float]!) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{"data": {"listFloatField": "SUCCESS-[345681.9-None]"}},
),
(
"""query ($param: [Float!]) { listFloatField(param: $param) }""",
None,
{"data": {"listFloatField": "SUCCESS"}},
),
(
"""query ($param: [Float!]) { listFloatField(param: $param) }""",
{"param": None},
{"data": {"listFloatField": "SUCCESS-[None]"}},
),
(
"""query ($param: [Float!]) { listFloatField(param: $param) }""",
{"param": [None]},
{
"data": None,
"errors": [
{
"message": "Variable < $param > got invalid value < [None] >; Expected non-nullable type < Float! > not to be null at value[0].",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float!]) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float!]) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float!]) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{
"data": None,
"errors": [
{
"message": "Variable < $param > got invalid value < [345678.9, None] >; Expected non-nullable type < Float! > not to be null at value[1].",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float!]!) { listFloatField(param: $param) }""",
None,
{
"data": None,
"errors": [
{
"message": "Variable < $param > of required type < [Float!]! > was not provided.",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float!]!) { listFloatField(param: $param) }""",
{"param": None},
{
"data": None,
"errors": [
{
"message": "Variable < $param > of non-null type < [Float!]! > must not be null.",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float!]!) { listFloatField(param: $param) }""",
{"param": [None]},
{
"data": None,
"errors": [
{
"message": "Variable < $param > got invalid value < [None] >; Expected non-nullable type < Float! > not to be null at value[0].",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($param: [Float!]!) { listFloatField(param: $param) }""",
{"param": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float!]!) { listFloatField(param: $param) }""",
{"param": [3456.789e2]},
{"data": {"listFloatField": "SUCCESS-[345681.9]"}},
),
(
"""query ($param: [Float!]!) { listFloatField(param: $param) }""",
{"param": [3456.789e2, None]},
{
"data": None,
"errors": [
{
"message": "Variable < $param > got invalid value < [345678.9, None] >; Expected non-nullable type < Float! > not to be null at value[1].",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($item: Float) { listFloatField(param: [23456.789e2, $item]) }""",
None,
{"data": {"listFloatField": "SUCCESS-[2345681.9-None]"}},
),
(
"""query ($item: Float) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": None},
{"data": {"listFloatField": "SUCCESS-[2345681.9-None]"}},
),
(
"""query ($item: Float) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[2345681.9-345681.9]"}},
),
(
"""query ($item: Float = null) { listFloatField(param: [23456.789e2, $item]) }""",
None,
{"data": {"listFloatField": "SUCCESS-[2345681.9-None]"}},
),
(
"""query ($item: Float = null) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": None},
{"data": {"listFloatField": "SUCCESS-[2345681.9-None]"}},
),
(
"""query ($item: Float = null) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[2345681.9-345681.9]"}},
),
(
"""query ($item: Float = 456.789e2) { listFloatField(param: [23456.789e2, $item]) }""",
None,
{"data": {"listFloatField": "SUCCESS-[2345681.9-45681.9]"}},
),
(
"""query ($item: Float = 456.789e2) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": None},
{"data": {"listFloatField": "SUCCESS-[2345681.9-None]"}},
),
(
"""query ($item: Float = 456.789e2) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[2345681.9-345681.9]"}},
),
(
"""query ($item: Float!) { listFloatField(param: [23456.789e2, $item]) }""",
None,
{
"data": None,
"errors": [
{
"message": "Variable < $item > of required type < Float! > was not provided.",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($item: Float!) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": None},
{
"data": None,
"errors": [
{
"message": "Variable < $item > of non-null type < Float! > must not be null.",
"path": None,
"locations": [{"line": 1, "column": 8}],
}
],
},
),
(
"""query ($item: Float!) { listFloatField(param: [23456.789e2, $item]) }""",
{"item": 3456.789e2},
{"data": {"listFloatField": "SUCCESS-[2345681.9-345681.9]"}},
),
],
)
async def test_coercion_list_float_field(engine, query, variables, expected):
assert await engine.execute(query, variables=variables) == expected
| 9,991 |
2,134 | <filename>logic/export.hpp
// generates export.hpp for each module from compat/linkage.hpp
#pragma once
#include "compat/linkage-macros.hpp"
#ifdef BUILD_LOGIC
# define OTR_LOGIC_EXPORT OTR_GENERIC_EXPORT
#else
# define OTR_LOGIC_EXPORT OTR_GENERIC_IMPORT
#endif
| 113 |
567 |
{
"id": "2021_Vitis-Tutorials-AI_Engine_Development",
"name": "2021_Vitis In Depth Tutorials",
"description": "2021_AI_Engine_Development"
}
| 66 |
346 | <filename>Language Skills/Python/Unit 07 Lists and Functions/01 Lists and Functions/Using Lists of Lists in Functions/17-Using two lists as two arguments in a function.py
m = [1, 2, 3]
n = [4, 5, 6]
n = [3, 5, 7]
# Add your code here!
def join_lists(x, y):
return x + y
print join_lists(m, n)
# You want this to print [1, 2, 3, 4, 5, 6]
| 125 |
322 | <filename>cppsrc/StarQuant/Services/starquant_.cpp
/*****************************************************************************
* Copyright [2019]
*
* 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 <Services/tradingengine.h>
#include <boost/python.hpp>
using namespace boost::python;
using namespace StarQuant;
// http://www.shocksolution.com/python-basics-tutorials-and-examples/linking-python-and-c-with-boostpython/
#ifdef _WIN32
BOOST_PYTHON_MODULE(StarQuant)
#else
BOOST_PYTHON_MODULE(libstarquant)
#endif
{
class_<tradingengine, boost::noncopyable>("tradingengine_").
def("run", &tradingengine::run).
def("live", &tradingengine::live);
}
| 366 |
354 | <filename>trojan/src/main/java/me/ele/trojan/utils/DateUtils.java
package me.ele.trojan.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
/**
* Created by michaelzhong on 2017/11/7.
*/
public class DateUtils {
private static final SimpleDateFormat dfYMD = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
public static String getDate() {
return dfYMD.format(Calendar.getInstance().getTime());
}
}
| 170 |
538 | import sys
sys.path.insert(0,'..')
from data.whale_data import find_exchange_txs
from plot.plotly_helper import plot_using_plotly
from .calculate_holding_amount import calculate_holding_amount
from .calculate_historical import *
from .coinmarketcap_draw import coinmarketcap_data
from data.whale_data import find_whale_account_token_tx,find_interstering_accounts
from .holder_tracking import track_holder_number_over_time
in_type = "IN"
out_type = "OUT"
# 保存最早的交易时间
from datetime import datetime
from datetime import timedelta
the_earliest_tx_time = datetime.now()
def update_y_array(X,y,timestamp,amount):
target_index = 0
for i in range(len(X)):
x_time = X[i]
if timestamp < x_time:
target_index = i
break
for i in range(target_index,len(y)):
y[i] += amount
return y
def update_y_daily_array(X,y,timestamp,amount):
target_index = 0
for i in range(len(X)):
x_time = X[i]
if timestamp < x_time:
target_index = i
break
y[target_index] += amount
return y
def main_business_logic(symbol,escape_accounts,coinmarketcap_symbol):
txs = find_exchange_txs()
# 找到最早的交易时间
global the_earliest_tx_time
for acc in txs:
print(acc)
acc_txs = txs[acc]
for sub_tx in acc_txs:
tx_date = sub_tx[0]
if tx_date < the_earliest_tx_time: the_earliest_tx_time = tx_date
# build X time array
the_earliest_tx_time = the_earliest_tx_time.replace(minute=0, second=0)
current_time = datetime.now().replace(minute=0, second=0)
tmp_time = the_earliest_tx_time
X = []
while tmp_time < current_time:
X.append(tmp_time)
tmp_time += timedelta(hours=1)
print(len(X))
# build all traxe Y: deposit_amount, withdraw_amount
deposit_trace_y = [0] * len(X)
withdraw_trace_y = [0] * len(X)
exchange_remain_amount_y = [0] * len(X)
# Daily Stat
deposit_daily_trace_y = [0] * len(X)
withdraw_daily_trace_y = [0] * len(X)
exchange_daily_remain_amount_y = [0] * len(X)
for holder in txs:
holder_txs = txs[holder]
for tx in holder_txs:
[timestamp,from_a,tx_type,to_a,amount] = tx
if tx_type == in_type:
deposit_trace_y = update_y_array(X,deposit_trace_y,timestamp,amount)
deposit_daily_trace_y = update_y_daily_array(X,deposit_daily_trace_y,timestamp,amount)
else:
withdraw_trace_y = update_y_array(X,withdraw_trace_y,timestamp,amount)
withdraw_daily_trace_y = update_y_daily_array(X,withdraw_daily_trace_y,timestamp,amount)
for i in range(0,len(X)):
exchange_remain_amount_y[i] = deposit_trace_y[i] - withdraw_trace_y[i]
exchange_daily_remain_amount_y[i] = deposit_daily_trace_y[i] - withdraw_daily_trace_y[i]
# Draw the kline data from coinmarketcap
df,df_date = coinmarketcap_data(coinmarketcap_symbol)
price_trace = {'x':df_date,'y':df['price_usd'].values.tolist(),'name':"Price(USD)","yaxis":'y2'}
volume_trace = {'x':df_date,'y':df['volume_token'].values.tolist(),'name':"Trading Volume(Token)"}
deposit_trace = {"x":X,"y":deposit_trace_y,"name":"Exchange Deposit Amount(Token)"}
withdraw_trace = {"x":X,"y":withdraw_trace_y,"name":"Exchange Withdraw Amount(Token)"}
exchange_remain_amount_trace = {"x":X,"y":exchange_remain_amount_y,"name":"Exchange Remain Amount(Token)"}
whale_txs = find_whale_account_token_tx(escape_accounts,1,1)
# current_top_50_holding_amount_y = calculate_holding_amount(X,escape_accounts,whale_txs)
# holding_amount_trace = {"x":X,"y":current_top_50_holding_amount_y,"name":"Top 50 {} Holder Holding Amount(Token)".format(symbol)}
first_plot = plot_using_plotly("Total {} Exchange Analysis (Bittrex, Bitfinex, Binance, Poloniex,liqui.io, Etherdelta, huobi.pro, CEX.com)".format(symbol),
[deposit_trace,withdraw_trace,exchange_remain_amount_trace,price_trace,volume_trace],
'{} Total'.format(symbol))
all_whale_txs = find_whale_account_token_tx(escape_accounts,2,2)
for acc in whale_txs:
if acc not in all_whale_txs:
all_whale_txs[acc] = whale_txs[acc]
acc_holding_values_dict = calculate_historical_holders(all_whale_txs,X)
top_50_holding_values = find_top_50_over_time_helper(acc_holding_values_dict)
top_50_list_and_token_amount_change_trace = calculate_top_50_list_and_token_amount_change(top_50_holding_values,escape_accounts)
top_50_list_and_token_amount_change_trace.append(price_trace)
plot_top_50_token_amount = plot_using_plotly("Top 50 List and their token amount (without counting the exchange)",top_50_list_and_token_amount_change_trace,'{} top 50'.format(symbol))
top_50_token_moving_average = calculate_top_50_token_moving_average(top_50_holding_values)
top_50_token_moving_average_trace = {"x":X,"y":top_50_token_moving_average,"name":"Top 50 Token MA"}
top_50_token_ma_trace = plot_using_plotly("Top 50 Token amount Moving Average (without counting the exchange)",[top_50_token_moving_average_trace,price_trace],'{} Top 50 MA'.format(symbol))
exchange_holding_values_dict = calculate_historical_holders(txs,X)
exchange_holding_values = find_top_50_over_time_helper(exchange_holding_values_dict)
exchange_token_moving_average_trace = calculate_top_50_token_moving_average(exchange_holding_values)
exchange_list_and_token_amount_change_trace = calculate_top_50_list_and_token_amount_change(exchange_holding_values,escape_accounts,is_exchange=True)
exchange_list_and_token_amount_change_trace.append(price_trace)
exchange_plot = plot_using_plotly("Exchange token amount",exchange_list_and_token_amount_change_trace,'{} exchange token amount'.format(symbol))
deposit_trace = {"x":X,"y":deposit_daily_trace_y,"name":"Exchange Deposit Amount(Token)"}
withdraw_trace = {"x":X,"y":withdraw_daily_trace_y,"name":"Exchange Withdraw Amount(Token)"}
exchange_daily_remain_amount_trace = {"x":X,"y":exchange_daily_remain_amount_y,"name":"Exchange Daily Remain Amount(Token)"}
second_plot = plot_using_plotly("Hourly {} Exchange Analysis (Bittrex, Bitfinex, Binance, Poloniex,liqui.io, Etherdelta, huobi.pro, CEX.com)".format(symbol),[deposit_trace,exchange_daily_remain_amount_trace,price_trace],'{} hourly'.format(symbol))
_,total_number_of_pages = find_interstering_accounts()
remaining_whale_data = find_whale_account_token_tx(escape_accounts,3,total_number_of_pages)
for acc in remaining_whale_data:
if acc not in all_whale_txs:
all_whale_txs[acc] = remaining_whale_data[acc]
acc_holding_values_dict = calculate_historical_holders(all_whale_txs,X)
track_holder_number_over_time_y = track_holder_number_over_time(acc_holding_values_dict)
track_holder_number_over_time_trace = {"x":X,"y":track_holder_number_over_time_y,"name":"Token Holder"}
plot_track_holder_number_over_time = plot_using_plotly("{} Token Holder Trace Overtime".format(symbol),[track_holder_number_over_time_trace,price_trace],'{} Holder'.format(symbol))
return ({"total_analysis":first_plot,"hourly analysis":second_plot,"plot_top_50_token_amount":plot_top_50_token_amount,"exchange_plot":exchange_plot,"top_50_token_ma_trace":top_50_token_ma_trace, "plot_track_holder_number_over_time":plot_track_holder_number_over_time})
| 3,089 |
3,102 | <filename>clang/test/Driver/nostdlibxx.cpp
// RUN: %clangxx -target i686-pc-linux-gnu -### -nostdlib++ %s 2> %t
// RUN: FileCheck < %t %s
// We should still have -lm and the C standard libraries, but not -lstdc++.
// CHECK-NOT: -lstdc++
// CHECK-NOT: -lc++
// CHECK: -lm
// Make sure -lstdc++ isn't rewritten to the default stdlib when -nostdlib++ is
// used.
//
// RUN: %clangxx -target i686-pc-linux-gnu -### \
// RUN: -nostdlib++ -stdlib=libc++ -lstdc++ %s 2> %t
// RUN: FileCheck --check-prefix=CHECK-RESERVED-LIB-REWRITE < %t %s
// CHECK-RESERVED-LIB-REWRITE: -lstdc++
// CHECK-RESERVED-LIB-REWRITE-NOT: -lc++
| 271 |
348 | {"nom":"Goualade","circ":"9ème circonscription","dpt":"Gironde","inscrits":77,"abs":20,"votants":57,"blancs":9,"nuls":3,"exp":45,"res":[{"nuance":"SOC","nom":"<NAME>","voix":25},{"nuance":"MDM","nom":"<NAME>","voix":20}]} | 92 |
868 | <reponame>codrinbucur/activemq-artemis
/*
* 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.activemq.artemis.tests.unit.core.remoting.server.impl.fake;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.activemq.artemis.api.core.BaseInterceptor;
import org.apache.activemq.artemis.core.security.ActiveMQPrincipal;
import org.apache.activemq.artemis.core.server.cluster.ClusterConnection;
import org.apache.activemq.artemis.core.server.management.NotificationService;
import org.apache.activemq.artemis.spi.core.protocol.ProtocolManager;
import org.apache.activemq.artemis.spi.core.remoting.Acceptor;
import org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory;
import org.apache.activemq.artemis.spi.core.remoting.BufferHandler;
import org.apache.activemq.artemis.spi.core.remoting.ServerConnectionLifeCycleListener;
public class FakeAcceptorFactory implements AcceptorFactory {
private boolean started = false;
@Override
public Acceptor createAcceptor(String name,
ClusterConnection clusterConnection,
Map<String, Object> configuration,
BufferHandler handler,
ServerConnectionLifeCycleListener listener,
Executor threadPool,
ScheduledExecutorService scheduledThreadPool,
Map<String, ProtocolManager> protocolMap) {
return new FakeAcceptor();
}
private final class FakeAcceptor implements Acceptor {
@Override
public String getName() {
return "fake";
}
@Override
public void pause() {
}
@Override
public void updateInterceptors(List<BaseInterceptor> incomingInterceptors,
List<BaseInterceptor> outgoingInterceptors) {
}
@Override
public ClusterConnection getClusterConnection() {
return null;
}
@Override
public Map<String, Object> getConfiguration() {
return null;
}
@Override
public void setNotificationService(NotificationService notificationService) {
}
@Override
public void setDefaultActiveMQPrincipal(ActiveMQPrincipal defaultActiveMQPrincipal) {
}
@Override
public boolean isUnsecurable() {
return false;
}
@Override
public void reload() {
}
@Override
public void start() throws Exception {
started = true;
}
@Override
public void stop() throws Exception {
started = false;
}
@Override
public boolean isStarted() {
return started;
}
}
}
| 1,366 |
453 | <gh_stars>100-1000
/* $NetBSD: hcreate.c,v 1.2 2001/02/19 21:26:04 ross Exp $ */
/*
* Copyright (c) 2001 <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* <<Id: LICENSE_GC,v 1.1 2001/10/01 23:24:05 cgd Exp>>
*/
/*
* hcreate() / hsearch() / hdestroy()
*
* SysV/XPG4 hash table functions.
*
* Implementation done based on NetBSD manual page and Solaris manual page,
* plus my own personal experience about how they're supposed to work.
*
* I tried to look at Knuth (as cited by the Solaris manual page), but
* nobody had a copy in the office, so...
*/
#include <sys/cdefs.h>
#if 0
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: hcreate.c,v 1.2 2001/02/19 21:26:04 ross Exp $");
#endif /* LIBC_SCCS and not lint */
#endif
#include <sys/types.h>
#include <errno.h>
#include <search.h>
#include <stdlib.h>
#include <string.h>
static struct hsearch_data htab;
int
_DEFUN(hcreate, (nel), size_t nel)
{
return hcreate_r (nel, &htab);
}
void
_DEFUN_VOID (hdestroy)
{
hdestroy_r (&htab);
}
ENTRY *
_DEFUN(hsearch, (item, action),
ENTRY item _AND
ACTION action)
{
ENTRY *retval;
hsearch_r (item, action, &retval, &htab);
return retval;
}
| 861 |
953 | <reponame>chen-hwera/rDSN
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include "nfs_client_impl.h"
# include <dsn/tool-api/nfs.h>
# include <queue>
namespace dsn {
namespace service {
void nfs_client_impl::begin_remote_copy(std::shared_ptr<remote_copy_request>& rci, aio_task* nfs_task)
{
user_request* req = new user_request();
req->file_size_req.source = rci->source;
req->file_size_req.dst_dir = rci->dest_dir.c_str();
for (auto& f : rci->files)
{
req->file_size_req.file_list.emplace_back(f.c_str());
}
req->file_size_req.source_dir = rci->source_dir.c_str();
req->file_size_req.overwrite = rci->overwrite;
req->nfs_task = nfs_task;
req->is_finished = false;
get_file_size(
req->file_size_req,
[=](error_code err, get_file_size_response&& resp)
{
end_get_file_size(err, std::move(resp), req);
},
std::chrono::milliseconds(0),
0,
0,
0,
req->file_size_req.source
);
}
void nfs_client_impl::end_get_file_size(
::dsn::error_code err,
const ::dsn::service::get_file_size_response& resp,
void* context)
{
user_request* ureq = (user_request*)context;
if (err != ::dsn::ERR_OK)
{
derror("remote copy request failed");
ureq->nfs_task->enqueue(err, 0);
delete ureq;
return;
}
err = resp.error;
if (err != ::dsn::ERR_OK)
{
derror("remote copy request failed");
ureq->nfs_task->enqueue(err, 0);
delete ureq;
return;
}
for (size_t i = 0; i < resp.size_list.size(); i++) // file list
{
file_context *filec;
uint64_t size = resp.size_list[i];
filec = new file_context(ureq, resp.file_list[i], resp.size_list[i]);
ureq->file_context_map.insert(std::pair<std::string, file_context*>(
utils::filesystem::path_combine(ureq->file_size_req.dst_dir, resp.file_list[i]),
filec
));
//dinfo("this file size is %d, name is %s", size, resp.file_list[i].c_str());
// new all the copy requests
uint64_t req_offset = 0;
uint32_t req_size;
if (size > _opts.nfs_copy_block_bytes)
req_size = _opts.nfs_copy_block_bytes;
else
req_size = static_cast<uint32_t>(size);
int idx = 0;
for (;;) // send one file with multi-round rpc
{
auto req = dsn::ref_ptr<copy_request_ex>(new copy_request_ex(filec, idx++));
filec->copy_requests.push_back(req);
{
zauto_lock l(_copy_requests_lock);
_copy_requests.push(req);
}
req->copy_req.source = ureq->file_size_req.source;
req->copy_req.file_name = resp.file_list[i];
req->copy_req.offset = req_offset;
req->copy_req.size = req_size;
req->copy_req.dst_dir = ureq->file_size_req.dst_dir;
req->copy_req.source_dir = ureq->file_size_req.source_dir;
req->copy_req.overwrite = ureq->file_size_req.overwrite;
req->copy_req.is_last = (size <= req_size);
req_offset += req_size;
size -= req_size;
if (size <= 0)
{
dassert(size == 0, "last request must read exactly the remaing size of the file");
break;
}
if (size > _opts.nfs_copy_block_bytes)
req_size = _opts.nfs_copy_block_bytes;
else
req_size = static_cast<uint32_t>(size);
}
}
continue_copy(0);
}
void nfs_client_impl::continue_copy(int done_count)
{
if (done_count > 0)
{
_concurrent_copy_request_count -= done_count;
}
if (++_concurrent_copy_request_count > _opts.max_concurrent_remote_copy_requests)
{
--_concurrent_copy_request_count;
return;
}
dsn::ref_ptr<copy_request_ex> req = nullptr;
while (true)
{
{
zauto_lock l(_copy_requests_lock);
if (!_copy_requests.empty())
{
req = _copy_requests.front();
_copy_requests.pop();
}
else
{
--_concurrent_copy_request_count;
break;
}
}
{
zauto_lock l(req->lock);
if (req->is_valid)
{
req->add_ref();
req->remote_copy_task = copy(
req->copy_req,
[=](error_code err, copy_response&& resp)
{
end_copy(err, std::move(resp), req.get());
},
std::chrono::milliseconds(0),
0,
0,
0,
req->file_ctx->user_req->file_size_req.source);
if (++_concurrent_copy_request_count > _opts.max_concurrent_remote_copy_requests)
{
--_concurrent_copy_request_count;
break;
}
}
}
}
}
void nfs_client_impl::end_copy(
::dsn::error_code err,
const copy_response& resp,
void* context)
{
//dinfo("*** call RPC_NFS_COPY end, return (%d, %d) with %s", resp.offset, resp.size, err.to_string());
dsn::ref_ptr<copy_request_ex> reqc;
reqc = (copy_request_ex*)context;
reqc->release_ref();
continue_copy(1);
if (err == ERR_OK)
{
err = resp.error;
}
if (err != ::dsn::ERR_OK)
{
handle_completion(reqc->file_ctx->user_req, err);
return;
}
reqc->response = resp;
reqc->response.error.end_tracking(); // always ERR_OK
reqc->is_ready_for_write = true;
auto& fc = reqc->file_ctx;
// check write availability
{
zauto_lock l(fc->user_req->user_req_lock);
if (fc->current_write_index != reqc->index - 1)
return;
}
// check readies for local writes
{
zauto_lock l(fc->user_req->user_req_lock);
for (int i = reqc->index; i < (int)(fc->copy_requests.size()); i++)
{
if (fc->copy_requests[i]->is_ready_for_write)
{
fc->current_write_index++;
{
zauto_lock l(_local_writes_lock);
_local_writes.push(fc->copy_requests[i]);
}
}
else
break;
}
}
continue_write();
}
void nfs_client_impl::continue_write()
{
// check write quota
if (++_concurrent_local_write_count > _opts.max_concurrent_local_writes)
{
--_concurrent_local_write_count;
return;
}
// get write
dsn::ref_ptr<copy_request_ex> reqc;
while (true)
{
{
zauto_lock l(_local_writes_lock);
if (!_local_writes.empty())
{
reqc = _local_writes.front();
_local_writes.pop();
}
else
{
reqc = nullptr;
break;
}
}
{
zauto_lock l(reqc->lock);
if (reqc->is_valid)
break;
}
}
if (nullptr == reqc)
{
--_concurrent_local_write_count;
return;
}
// real write
std::string file_path = dsn::utils::filesystem::path_combine(reqc->copy_req.dst_dir, reqc->file_ctx->file_name);
std::string path = dsn::utils::filesystem::remove_file_name(file_path.c_str());
if (!dsn::utils::filesystem::create_directory(path))
{
dassert(false, "Fail to create directory %s.", path.c_str());
}
dsn_handle_t hfile = reqc->file_ctx->file.load();
if (!hfile)
{
zauto_lock l(reqc->file_ctx->user_req->user_req_lock);
hfile = reqc->file_ctx->file.load();
if (!hfile)
{
hfile = dsn_file_open(file_path.c_str(), O_RDWR | O_CREAT | O_BINARY, 0666);
reqc->file_ctx->file = hfile;
}
}
if (!hfile)
{
derror("file open %s failed", file_path.c_str());
error_code err = ERR_FILE_OPERATION_FAILED;
handle_completion(reqc->file_ctx->user_req, err);
--_concurrent_local_write_count;
continue_write();
return;
}
{
zauto_lock l(reqc->lock);
auto& reqc_save = *reqc.get();
reqc_save.local_write_task = file::write(
hfile,
reqc_save.response.file_content.data(),
reqc_save.response.size,
reqc_save.response.offset,
LPC_NFS_WRITE,
this,
[this, reqc_cap = std::move(reqc)] (error_code err, int sz)
{
local_write_callback(err, sz, std::move(reqc_cap));
}
);
}
}
void nfs_client_impl::local_write_callback(error_code err, size_t sz, dsn::ref_ptr<copy_request_ex> reqc)
{
//dassert(reqc->local_write_task == task::get_current_task(), "");
--_concurrent_local_write_count;
// clear all content to release memory quickly
reqc->response.file_content = blob();
continue_write();
bool completed = false;
if (err != ERR_OK)
{
completed = true;
}
else
{
zauto_lock l(reqc->file_ctx->user_req->user_req_lock);
if (++reqc->file_ctx->finished_segments == (int)reqc->file_ctx->copy_requests.size())
{
if (++reqc->file_ctx->user_req->finished_files == (int)reqc->file_ctx->user_req->file_context_map.size())
{
completed = true;
}
}
}
if (completed)
{
handle_completion(reqc->file_ctx->user_req, err);
}
}
void nfs_client_impl::handle_completion(user_request *req, error_code err)
{
{
zauto_lock l(req->user_req_lock);
if (req->is_finished)
return;
req->is_finished = true;
}
size_t total_size = 0;
for (auto& f : req->file_context_map)
{
total_size += f.second->file_size;
for (auto& rc : f.second->copy_requests)
{
::dsn::task_ptr ctask, wtask;
{
zauto_lock l(rc->lock);
rc->is_valid = false;
ctask = rc->remote_copy_task;
wtask = rc->local_write_task;
rc->remote_copy_task = nullptr;
rc->local_write_task = nullptr;
}
if (err != ERR_OK)
{
if (ctask != nullptr)
{
if (ctask->cancel(true))
{
_concurrent_copy_request_count--;
rc->release_ref();
}
}
if (wtask != nullptr)
{
if (wtask->cancel(true))
{
_concurrent_local_write_count--;
}
}
}
}
if (f.second->file)
{
auto err2 = dsn_file_close(f.second->file);
dassert(err2 == ERR_OK, "dsn_file_close failed, err = %s", dsn_error_to_string(err2));
f.second->file = nullptr;
if (f.second->finished_segments != (int)f.second->copy_requests.size())
{
::remove((f.second->user_req->file_size_req.dst_dir
+ f.second->file_name).c_str());
}
f.second->copy_requests.clear();
}
delete f.second;
}
req->file_context_map.clear();
req->nfs_task->enqueue(err, err == ERR_OK ? total_size : 0);
delete req;
// clear out all canceled requests
if (err != ERR_OK)
{
continue_copy(0);
continue_write();
}
}
}
}
| 9,910 |
567 | package com.twitter;
import com.google.common.collect.ImmutableList;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* This mojo executes the {@code thrift} compiler for generating java sources
* from thrift definitions. It also searches dependency artifacts for
* thrift files and includes them in the thriftPath so that they can be
* referenced. Finally, it adds the thrift files to the project as resources so
* that they are included in the final artifact.
*
* @phase generate-sources
* @goal compile
* @threadSafe true
*/
public final class MavenScroogeCompileMojo extends AbstractMavenScroogeMojo {
/**
* The source directories containing the sources to be compiled.
*
* @parameter default-value="${basedir}/src/main/thrift"
* @required
*/
private File thriftSourceRoot;
/**
* This is the directory into which the {@code .java} will be created.
*
* @parameter default-value="${project.build.directory}/generated-sources/thrift"
* @required
*/
private File outputDirectory;
/**
* This is the directory into which dependent {@code .thrift} files will be extracted.
*
* @parameter default-value="${project.build.directory}/generated-resources/"
* @required
*/
private File resourcesOutputDirectory;
@Override
protected File getOutputDirectory() {
return outputDirectory;
}
@Override
protected File getResourcesOutputDirectory() {
return resourcesOutputDirectory;
}
@Override
protected File getThriftSourceRoot() {
return thriftSourceRoot;
}
@Override
protected void attachFiles(Set<String> compileRoots) {
for (String root : compileRoots) {
project.addCompileSourceRoot(new File(outputDirectory, root).getAbsolutePath());
}
projectHelper.addResource(project, thriftSourceRoot.getAbsolutePath(),
ImmutableList.of("**/*.thrift"), ImmutableList.of());
projectHelper.addResource(project, resourcesOutputDirectory.getAbsolutePath(),
ImmutableList.of("**/*.thrift"), ImmutableList.of());
}
@Override
protected String getDependencyScopeFilter() {
return "compile";
}
@Override
protected List<File> getReferencedThriftFiles() throws IOException {
return getRecursiveThriftFiles(project, "classes");
}
}
| 713 |
2,127 | import time
import uuid
import server.test as base_test
import server.db.diary as db_diary
import server.logic.sync as logic_sync
from server.logic import user as logic_user
DIARY_DB_NAME = 'Diary'
def execute_all_test():
test_create()
test_update()
test_delete()
test_push()
test_pull()
test_sync()
def test_create():
base_test.reinit_table()
_create_mock_user(3)
for user_id in [1, 2, 3]:
title = _get_title()
content = _get_content()
print 'create diary for user_id %s' % user_id
db_diary.create_diary(user_id, _get_uuid(), title, content)
for user_id in [1, 2, 3]:
print 'user_id = %s' % user_id
result = db_diary.get_diary_list_since_last_sync(user_id, 0)
assert len(result) == 1
def test_update():
base_test.reinit_table()
_create_mock_user(1)
user_id = 1
_uuid = _get_uuid()
print 'uuid generated: ', _uuid
db_diary.create_diary(user_id, _uuid, _get_title(), _get_content())
result = db_diary.get_diary_by_uuid(_uuid, user_id)
print result['uuid']
print _uuid
assert result['uuid'] == _uuid
db_diary.update_diary(user_id, _uuid, 'updated title', 'updated content')
result = db_diary.get_diary_by_uuid(_uuid, user_id)
print result
assert result['user_id'] == user_id
assert result['uuid'] == _uuid
assert result['title'] == 'updated title'
assert result['content'] == 'updated content'
def test_delete():
base_test.reinit_table()
_create_mock_user(3)
uuid1 = _get_uuid()
uuid2 = _get_uuid()
uuid3 = _get_uuid()
diary_id_1 = db_diary.create_diary(1, uuid1, _get_title(), _get_content())
diary_id_2 = db_diary.create_diary(2, uuid2, _get_title(), _get_content())
diary_id_3 = db_diary.create_diary(3, uuid3, _get_title(), _get_content())
assert db_diary.get_diary_by_id(diary_id_1) is not None
assert db_diary.get_diary_by_uuid(uuid1, 1) is not None
assert db_diary.get_diary_by_id(diary_id_2) is not None
assert db_diary.get_diary_by_uuid(uuid2, 2) is not None
assert db_diary.get_diary_by_id(diary_id_3) is not None
assert db_diary.get_diary_by_uuid(uuid3, 3) is not None
db_diary.delete_diary(1, uuid1)
assert db_diary.get_diary_by_id(diary_id_1) is None
assert db_diary.get_diary_by_uuid(uuid1, 1) is None
db_diary.delete_diary(2, uuid2)
assert db_diary.get_diary_by_id(diary_id_1) is None
assert db_diary.get_diary_by_uuid(uuid2, 2) is None
db_diary.delete_diary(3, uuid3)
assert db_diary.get_diary_by_id(diary_id_3) is None
assert db_diary.get_diary_by_uuid(uuid3, 3) is None
def test_push():
base_test.reinit_table()
# create mock user
_create_mock_user(1)
# create a diary
data = {
'title': 'first diary',
'content': 'first diary',
'time': 11111111,
}
_uuid = _get_uuid()
user_id = 1
assert db_diary.get_diary_by_uuid(_uuid, user_id) is None
db_diary.upsert_diary(user_id, _uuid, data)
diary = db_diary.get_diary_by_uuid(_uuid, user_id)
assert diary is not None
assert diary.get('time_created') == 11111111
assert diary.get('time_modified') == 11111111
# change this diary
data = {
'title': 'changed diary',
'content': 'changed diary',
'time': 2222222,
}
db_diary.upsert_diary(user_id, _uuid, data)
diary = db_diary.get_diary_by_uuid(_uuid, user_id)
assert diary is not None
assert diary.get('title') == 'changed diary'
assert diary.get('content') == 'changed diary'
assert diary.get('time_created') == 11111111
assert diary.get('time_modified') == 2222222
# delete this diary
time_delete = 333333333
db_diary.delete_diary(user_id, _uuid, time_delete)
diary = db_diary.get_diary_by_uuid(_uuid, user_id)
assert diary is None
def test_pull():
base_test.reinit_table()
# create mock user
_create_mock_user(1)
user_id = 1
# set last_sync_time
current_time = int(time.time())
last_sync_time = current_time - 1000
# generate new data[create, update, delete] since last_sync_time
uuid1 = _get_uuid()
db_diary.create_diary(user_id, uuid1, _get_title(), _get_content(), current_time)
uuid2 = _get_uuid()
db_diary.create_diary(user_id, uuid2, _get_title(), _get_content(), current_time)
db_diary.update_diary(user_id, uuid2, 'updated', 'updated', current_time + 100)
uuid3 = _get_uuid()
db_diary.create_diary(user_id, uuid3, _get_title(), _get_content(), current_time)
db_diary.delete_diary(user_id, uuid3, current_time + 150)
# assert uuid1 created, uuid2 created, uuid3 unknown
changed_diary_list = db_diary.get_diary_list_since_last_sync(user_id, last_sync_time)
assert len(changed_diary_list) == 3
def test_sync():
base_test.reinit_table()
# create mock user
_create_mock_user(1)
user_id = 1
current_time = int(time.time())
# user 1 create two diary long long ago
uuid_1 = _get_uuid()
uuid_2 = _get_uuid()
db_diary.create_diary(user_id, uuid_1, "first", "first", current_time - 10000)
db_diary.create_diary(user_id, uuid_2, "second", "second", current_time - 9000)
assert db_diary.get_diary_by_uuid(uuid_1, user_id) is not None
assert db_diary.get_diary_by_uuid(uuid_2, user_id) is not None
# until now, he update first diary, delete second diary, created one new diary. he starts sync
sync_token = None
uuid_3 = "2F69DEB5-B631-40DD-A65E-AFE9A0882275"
sync_items = [
{
'Diary': {
'update': {
'uuid': uuid_1,
'time': current_time - 2000,
'title': 'I update first diary',
'content': 'I update first diary'
}
}
},
{
'Diary': {
'delete': {
'uuid': uuid_2,
'time': current_time - 1000,
}
}
},
{
'Diary': {
'create': {
'uuid': uuid_3,
'time': current_time - 3000,
'title': 'this is third diary',
'content': 'this is third diary',
}
}
}
]
pull_result = logic_sync.sync_data(user_id, sync_token, sync_items, True)
# if sync success, user 1 currently will only own first & third diary
first_diary = db_diary.get_diary_by_uuid(uuid_1, user_id)
assert first_diary is not None
assert first_diary['title'] == 'I update first diary'
assert first_diary['content'] == 'I update first diary'
assert first_diary['time_modified'] == current_time - 2000
second_diary = db_diary.get_diary_by_uuid(uuid_2, user_id)
assert second_diary is None
third_diary = db_diary.get_diary_by_uuid(uuid_3, user_id)
assert third_diary is not None
assert third_diary['time_created'] == current_time - 3000
assert third_diary['time_modified'] == current_time - 3000
def _get_uuid():
return str(uuid.uuid1())
def _get_title():
return 'title %s' % int(time.time())
def _get_content():
return 'content %s' % int(time.time())
def _create_mock_user(count):
i = 1
while i <= count:
user = logic_user.signup("<EMAIL>" % i, "<PASSWORD>")
i += 1
assert user is not None
| 3,451 |
310 | <filename>gear/hardware/c/c015.json<gh_stars>100-1000
{
"name": "C015",
"description": "A 5 megapixel webcam.",
"url": "https://www.amazon.com/TeckNet%C2%AE-Webcam-Camera-MegaPixel-Microphone/dp/B00K11RI6W"
} | 91 |
502 | /*
* 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.iceberg.encryption.kms;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Enumeration;
import java.util.Map;
import javax.crypto.SecretKey;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
/**
* KMS client demo class, based on the Java KeyStore API that reads keys from standard PKCS12 keystore files.
* Not for use in production.
*/
public class KeyStoreKmsClient extends MemoryMockKMS {
// Path to keystore file. Preferably kept in volatile storage, such as ramdisk. Don't store with data.
public static final String KEYSTORE_FILE_PATH_PROP = "keystore.kms.client.file.path";
// Credentials (such as keystore password) must never be kept in a persistent storage.
// In this class, the password is passed as a system environment variable.
public static final String KEYSTORE_PASSWORD_ENV_VAR = "KEYSTORE_PASSWORD";
@Override
public String wrapKey(ByteBuffer key, String wrappingKeyId) {
// keytool keeps key names in lower case
return super.wrapKey(key, wrappingKeyId.toLowerCase());
}
@Override
public ByteBuffer unwrapKey(String wrappedKey, String wrappingKeyId) {
// keytool keeps key names in lower case
return super.unwrapKey(wrappedKey, wrappingKeyId.toLowerCase());
}
@Override
public void initialize(Map<String, String> properties) {
String keystorePath = properties.get(KEYSTORE_FILE_PATH_PROP);
Preconditions.checkNotNull(keystorePath, KEYSTORE_FILE_PATH_PROP + " must be set in hadoop or table " +
"properties");
String keystorePassword = System.getenv(KEYSTORE_PASSWORD_ENV_VAR);
Preconditions.checkNotNull(keystorePassword, KEYSTORE_PASSWORD_ENV_VAR + " environment variable " +
"must be set");
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance("PKCS12");
} catch (KeyStoreException e) {
throw new RuntimeException("Failed to init keystore", e);
}
char[] pwdArray = keystorePassword.toCharArray();
FileInputStream fis;
try {
fis = new FileInputStream(keystorePath);
} catch (FileNotFoundException e) {
throw new RuntimeException("Failed to find keystore file " + keystorePath, e);
}
try {
keyStore.load(fis, pwdArray);
} catch (IOException | NoSuchAlgorithmException | CertificateException e) {
throw new RuntimeException("Failed to load keystore file " + keystorePath, e);
}
Enumeration<String> keyAliases;
try {
keyAliases = keyStore.aliases();
} catch (KeyStoreException e) {
throw new RuntimeException("Failed to get key aliases in keystore file " + keystorePath, e);
}
masterKeys = Maps.newHashMap();
while (keyAliases.hasMoreElements()) {
String keyAlias = keyAliases.nextElement();
SecretKey secretKey;
try {
secretKey = (SecretKey) keyStore.getKey(keyAlias, pwdArray);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new RuntimeException("Failed to get key " + keyAlias, e);
}
masterKeys.put(keyAlias, secretKey.getEncoded());
}
if (masterKeys.isEmpty()) {
throw new RuntimeException("No keys found in " + keystorePath);
}
}
}
| 1,405 |
72,551 | <reponame>gandhi56/swift<filename>include/swift/SILOptimizer/Analysis/PassManagerVerifierAnalysis.h
//===--- PassManagerVerifierAnalysis.h ------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SILOPTIMIZER_ANALYSIS_PASSMANAGERVERIFIERANALYSIS_H
#define SWIFT_SILOPTIMIZER_ANALYSIS_PASSMANAGERVERIFIERANALYSIS_H
#include "swift/SIL/SILFunction.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "llvm/ADT/StringSet.h"
namespace swift {
/// An analysis that validates that the pass manager properly sends add/delete
/// messages as functions are added/deleted from the module.
///
/// All methods are no-ops when asserts are disabled.
class PassManagerVerifierAnalysis : public SILAnalysis {
/// The module that we are processing.
LLVM_ATTRIBUTE_UNUSED
SILModule &mod;
/// The set of "live" functions that we are tracking. We store the names of
/// the functions so that if a function is deleted we do not need to touch its
/// memory to get its name.
///
/// All functions in mod must be in liveFunctions and vis-a-versa.
llvm::StringSet<> liveFunctionNames;
public:
PassManagerVerifierAnalysis(SILModule *mod);
static bool classof(const SILAnalysis *analysis) {
return analysis->getKind() == SILAnalysisKind::PassManagerVerifier;
}
/// Validate that the analysis is able to look up all functions and that those
/// functions are live.
void invalidate() override final;
/// Validate that the analysis is able to look up the given function.
void invalidate(SILFunction *f, InvalidationKind k) override final;
/// If a function has not yet been seen start tracking it.
void notifyAddedOrModifiedFunction(SILFunction *f) override final;
/// Stop tracking a function.
void notifyWillDeleteFunction(SILFunction *f) override final;
/// Make sure that when we invalidate a function table, make sure we can find
/// all functions for all witness tables.
void invalidateFunctionTables() override final;
/// Run the entire verification.
void verifyFull() const override final;
};
} // namespace swift
#endif
| 707 |
348 | {"nom":"Dombasle-sur-Meurthe","circ":"4ème circonscription","dpt":"Meurthe-et-Moselle","inscrits":6781,"abs":3569,"votants":3212,"blancs":34,"nuls":16,"exp":3162,"res":[{"nuance":"REM","nom":"<NAME>","voix":983},{"nuance":"LR","nom":"<NAME>","voix":704},{"nuance":"FN","nom":"Mme <NAME>","voix":621},{"nuance":"FI","nom":"M. <NAME>","voix":367},{"nuance":"ECO","nom":"Mme <NAME>","voix":273},{"nuance":"DLF","nom":"<NAME>","voix":58},{"nuance":"ECO","nom":"M. <NAME>","voix":40},{"nuance":"EXG","nom":"Mme <NAME>","voix":38},{"nuance":"EXD","nom":"M. <NAME>","voix":31},{"nuance":"RDG","nom":"M. <NAME>","voix":20},{"nuance":"DIV","nom":"M. <NAME>","voix":19},{"nuance":"DIV","nom":"<NAME>","voix":8}]} | 291 |
432 | <reponame>lambdaxymox/DragonFlyBSD<filename>games/primes/pattern.c
/*-
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* <NAME>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)pattern.c 8.1 (Berkeley) 5/31/93
* $FreeBSD: src/games/primes/pattern.c,v 1.3.2.1 2002/10/23 14:59:14 fanf Exp $
* $DragonFly: src/games/primes/pattern.c,v 1.2 2003/06/17 04:25:24 dillon Exp $
*/
/*
* pattern - the Eratosthenes sieve on odd numbers for 3,5,7,11 and 13
*
* By: <NAME> <EMAIL>
*
* chongo <for a good prime call: 391581 * 2^216193 - 1> /\oo/\
*
* To avoid excessive sieves for small factors, we use the table below to
* setup our sieve blocks. Each element represents a odd number starting
* with 1. All non-zero elements are factors of 3, 5, 7, 11 and 13.
*/
#include <stddef.h>
#include "primes.h"
const char pattern[] = {
1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
0,0,0,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,0,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,0,1,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,0,0,0,
0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,
0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,0,1,
1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,0,0,0,1,0,1,
1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
0,0,0,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,
1,0,0,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,
1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,
0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,0,0,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,
0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,
1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,
0,0,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,0,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,
0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,
1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,0,0,0,
1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,0,1,
0,0,0,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,
0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,
1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,0,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,0,1,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
0,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,
0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,0,0,0,
1,0,0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,
1,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,1,
1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,
0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,0,0,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,
1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,
0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,0,0,1,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,
1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,
1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,
1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,0,0,1,0,0,0,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,
0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,
0,0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,
1,0,1,0,0,0,0,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,
1,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,0,1,0,1,0,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,
0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,
1,0,0,1,0,0,0,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,0,
0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,
0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,0,0,0,0,0,0,0,
1,0,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,
0,0,0,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,1,0,1,1,0,0,1,0,0,0,0,1,0,0,0,
0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,1,
0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,
1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,0,0,
1,0,0,1,0,1,0,0,1,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,
1,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,0,0,1,1,0,0,
1,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,0,0,1,
0,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1,
1,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,0,0,0,1,
0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,1,0,1,
1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,1,0,1,
0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,
1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,0,
1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,
1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,0,0,0,1,1,0,0,
0,0,1,1,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,
0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,
1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,1,1,0,0,0,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,
1,0,0,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,1,
1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,0,1,1,0,0,
1,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,0,1,0,0,1,0,1,0,0,1,
0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,
0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,0,0,0,0,0,1
};
const size_t pattern_size = (sizeof(pattern)/sizeof(pattern[0]));
| 31,209 |
1,531 | /*
* 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.ngrinder.home.controller;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.common.util.ThreadUtils;
import org.ngrinder.infra.config.Config;
import org.ngrinder.region.service.RegionService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Health check api controller.
*
* @since 3.5.0
*/
@Slf4j
@RestController
@RequiredArgsConstructor
public class HealthCheckApiController implements ControllerConstants {
private final RegionService regionService;
private final Config config;
/**
* Return the health check message. If there is shutdown lock, it returns
* 503. Otherwise it returns region lists.
*
* @param response response
* @return region list
*/
@GetMapping("/check/healthcheck")
public Map<String, Object> healthCheck(HttpServletResponse response) {
if (config.hasShutdownLock()) {
try {
response.sendError(503, "nGrinder is about to down");
} catch (IOException e) {
log.error("While running healthCheck() in HomeController, the error occurs.");
log.error("Details : ", e);
}
}
Map<String, Object> map = new HashMap<>();
map.put("current", regionService.getCurrent());
map.put("regions", regionService.getAll());
return map;
}
/**
* Return health check message with 1 sec delay. If there is shutdown lock,
* it returns 503. Otherwise, it returns region lists.
*
* @param sleep in milliseconds.
* @param response response
* @return region list
*/
@GetMapping("/check/healthcheck_slow")
public Map<String, Object> healthCheckSlowly(@RequestParam(value = "delay", defaultValue = "1000") int sleep,
HttpServletResponse response) {
ThreadUtils.sleep(sleep);
return healthCheck(response);
}
}
| 813 |
482 | <reponame>benmcclelland/GrovePi<filename>Software/Cpp/grove_button.cpp
//
// GrovePi Example for using the Grove Button (http://www.seeedstudio.com/wiki/Grove_-_Button)
//
// The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi
//
// Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi
//
/*
## License
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2017 Dexter Industries
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.
*/
#include "grovepi.h"
using namespace GrovePi;
// sudo g++ -Wall grovepi.cpp grove_button.cpp -o grove_button.out -> without grovepicpp package installed
// sudo g++ -Wall -lgrovepicpp grove_button.cpp -o grove_button.out -> with grovepicpp package installed
int main()
{
int button_pin = 4; // Grove Button is connected to digital port D4 on the GrovePi
int button_state; // variable to hold the current state of the button
try
{
initGrovePi(); // initialize communications w/ GrovePi
pinMode(button_pin, INPUT); // set the button_pin (D3) as INPUT
// do this indefinitely
while(true)
{
button_state = digitalRead(button_pin); // read the button state
printf("[pin %d][button state = ", button_pin); // and print it on the terminal screen
if(button_state == 0)
printf("not pressed]\n");
else
printf("pressed]\n");
delay(100); // wait 100 ms for the next reading
}
}
catch (I2CError &error)
{
printf(error.detail());
return -1;
}
return 0;
}
| 825 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-mm8r-8vpw-4648",
"modified": "2022-04-30T18:20:37Z",
"published": "2022-04-30T18:20:37Z",
"aliases": [
"CVE-2002-1141"
],
"details": "An input validation error in the Sun Microsystems RPC library Services for Unix 3.0 Interix SD, as implemented on Microsoft Windows NT4, 2000, and XP, allows remote attackers to cause a denial of service via malformed fragmented RPC client packets, aka \"Denial of service by sending an invalid RPC request.\"",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2002-1141"
},
{
"type": "WEB",
"url": "https://docs.microsoft.com/en-us/security-updates/securitybulletins/2002/ms02-057"
},
{
"type": "WEB",
"url": "http://www.iss.net/security_center/static/10259.php"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/5880"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 479 |
840 | #pragma once
// Circular buffer/queue of elements of type T, with capacity C.
// NOTE: Both read and write indexes will freely overflow uint32_t and that's fine.
template<typename T, unsigned int C>
class CircularBuffer {
static_assert(!(C & (C-1)), "Only power-of-two sizes of circular buffer are supported.");
static_assert(C > 0, "Please provide positive capacity");
public:
CircularBuffer() : read_idx_(0), write_idx_(0) {}
inline bool empty() {
return read_idx_ == write_idx_;
}
inline bool full() {
return size() >= C;
}
inline unsigned long size() {
return write_idx_ - read_idx_;
}
inline unsigned long max_size() {
return C;
}
inline const T& front() const {
return elems_[read_idx_ & (C-1)];
}
// Increment read counter.
inline void pop_front() {
if (!empty()) {
read_idx_++;
}
}
// Example usage:
// T cur_elem;
// while (c.dequeue(&cur_elem)) {
// // use cur_elem.
// }
inline bool dequeue(T *result_elem) {
if (!empty()) {
*result_elem = elems_[read_idx_ & (C-1)];
#ifdef __arm__
// As this function can be used across irq context, make sure the order is correct.
asm volatile ("dmb 0xF":::"memory");
#endif
read_idx_++;
return true;
} else {
return false;
}
}
// Example usage:
// c.enqueue(elem);
inline bool enqueue(const T& elem) {
if (!full()) {
elems_[write_idx_ & (C-1)] = elem;
#ifdef __arm__
// As this function can be used across irq context, make sure the order is correct.
asm volatile ("dmb 0xF":::"memory");
#endif
write_idx_++;
return true;
} else {
// TODO: We might want to increment an overflow counter here.
return false;
}
}
private:
volatile unsigned long read_idx_, write_idx_;
T elems_[C];
};
| 920 |
302 | <reponame>sesu089/stackoverflow
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QDebug>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QGraphicsView w;
QGraphicsScene *scene = new QGraphicsScene;
w.setScene(scene);
QList<QGraphicsPixmapItem *> items;
for (const QString &filename : {":/character.png", ":/owl.png"}) {
QGraphicsPixmapItem *item = scene->addPixmap(QPixmap(filename));
item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);
items << item;
}
items[1]->setPos(50, 22);
if (items[0]->collidingItems().isEmpty())
qDebug() << "there is no intersection";
w.show();
return a.exec();
}
| 303 |
7,064 | <reponame>jaguerraEmergya/elasticsearch-sql
/**
*
*/
/**
* @author ansj
*
*/
package org.elasticsearch.plugin.nlpcn; | 51 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-5f3g-f3qg-cgq4",
"modified": "2022-05-13T01:53:07Z",
"published": "2022-05-13T01:53:07Z",
"aliases": [
"CVE-2018-6533"
],
"details": "An issue was discovered in Icinga 2.x through 2.8.1. By editing the init.conf file, Icinga 2 can be run as root. Following this the program can be used to run arbitrary code as root. This was fixed by no longer using init.conf to determine account information for any root-executed code (a larger issue than CVE-2017-16933).",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-6533"
},
{
"type": "WEB",
"url": "https://github.com/Icinga/icinga2/pull/5850"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 465 |
421 | //<Snippet4>
using namespace System;
void main()
{
// Define an array of 8-bit signed integer values.
array<SByte>^ values = { SByte::MinValue, SByte::MaxValue,
0x3F, 123, -100 };
// Convert each value to a Decimal.
for each (SByte value in values) {
Decimal decValue = value;
Console::WriteLine("{0} ({1}) --> {2} ({3})", value,
value.GetType()->Name, decValue,
decValue.GetType()->Name);
}
}
// The example displays the following output:
// -128 (SByte) --> -128 (Decimal)
// 127 (SByte) --> 127 (Decimal)
// 63 (SByte) --> 63 (Decimal)
// 123 (SByte) --> 123 (Decimal)
// -100 (SByte) --> -100 (Decimal)
// </Snippet4>
| 410 |
320 | #include "MSXPPI.hh"
#include "LedStatus.hh"
#include "MSXCPUInterface.hh"
#include "MSXMotherBoard.hh"
#include "Reactor.hh"
#include "CassettePort.hh"
#include "RenShaTurbo.hh"
#include "GlobalSettings.hh"
#include "serialize.hh"
namespace openmsx {
MSXPPI::MSXPPI(const DeviceConfig& config)
: MSXDevice(config)
, cassettePort(getMotherBoard().getCassettePort())
, renshaTurbo(getMotherBoard().getRenShaTurbo())
, i8255(*this, getCurrentTime(), config.getGlobalSettings().getInvalidPpiModeSetting())
, click(config)
, keyboard(
config.getMotherBoard(),
config.getMotherBoard().getScheduler(),
config.getMotherBoard().getCommandController(),
config.getMotherBoard().getReactor().getEventDistributor(),
config.getMotherBoard().getMSXEventDistributor(),
config.getMotherBoard().getStateChangeDistributor(),
Keyboard::MATRIX_MSX, config)
, prevBits(15)
, selectedRow(0)
{
reset(getCurrentTime());
}
MSXPPI::~MSXPPI()
{
powerDown(EmuTime::dummy());
}
void MSXPPI::reset(EmuTime::param time)
{
i8255.reset(time);
click.reset(time);
}
void MSXPPI::powerDown(EmuTime::param /*time*/)
{
getLedStatus().setLed(LedStatus::CAPS, false);
}
byte MSXPPI::readIO(word port, EmuTime::param time)
{
return i8255.read(port & 0x03, time);
}
byte MSXPPI::peekIO(word port, EmuTime::param time) const
{
return i8255.peek(port & 0x03, time);
}
void MSXPPI::writeIO(word port, byte value, EmuTime::param time)
{
i8255.write(port & 0x03, value, time);
}
// I8255Interface
byte MSXPPI::readA(EmuTime::param time)
{
return peekA(time);
}
byte MSXPPI::peekA(EmuTime::param /*time*/) const
{
// port A is normally an output on MSX, reading from an output port
// is handled internally in the 8255
// TODO check this on a real MSX
// TODO returning 0 fixes the 'get_selected_slot' script right after
// reset (when PPI directions are not yet set). For now this
// solution is good enough.
return 0;
}
void MSXPPI::writeA(byte value, EmuTime::param /*time*/)
{
getCPUInterface().setPrimarySlots(value);
}
byte MSXPPI::readB(EmuTime::param time)
{
return peekB(time);
}
byte MSXPPI::peekB(EmuTime::param time) const
{
auto& keyb = const_cast<Keyboard&>(keyboard);
if (selectedRow != 8) {
return keyb.getKeys()[selectedRow];
} else {
return keyb.getKeys()[8] | (renshaTurbo.getSignal(time) ? 1:0);
}
}
void MSXPPI::writeB(byte /*value*/, EmuTime::param /*time*/)
{
// probably nothing happens on a real MSX
}
nibble MSXPPI::readC1(EmuTime::param time)
{
return peekC1(time);
}
nibble MSXPPI::peekC1(EmuTime::param /*time*/) const
{
return 15; // TODO check this
}
nibble MSXPPI::readC0(EmuTime::param time)
{
return peekC0(time);
}
nibble MSXPPI::peekC0(EmuTime::param /*time*/) const
{
return 15; // TODO check this
}
void MSXPPI::writeC1(nibble value, EmuTime::param time)
{
if ((prevBits ^ value) & 1) {
cassettePort.setMotor((value & 1) == 0, time); // 0=0n, 1=Off
}
if ((prevBits ^ value) & 2) {
cassettePort.cassetteOut((value & 2) != 0, time);
}
if ((prevBits ^ value) & 4) {
getLedStatus().setLed(LedStatus::CAPS, (value & 4) == 0);
}
if ((prevBits ^ value) & 8) {
click.setClick((value & 8) != 0, time);
}
prevBits = value;
}
void MSXPPI::writeC0(nibble value, EmuTime::param /*time*/)
{
selectedRow = value;
}
template<typename Archive>
void MSXPPI::serialize(Archive& ar, unsigned /*version*/)
{
ar.template serializeBase<MSXDevice>(*this);
ar.serialize("i8255", i8255);
// merge prevBits and selectedRow into one byte
byte portC = (prevBits << 4) | (selectedRow << 0);
ar.serialize("portC", portC);
if constexpr (Archive::IS_LOADER) {
selectedRow = (portC >> 0) & 0xF;
nibble bits = (portC >> 4) & 0xF;
writeC1(bits, getCurrentTime());
}
ar.serialize("keyboard", keyboard);
}
INSTANTIATE_SERIALIZE_METHODS(MSXPPI);
REGISTER_MSXDEVICE(MSXPPI, "PPI");
} // namespace openmsx
| 1,545 |
14,668 | # Copyright 2015 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.
from code import Code
from model import PropertyType
from datetime import datetime
LICENSE = """// Copyright %s 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.
"""
INFO = """// This file was generated by:
// %s.
"""
class JsUtil(object):
"""A helper class for generating JS Code.
"""
def GetLicense(self):
"""Returns the license text for JS extern and interface files.
"""
return (LICENSE % datetime.now().year)
def GetInfo(self, tool):
"""Returns text describing how the file was generated.
"""
return (INFO % tool)
def AppendObjectDefinition(self, c, namespace_name, properties,
new_line=True):
"""Given an OrderedDict of properties, returns a Code containing the
description of an object.
"""
if not properties:
return
c.Sblock('{', new_line=new_line)
first = True
for field, prop in properties.items():
# Avoid trailing comma.
# TODO(devlin): This will be unneeded, if/when
# https://github.com/google/closure-compiler/issues/796 is fixed.
if not first:
c.Append(',', new_line=False)
first = False
js_type = self._TypeToJsType(namespace_name, prop.type_)
if prop.optional:
js_type = (Code().Append('(')
.Concat(js_type, new_line=False)
.Append('|undefined)', new_line=False))
c.Append('%s: ' % field, strip_right=False)
c.Concat(js_type, new_line=False)
c.Eblock('}')
def AppendFunctionJsDoc(self, c, namespace_name, function):
"""Appends the documentation for a function as a Code.
Returns an empty code object if the object has no documentation.
"""
c.Sblock(line='/**', line_prefix=' * ')
if function.description:
c.Comment(function.description, comment_prefix='')
def append_field(c, tag, js_type, name, optional, description):
c.Append('@%s {' % tag)
c.Concat(js_type, new_line=False)
if optional:
c.Append('=', new_line=False)
c.Append('}', new_line=False)
c.Comment(' %s' % name, comment_prefix='', wrap_indent=4, new_line=False)
if description:
c.Comment(' %s' % description, comment_prefix='',
wrap_indent=4, new_line=False)
for i, param in enumerate(function.params):
# Mark the parameter as optional, *only if* all following parameters are
# also optional, to avoid JSC_OPTIONAL_ARG_AT_END errors thrown by Closure
# Compiler.
optional = (
all(p.optional for p in function.params[i:]) and
(function.returns_async is None or function.returns_async.optional))
js_type = self._TypeToJsType(namespace_name, param.type_)
# If the parameter was originally optional, but was followed by
# non-optional parameters, allow it to be `null` or `undefined` instead.
if not optional and param.optional:
js_type_string = js_type.Render()
# Remove the leading "!" from |js_type_string| if it exists, since "?!"
# is not a valid type modifier.
if js_type_string.startswith('!'):
js_type_string = js_type_string[1:]
js_type = Code().Append('?%s|undefined' % js_type_string)
append_field(c, 'param', js_type, param.name, optional, param.description)
if function.returns_async:
append_field(
c, 'param',
self._ReturnsAsyncToJsFunction(namespace_name,
function.returns_async),
function.returns_async.name, function.returns_async.optional,
function.returns_async.description)
if function.returns:
append_field(c, 'return',
self._TypeToJsType(namespace_name, function.returns),
'', False, function.returns.description)
if function.deprecated:
c.Append('@deprecated %s' % function.deprecated)
self.AppendSeeLink(c, namespace_name, 'method', function.name)
c.Eblock(' */')
def AppendTypeJsDoc(self, c, namespace_name, js_type, optional):
"""Appends the documentation for a type as a Code.
"""
c.Append('@type {')
if optional:
c.Append('(', new_line=False)
c.Concat(self._TypeToJsType(namespace_name, js_type), new_line=False)
c.Append('|undefined)', new_line=False)
else:
c.Concat(self._TypeToJsType(namespace_name, js_type), new_line=False)
c.Append('}', new_line=False)
def _FunctionToJsFunction(self, namespace_name, function):
"""Converts a model.Function to a JS type (i.e., function([params])...)"""
c = Code()
c.Append('function(')
c.Concat(
self._FunctionParamsToJsParams(namespace_name, function.params),
new_line=False)
c.Append('): ', new_line=False, strip_right=False)
if function.returns:
c.Concat(self._TypeToJsType(namespace_name, function.returns),
new_line=False)
else:
c.Append('void', new_line=False)
return c
def _ReturnsAsyncToJsFunction(self, namespace_name, returns_async):
"""Converts a model.ReturnsAsync to a JS function equivalent"""
# TODO(https://crbug.com/1142991) update this to generate promise-based
# types and show that as a return from the API function itself, rather than
# appended to the params as a callback.
c = Code()
c.Append('function(')
c.Concat(
self._FunctionParamsToJsParams(namespace_name, returns_async.params),
new_line=False)
c.Append('): ', new_line=False, strip_right=False)
c.Append('void', new_line=False)
return c
def _FunctionParamsToJsParams(self, namespace_name, params):
c = Code()
for i, param in enumerate(params):
t = self._TypeToJsType(namespace_name, param.type_)
if param.optional:
c.Append('(', new_line=False)
c.Concat(t, new_line=False)
c.Append('|undefined)', new_line=False)
else:
c.Concat(t, new_line=False)
if i is not len(params) - 1:
c.Append(', ', new_line=False, strip_right=False)
return c
def _TypeToJsType(self, namespace_name, js_type):
"""Converts a model.Type to a JS type (number, Array, etc.)"""
if js_type.property_type in (PropertyType.INTEGER, PropertyType.DOUBLE):
return Code().Append('number')
if js_type.property_type is PropertyType.OBJECT:
if js_type.properties:
c = Code()
self.AppendObjectDefinition(c, namespace_name, js_type.properties)
return c
# Support instanceof for types in the same namespace and built-in
# types. This doesn't support types in another namespace e.g. if
# js_type.instanceof is 'tabs.Tab'.
if js_type.instance_of:
if js_type.instance_of in js_type.namespace.types:
return Code().Append('chrome.%s.%s' %
(namespace_name, js_type.instance_of))
return Code().Append(js_type.instance_of)
return Code().Append('Object')
if js_type.property_type is PropertyType.ARRAY:
return (Code().Append('!Array<').
Concat(self._TypeToJsType(namespace_name, js_type.item_type),
new_line=False).
Append('>', new_line=False))
if js_type.property_type is PropertyType.REF:
ref_type = '!chrome.%s.%s' % (namespace_name, js_type.ref_type)
return Code().Append(ref_type)
if js_type.property_type is PropertyType.CHOICES:
c = Code()
c.Append('(')
for i, choice in enumerate(js_type.choices):
c.Concat(self._TypeToJsType(namespace_name, choice), new_line=False)
if i is not len(js_type.choices) - 1:
c.Append('|', new_line=False)
c.Append(')', new_line=False)
return c
if js_type.property_type is PropertyType.FUNCTION:
return self._FunctionToJsFunction(namespace_name, js_type.function)
if js_type.property_type is PropertyType.BINARY:
return Code().Append('ArrayBuffer')
if js_type.property_type is PropertyType.ANY:
return Code().Append('*')
if js_type.property_type.is_fundamental:
return Code().Append(js_type.property_type.name)
return Code().Append('?') # TODO(tbreisacher): Make this more specific.
def AppendSeeLink(self, c, namespace_name, object_type, object_name):
"""Appends a @see link for a given API 'object' (type, method, or event).
"""
# TODO(nigeltao): this should actually be gated on if there is
# documentation, rather than if it's a private API. Most private APIs
# aren't documented, but some are. For example:
# - https://developer.chrome.com/apps/developerPrivate exists
# - https://developer.chrome.com/apps/mediaPlayerPrivate does not
if namespace_name.endswith('Private'):
return
# NOTE(devlin): This is kind of a hack. Some APIs will be hosted on
# developer.chrome.com/apps/ instead of /extensions/, and some APIs have
# '.'s in them (like app.window), which should resolve to 'app_window'.
# Luckily, the doc server has excellent url resolution, and knows exactly
# what we mean. This saves us from needing any complicated logic here.
c.Append('@see https://developer.chrome.com/extensions/%s#%s-%s' %
(namespace_name, object_type, object_name))
| 3,833 |
3,102 | <filename>clang/test/OpenMP/nvptx_data_sharing.cpp
// Test device global memory data sharing codegen.
///==========================================================================///
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -disable-llvm-optzns | FileCheck %s --check-prefix CK1
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
void test_ds(){
#pragma omp target
{
int a = 10;
#pragma omp parallel
{
a = 1000;
}
int b = 100;
int c = 1000;
#pragma omp parallel private(c)
{
int *c1 = &c;
b = a + 10000;
}
}
}
// CK1: [[MEM_TY:%.+]] = type { [128 x i8] }
// CK1-DAG: [[SHARED_GLOBAL_RD:@.+]] = common addrspace(3) global [[MEM_TY]] zeroinitializer
// CK1-DAG: [[KERNEL_PTR:@.+]] = internal addrspace(3) global i8* null
// CK1-DAG: [[KERNEL_SIZE:@.+]] = internal unnamed_addr constant i64 8
// CK1-DAG: [[KERNEL_SHARED:@.+]] = internal unnamed_addr constant i16 1
/// ========= In the worker function ========= ///
// CK1: {{.*}}define internal void @__omp_offloading{{.*}}test_ds{{.*}}_worker()
// CK1: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0)
// CK1-NOT: call void @__kmpc_data_sharing_init_stack
/// ========= In the kernel function ========= ///
// CK1: {{.*}}define weak void @__omp_offloading{{.*}}test_ds{{.*}}()
// CK1: [[SHAREDARGS1:%.+]] = alloca i8**
// CK1: [[SHAREDARGS2:%.+]] = alloca i8**
// CK1: call void @__kmpc_kernel_init
// CK1: call void @__kmpc_data_sharing_init_stack
// CK1: [[SHARED_MEM_FLAG:%.+]] = load i16, i16* [[KERNEL_SHARED]],
// CK1: [[SIZE:%.+]] = load i64, i64* [[KERNEL_SIZE]],
// CK1: call void @__kmpc_get_team_static_memory(i16 0, i8* addrspacecast (i8 addrspace(3)* getelementptr inbounds ([[MEM_TY]], [[MEM_TY]] addrspace(3)* [[SHARED_GLOBAL_RD]], i32 0, i32 0, i32 0) to i8*), i64 [[SIZE]], i16 [[SHARED_MEM_FLAG]], i8** addrspacecast (i8* addrspace(3)* [[KERNEL_PTR]] to i8**))
// CK1: [[KERNEL_RD:%.+]] = load i8*, i8* addrspace(3)* [[KERNEL_PTR]],
// CK1: [[GLOBALSTACK:%.+]] = getelementptr inbounds i8, i8* [[KERNEL_RD]], i64 0
// CK1: [[GLOBALSTACK2:%.+]] = bitcast i8* [[GLOBALSTACK]] to %struct._globalized_locals_ty*
// CK1: [[A:%.+]] = getelementptr inbounds %struct._globalized_locals_ty, %struct._globalized_locals_ty* [[GLOBALSTACK2]], i32 0, i32 0
// CK1: [[B:%.+]] = getelementptr inbounds %struct._globalized_locals_ty, %struct._globalized_locals_ty* [[GLOBALSTACK2]], i32 0, i32 1
// CK1: store i32 10, i32* [[A]]
// CK1: call void @__kmpc_kernel_prepare_parallel({{.*}}, i16 1)
// CK1: call void @__kmpc_begin_sharing_variables(i8*** [[SHAREDARGS1]], i64 1)
// CK1: [[SHARGSTMP1:%.+]] = load i8**, i8*** [[SHAREDARGS1]]
// CK1: [[SHARGSTMP2:%.+]] = getelementptr inbounds i8*, i8** [[SHARGSTMP1]], i64 0
// CK1: [[SHAREDVAR:%.+]] = bitcast i32* [[A]] to i8*
// CK1: store i8* [[SHAREDVAR]], i8** [[SHARGSTMP2]]
// CK1: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0)
// CK1: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0)
// CK1: call void @__kmpc_end_sharing_variables()
// CK1: store i32 100, i32* [[B]]
// CK1: call void @__kmpc_kernel_prepare_parallel({{.*}}, i16 1)
// CK1: call void @__kmpc_begin_sharing_variables(i8*** [[SHAREDARGS2]], i64 2)
// CK1: [[SHARGSTMP3:%.+]] = load i8**, i8*** [[SHAREDARGS2]]
// CK1: [[SHARGSTMP4:%.+]] = getelementptr inbounds i8*, i8** [[SHARGSTMP3]], i64 0
// CK1: [[SHAREDVAR1:%.+]] = bitcast i32* [[B]] to i8*
// CK1: store i8* [[SHAREDVAR1]], i8** [[SHARGSTMP4]]
// CK1: [[SHARGSTMP12:%.+]] = getelementptr inbounds i8*, i8** [[SHARGSTMP3]], i64 1
// CK1: [[SHAREDVAR2:%.+]] = bitcast i32* [[A]] to i8*
// CK1: store i8* [[SHAREDVAR2]], i8** [[SHARGSTMP12]]
// CK1: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0)
// CK1: call void @__kmpc_barrier_simple_spmd(%struct.ident_t* null, i32 0)
// CK1: call void @__kmpc_end_sharing_variables()
// CK1: [[SHARED_MEM_FLAG:%.+]] = load i16, i16* [[KERNEL_SHARED]],
// CK1: call void @__kmpc_restore_team_static_memory(i16 0, i16 [[SHARED_MEM_FLAG]])
// CK1: call void @__kmpc_kernel_deinit(i16 1)
/// ========= In the data sharing wrapper function ========= ///
// CK1: {{.*}}define internal void @__omp_outlined{{.*}}wrapper({{.*}})
// CK1: [[SHAREDARGS4:%.+]] = alloca i8**
// CK1: call void @__kmpc_get_shared_variables(i8*** [[SHAREDARGS4]])
// CK1: [[SHARGSTMP13:%.+]] = load i8**, i8*** [[SHAREDARGS4]]
// CK1: [[SHARGSTMP14:%.+]] = getelementptr inbounds i8*, i8** [[SHARGSTMP13]], i64 0
// CK1: [[SHARGSTMP15:%.+]] = bitcast i8** [[SHARGSTMP14]] to i32**
// CK1: [[SHARGSTMP16:%.+]] = load i32*, i32** [[SHARGSTMP15]]
// CK1: call void @__omp_outlined__{{.*}}({{.*}}, i32* [[SHARGSTMP16]])
/// outlined function for the second parallel region ///
// CK1: define internal void @{{.+}}(i32* noalias %{{.+}}, i32* noalias %{{.+}}, i32* dereferenceable{{.+}}, i32* dereferenceable{{.+}})
// CK1-NOT: call i8* @__kmpc_data_sharing_push_stack(
// CK1: [[C_ADDR:%.+]] = alloca i32,
// CK1: store i32* [[C_ADDR]], i32** %
// CK1i-NOT: call void @__kmpc_data_sharing_pop_stack(
/// ========= In the data sharing wrapper function ========= ///
// CK1: {{.*}}define internal void @__omp_outlined{{.*}}wrapper({{.*}})
// CK1: [[SHAREDARGS3:%.+]] = alloca i8**
// CK1: call void @__kmpc_get_shared_variables(i8*** [[SHAREDARGS3]])
// CK1: [[SHARGSTMP5:%.+]] = load i8**, i8*** [[SHAREDARGS3]]
// CK1: [[SHARGSTMP6:%.+]] = getelementptr inbounds i8*, i8** [[SHARGSTMP5]], i64 0
// CK1: [[SHARGSTMP7:%.+]] = bitcast i8** [[SHARGSTMP6]] to i32**
// CK1: [[SHARGSTMP8:%.+]] = load i32*, i32** [[SHARGSTMP7]]
// CK1: [[SHARGSTMP9:%.+]] = getelementptr inbounds i8*, i8** [[SHARGSTMP5]], i64 1
// CK1: [[SHARGSTMP10:%.+]] = bitcast i8** [[SHARGSTMP9]] to i32**
// CK1: [[SHARGSTMP11:%.+]] = load i32*, i32** [[SHARGSTMP10]]
// CK1: call void @__omp_outlined__{{.*}}({{.*}}, i32* [[SHARGSTMP8]], i32* [[SHARGSTMP11]])
#endif
| 2,797 |
3,428 | <gh_stars>1000+
{"id":"00739","group":"easy-ham-1","checksum":{"type":"MD5","value":"9034df113ffe0cff225c698efcea7426"},"text":"From <EMAIL> Mon Sep 23 23:45:34 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 7795716F03\n\tfor <jm@localhost>; Mon, 23 Sep 2002 23:45:34 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 23 Sep 2002 23:45:34 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g8NMfvC06032 for <<EMAIL>>;\n Mon, 23 Sep 2002 23:41:58 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id 8BC202941D8; Mon, 23 Sep 2002 15:38:07 -0700 (PDT)\nDelivered-To: <EMAIL>\nReceived: from crank.slack.net (slack.net [192.168.127.121]) by xent.com\n (Postfix) with ESMTP id 3EB2329409A for <<EMAIL>>; Mon,\n 23 Sep 2002 15:37:54 -0700 (PDT)\nReceived: by crank.slack.net (Postfix, from userid 596) id 59BF13ED81;\n Mon, 23 Sep 2002 18:46:14 -0400 (EDT)\nReceived: from localhost (localhost [127.0.0.1]) by crank.slack.net\n (Postfix) with ESMTP id 4EA673ED60 for <<EMAIL>>; Mon,\n 23 Sep 2002 18:46:14 -0400 (EDT)\nFrom: Tom <<EMAIL>>\nTo: <EMAIL>\nSubject: Googlenews\nMessage-Id: <<EMAIL>.44.0209231842<EMAIL>.29230-<EMAIL>>\nMIME-Version: 1.0\nContent-Type: TEXT/PLAIN; charset=US-ASCII\nSender: fork-<EMAIL>\nErrors-To: fork-admin@x<EMAIL>.com\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of Rohit Khare <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Mon, 23 Sep 2002 18:46:14 -0400 (EDT)\n\n\nThe further googlization of my screentimes....News...No not just\nnews...google news. I love the line that tells me how fresh/stale the news\nitem is....phreaking cewl.\n\nSo far I like the content range.\n\n\n\n\n"} | 978 |
311 | {
"GunicornTokioWebWorker.init_process": {
"has": [
"global",
"import"
],
"raises": [
"AssertionError"
]
},
"GunicornUVLoopWebWorker.init_process": {
"has": [
"global",
"import"
],
"raises": [
"AssertionError"
]
},
"GunicornWebWorker._create_ssl_context": {
"raises": [
"RuntimeError"
]
},
"GunicornWebWorker._get_valid_log_format": {
"raises": [
"ValueError"
]
},
"GunicornWebWorker._run": {
"raises": [
"AssertionError",
"RuntimeError"
]
},
"GunicornWebWorker._wait_next_notify": {
"raises": [
"AssertionError"
]
},
"GunicornWebWorker.handle_abort": {
"raises": [
"SystemExit"
]
},
"GunicornWebWorker.run": {
"raises": [
"SystemExit"
]
}
} | 429 |
320 | /*
* Copyright (c) 2009-2018 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.gde.materials.multiview.widgets;
import com.jme3.gde.materials.MaterialProperty;
import javax.swing.JPanel;
/**
*
* @author normenhansen
*/
public abstract class MaterialPropertyWidget extends JPanel {
protected MaterialProperty property;
private MaterialWidgetListener listener;
public void registerChangeListener(MaterialWidgetListener listener) {
this.listener = listener;
}
protected void fireChanged() {
if (listener == null) {
return;
}
listener.propertyChanged(property);
}
/**
* @return the properties
*/
public MaterialProperty getProperty() {
return property;
}
/**
* @param properties the properties to set
*/
public void setProperty(MaterialProperty property) {
this.property = property;
readProperty();
}
protected abstract void readProperty();
public void cleanUp() {
}
}
| 810 |
8,027 | <reponame>Unknoob/buck
package com.facebook.buck.infer.testdata.several_libraries;
public class JavaSmokeTest {
public String warnReturnNullableFromNonnullable() {
L1 o = new L2().getL1();
return o.getNullableString();
}
}
| 88 |
329 | <reponame>cloudsoft/cm_api<filename>java/src/main/java/com/cloudera/api/model/ApiTimeSeriesRow.java<gh_stars>100-1000
//Licensed to Cloudera, Inc. under one
//or more contributor license agreements. See the NOTICE file
//distributed with this work for additional information
//regarding copyright ownership. Cloudera, Inc. licenses this file
//to you under the Apache License, Version 2.0 (the
//"License"); you may not use this file except in compliance
//with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
package com.cloudera.api.model;
import java.util.Date;
import com.google.common.base.Preconditions;
/**
* A time series data point.
*/
public class ApiTimeSeriesRow {
private String entityName;
private String metricName;
private Date timestamp;
private double value;
public ApiTimeSeriesRow() {
}
public ApiTimeSeriesRow(
final String entityName,
final String metricName,
final Date timestamp,
final double value) {
Preconditions.checkNotNull(entityName);
Preconditions.checkNotNull(metricName);
Preconditions.checkNotNull(timestamp);
this.entityName = entityName;
this.metricName = metricName;
this.timestamp = timestamp;
this.value = value;
}
/** The name of the entity for this time series data point. */
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
/** The name of the metric for this time series data point. */
public String getMetricName() {
return metricName;
}
public void setMetricName(String metricName) {
this.metricName = metricName;
}
/**
* The timestamp for this time series data point. Note that the timestamp
* reflects coordinated universal time (UTC) and not necessarily the server's
* time zone. The rest API formats the UTC timestamp as an ISO-8061 string.
*/
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
/** The value for this time series data point. */
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
} | 788 |
627 | <reponame>Rob-S/indy-node
from collections import OrderedDict
from indy_common.types import RevocDefValueField, ClientRevocDefSubmitField
from plenum.common.messages.fields import IntegerField, AnyMapField, NonEmptyStringField, ConstantField, ChooseField, \
LimitedLengthStringField
from indy_common.constants import ISSUANCE_TYPE, MAX_CRED_NUM, PUBLIC_KEYS, \
TAILS_LOCATION, TAILS_HASH, ID, REVOC_TYPE, TXN_TYPE, TAG, CRED_DEF_ID, VALUE
EXPECTED_REVOC_DEF_VALUE_FIELDS = OrderedDict([
(ISSUANCE_TYPE, ChooseField),
(MAX_CRED_NUM, IntegerField),
(PUBLIC_KEYS, AnyMapField),
(TAILS_HASH, NonEmptyStringField),
(TAILS_LOCATION, NonEmptyStringField),
])
EXPECTED_REVOC_DEF_SUBMIT_FIELDS = OrderedDict([
(TXN_TYPE, ConstantField),
(ID, NonEmptyStringField),
(REVOC_TYPE, LimitedLengthStringField),
(TAG, LimitedLengthStringField),
(CRED_DEF_ID, NonEmptyStringField),
(VALUE, RevocDefValueField)
])
def test_revoc_value_has_expected_fields():
actual_field_names = OrderedDict(
RevocDefValueField.schema).keys()
assert actual_field_names == EXPECTED_REVOC_DEF_VALUE_FIELDS.keys()
def test_revoc_value_has_expected_validators():
schema = dict(RevocDefValueField.schema)
for field, validator in EXPECTED_REVOC_DEF_VALUE_FIELDS.items():
assert isinstance(schema[field], validator)
def test_client_submit_has_expected_fields():
actual_field_names = OrderedDict(
ClientRevocDefSubmitField.schema).keys()
assert actual_field_names == EXPECTED_REVOC_DEF_SUBMIT_FIELDS.keys()
def test_client_submit_has_expected_validators():
schema = dict(ClientRevocDefSubmitField.schema)
for field, validator in EXPECTED_REVOC_DEF_SUBMIT_FIELDS.items():
assert isinstance(schema[field], validator)
| 688 |
454 | <reponame>agave233/PaddleHelix
#!/usr/bin/python
#-*-coding:utf-8-*-
# Copyright (c) 2020 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.
"""
GEM pretrain
"""
import os
from os.path import join, exists, basename
import sys
import argparse
import time
import numpy as np
from glob import glob
import logging
import paddle
import paddle.distributed as dist
from pahelix.datasets.inmemory_dataset import InMemoryDataset
from pahelix.utils import load_json_config
from pahelix.featurizers.gem_featurizer import GeoPredTransformFn, GeoPredCollateFn
from pahelix.model_zoo.gem_model import GeoGNNModel, GeoPredModel
from src.utils import exempt_parameters
def train(args, model, optimizer, data_gen):
"""tbd"""
model.train()
steps = get_steps_per_epoch(args)
step = 0
list_loss = []
for graph_dict, feed_dict in data_gen:
print('rank:%s step:%s' % (dist.get_rank(), step))
# if dist.get_rank() == 1:
# time.sleep(100000)
for k in graph_dict:
graph_dict[k] = graph_dict[k].tensor()
for k in feed_dict:
feed_dict[k] = paddle.to_tensor(feed_dict[k])
train_loss = model(graph_dict, feed_dict)
train_loss.backward()
optimizer.step()
optimizer.clear_grad()
list_loss.append(train_loss.numpy().mean())
step += 1
if step > steps:
print("jumpping out")
break
return np.mean(list_loss)
@paddle.no_grad()
def evaluate(args, model, test_dataset, collate_fn):
"""tbd"""
model.eval()
data_gen = test_dataset.get_data_loader(
batch_size=args.batch_size,
num_workers=args.num_workers,
shuffle=True,
collate_fn=collate_fn)
dict_loss = {'loss': []}
for graph_dict, feed_dict in data_gen:
for k in graph_dict:
graph_dict[k] = graph_dict[k].tensor()
for k in feed_dict:
feed_dict[k] = paddle.to_tensor(feed_dict[k])
loss, sub_losses = model(graph_dict, feed_dict, return_subloss=True)
for name in sub_losses:
if not name in dict_loss:
dict_loss[name] = []
v_np = sub_losses[name].numpy()
dict_loss[name].append(v_np)
dict_loss['loss'] = loss.numpy()
dict_loss = {name: np.mean(dict_loss[name]) for name in dict_loss}
return dict_loss
def get_steps_per_epoch(args):
"""tbd"""
# add as argument
if args.dataset == 'zinc':
train_num = int(20000000 * (1 - args.test_ratio))
else:
raise ValueError(args.dataset)
if args.DEBUG:
train_num = 100
steps_per_epoch = int(train_num / args.batch_size)
if args.distributed:
steps_per_epoch = int(steps_per_epoch / dist.get_world_size())
return steps_per_epoch
def load_smiles_to_dataset(data_path):
"""tbd"""
files = sorted(glob('%s/*' % data_path))
data_list = []
for file in files:
with open(file, 'r') as f:
tmp_data_list = [line.strip() for line in f.readlines()]
data_list.extend(tmp_data_list)
dataset = InMemoryDataset(data_list=data_list)
return dataset
def main(args):
"""tbd"""
compound_encoder_config = load_json_config(args.compound_encoder_config)
model_config = load_json_config(args.model_config)
if not args.dropout_rate is None:
compound_encoder_config['dropout_rate'] = args.dropout_rate
model_config['dropout_rate'] = args.dropout_rate
compound_encoder = GeoGNNModel(compound_encoder_config)
model = GeoPredModel(model_config, compound_encoder)
if args.distributed:
model = paddle.DataParallel(model)
opt = paddle.optimizer.Adam(learning_rate=args.lr, parameters=model.parameters())
print('Total param num: %s' % (len(model.parameters())))
for i, param in enumerate(model.named_parameters()):
print(i, param[0], param[1].name)
if not args.init_model is None and not args.init_model == "":
compound_encoder.set_state_dict(paddle.load(args.init_model))
print('Load state_dict from %s' % args.init_model)
# get dataset
dataset = load_smiles_to_dataset(args.data_path)
if args.DEBUG:
dataset = dataset[100:180]
dataset = dataset[dist.get_rank()::dist.get_world_size()]
smiles_lens = [len(smiles) for smiles in dataset]
print('Total size:%s' % (len(dataset)))
print('Dataset smiles min/max/avg length: %s/%s/%s' % (
np.min(smiles_lens), np.max(smiles_lens), np.mean(smiles_lens)))
transform_fn = GeoPredTransformFn(model_config['pretrain_tasks'], model_config['mask_ratio'])
# this step will be time consuming due to rdkit 3d calculation
dataset.transform(transform_fn, num_workers=args.num_workers)
test_index = int(len(dataset) * (1 - args.test_ratio))
train_dataset = dataset[:test_index]
test_dataset = dataset[test_index:]
print("Train/Test num: %s/%s" % (len(train_dataset), len(test_dataset)))
collate_fn = GeoPredCollateFn(
atom_names=compound_encoder_config['atom_names'],
bond_names=compound_encoder_config['bond_names'],
bond_float_names=compound_encoder_config['bond_float_names'],
bond_angle_float_names=compound_encoder_config['bond_angle_float_names'],
pretrain_tasks=model_config['pretrain_tasks'],
mask_ratio=model_config['mask_ratio'],
Cm_vocab=model_config['Cm_vocab'])
train_data_gen = train_dataset.get_data_loader(
batch_size=args.batch_size,
num_workers=args.num_workers,
shuffle=True,
collate_fn=collate_fn)
list_test_loss = []
for epoch_id in range(args.max_epoch):
s = time.time()
train_loss = train(args, model, opt, train_data_gen)
test_loss = evaluate(args, model, test_dataset, collate_fn)
if not args.distributed or dist.get_rank() == 0:
paddle.save(compound_encoder.state_dict(),
'%s/epoch%d.pdparams' % (args.model_dir, epoch_id))
list_test_loss.append(test_loss['loss'])
print("epoch:%d train/loss:%s" % (epoch_id, train_loss))
print("epoch:%d test/loss:%s" % (epoch_id, test_loss))
print("Time used:%ss" % (time.time() - s))
if not args.distributed or dist.get_rank() == 0:
print('Best epoch id:%s' % np.argmin(list_test_loss))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--DEBUG", action='store_true', default=False)
parser.add_argument("--distributed", action='store_true', default=False)
parser.add_argument("--batch_size", type=int, default=256)
parser.add_argument("--num_workers", type=int, default=4)
parser.add_argument("--max_epoch", type=int, default=100)
parser.add_argument("--dataset", type=str, default='zinc')
parser.add_argument("--data_path", type=str, default=None)
parser.add_argument("--test_ratio", type=float, default=0.1)
parser.add_argument("--compound_encoder_config", type=str)
parser.add_argument("--model_config", type=str)
parser.add_argument("--init_model", type=str)
parser.add_argument("--model_dir", type=str)
parser.add_argument("--lr", type=float, default=0.001)
parser.add_argument("--dropout_rate", type=float, default=0.2)
args = parser.parse_args()
if args.distributed:
dist.init_parallel_env()
main(args) | 3,516 |
5,964 | /* bio.h for openssl */
#include <wolfssl/openssl/bio.h>
| 25 |
5,169 | {
"name": "WalmartBuynowSDK",
"version": "1.0.3-beta",
"summary": "Walmart Buynow SDK Kit for iOS",
"description": "Walmart Buynow SDK is designed to let you drive sales right in your app or on your website. SDK components like BuyNow button can be placed next to a product offering on the website or in a mobile application and it can be configured to directly add the product to the cart on Walmart.com.s the world's largest retailer, and the Walmart Open API provides",
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"frameworks": [
"Foundation",
"UIKit"
],
"homepage": "https://affiliates.walmart.com/#!/mobilesdk",
"license": "Private",
"source": {
"git": "https://gecgithub01.walmart.com/labs-affiliates/WalmartSDKKit-iOS-Source.git",
"tag": "1.0.3-beta"
},
"authors": {
"@WalmartLabs": "<EMAIL>"
},
"source_files": [
"WalmartBuynowSDK",
"WalmartBuynowSDK/**/*.{h,m}"
],
"public_header_files": [
"WalmartBuynowSDK/**/public/**/*.h",
"WalmartBuynowSDK/WalmartBuynowSDK.h"
],
"resources": "WalmartBuynowSDK/Resources/WMTSDKMedia.xcassets",
"module_map": "WalmartBuynowSDK/module.modulemap",
"dependencies": {
"WalmartOpenApi": [
"~> 1"
]
}
}
| 488 |
3,262 | #pragma once
#include "../utils/utils.h"
#include "../time/halleytime.h"
namespace Halley {
enum class TweenCurve {
Linear,
Cosine
};
template <typename T>
class Tween {
public:
Tween() {}
Tween(T a, T b, Time length = 1.0, TweenCurve curve = TweenCurve::Linear)
: a(std::move(a))
, b(std::move(b))
, length(length)
, curve(curve)
{}
float getProgress() const
{
return float(time / length);
}
T getValue() const
{
float t = getProgress();
switch (curve) {
case TweenCurve::Cosine:
t = smoothCos(t);
break;
default:
// Do nothing
break;
}
return interpolate(a, b, t);
}
void update(Time t)
{
time = clamp(time + t * direction, 0.0, length);
}
Tween& setLength(Time t)
{
length = t;
return *this;
}
Tween& setStart(T _a)
{
a = std::move(_a);
return *this;
}
Tween& setEnd(T _b)
{
b = std::move(_b);
return *this;
}
Tween& resetTarget(T target)
{
a = getValue();
b = std::move(target);
time = 0;
direction = 1;
return *this;
}
Tween& setDirection(int dir)
{
direction = dir;
return *this;
}
Tween& setCurve(TweenCurve c)
{
curve = c;
return *this;
}
private:
T a;
T b;
Time time = 0.0;
Time length = 1.0;
int direction = 0;
TweenCurve curve = TweenCurve::Linear;
};
} | 668 |
1,078 | <gh_stars>1000+
// { Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/*You are required to complete this function*/
class Solution{
public:
int maxLen(vector<int>&A, int n)
{
unordered_map<int, int> map;
int sum = 0;
int len = 0;
for (int i = 0; i < n; i++) {
sum += A[i];
if (A[i] == 0 && len == 0)
len = 1;
if (sum == 0)
len = i + 1;
if (map.find(sum) != map.end()) {
len = max(len, i - map[sum]);
}
else {
map[sum] = i;
}
}
return len;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int m;
cin>>m;
vector<int> array1(m);
for (int i = 0; i < m; ++i){
cin>>array1[i];
}
Solution ob;
cout<<ob.maxLen(array1,m)<<endl;
}
return 0;
}
// } Driver Code Ends | 640 |
793 | // Test that the --print-supported-cpus flag works
// REQUIRES: x86-registered-target
// RUN: %clang --target=x86_64-unknown-linux-gnu \
// RUN: --print-supported-cpus 2>&1 \
// RUN: | FileCheck %s --check-prefix=CHECK-X86
// CHECK-X86: Target: x86_64-unknown-linux-gnu
// CHECK-X86: corei7
// CHECK-X86: Use -mcpu or -mtune to specify the target's processor.
// REQUIRES: arm-registered-target
// RUN: %clang --target=arm-unknown-linux-android \
// RUN: --print-supported-cpus 2>&1 \
// RUN: | FileCheck %s --check-prefix=CHECK-ARM
// CHECK-ARM: Target: arm-unknown-linux-android
// CHECK-ARM: cortex-a73
// CHECK-ARM: cortex-a75
// CHECK-ARM: Use -mcpu or -mtune to specify the target's processor.
| 269 |
799 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from datetime import datetime
from unittest.mock import patch
from pyowm.commons.image import Image, ImageTypeEnum
from pyowm.agroapi10.enums import PresetEnum, SatelliteEnum
from pyowm.agroapi10.imagery import MetaImage, SatelliteImage
class TestMetaImage(unittest.TestCase):
test_acquisition_time = 1378459200
test_iso_acquisition_time = "2013-09-06 09:20:00+00:00"
test_date_acquisition_time = datetime.fromisoformat(test_iso_acquisition_time)
test_instance = MetaImage('http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, test_acquisition_time, 98.2, 0.3, 11.7, 7.89,
polygon_id='my_polygon', stats_url='http://stats.com')
def test_init_fails_with_wrong_parameters(self):
self.assertRaises(AssertionError, MetaImage, None, PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 0.3, 11.7, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, 'a_string', 98.2, 0.3, 11.7, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, -567, 98.2, 0.3, 11.7, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 'a_string', 0.3, 11.7, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, -32.1, 0.3, 11.7, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 'a_string', 11.7, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, -21.1, 11.7, 7.89)
# sun azimuth
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 21.1, 'a_string', 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2, self.test_acquisition_time, 98.2, 21.1, -54.4, 7.89)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 21.1, 368.4, 7.89)
# sun elevation
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 21.1, 54.4, 'a_string')
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 21.1, 54.4, -32.2)
self.assertRaises(AssertionError, MetaImage, 'http://a.com', PresetEnum.FALSE_COLOR,
SatelliteEnum.SENTINEL_2.name, self.test_acquisition_time, 98.2, 21.1, 54.4, 100.3)
def test_acquisition_time_returning_different_formats(self):
self.assertEqual(self.test_instance.acquisition_time(timeformat='unix'),
self.test_acquisition_time)
self.assertEqual(self.test_instance.acquisition_time(timeformat='iso'),
self.test_iso_acquisition_time)
self.assertEqual(self.test_instance.acquisition_time(timeformat='date'),
self.test_date_acquisition_time)
def test_acquisition_time_fails_with_unknown_timeformat(self):
self.assertRaises(ValueError, MetaImage.acquisition_time, self.test_instance, 'xyz')
def test_repr(self):
repr(self.test_instance)
class TestSatelliteImage(unittest.TestCase):
test_image = Image(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x00\x00\x00\x01', ImageTypeEnum.PNG)
test_instance = SatelliteImage(TestMetaImage.test_instance, test_image,
downloaded_on=TestMetaImage.test_acquisition_time)
def test_init_fails_with_wrong_parameters(self):
with self.assertRaises(AssertionError):
SatelliteImage(None, self.test_image)
with self.assertRaises(AssertionError):
SatelliteImage(TestMetaImage.test_instance, None)
with self.assertRaises(AssertionError):
SatelliteImage(TestMetaImage.test_instance, self.test_image, downloaded_on='not_an_int')
with self.assertRaises(AssertionError):
SatelliteImage(TestMetaImage.test_instance, self.test_image, downloaded_on=1234567, palette=888)
def test_downloaded_on_returning_different_formats(self):
self.assertEqual(self.test_instance.downloaded_on(timeformat='unix'),
TestMetaImage.test_acquisition_time)
self.assertEqual(self.test_instance.downloaded_on(timeformat='iso'),
TestMetaImage.test_iso_acquisition_time)
self.assertEqual(self.test_instance.downloaded_on(timeformat='date'),
TestMetaImage.test_date_acquisition_time)
def test_downloaded_on_fails_with_unknown_timeformat(self):
self.assertRaises(ValueError, SatelliteImage.downloaded_on, self.test_instance, 'xyz')
def test_repr(self):
repr(self.test_instance)
def test_init(self):
test_instance = SatelliteImage(TestMetaImage.test_instance, self.test_image)
self.assertFalse(hasattr(test_instance, '_downloaded_on'))
def test_persist(self):
with patch('builtins.open', unittest.mock.mock_open()) as mocked_open:
persists = self.test_instance.persist('filename')
assert persists is None
mocked_open.assert_called_once_with('filename', 'wb')
| 3,020 |
551 | #ifndef DARWIN_CRASH_H
#define DARWIN_CRASH_H
namespace CrashHandler {
std::string
GetLogsDirectory();
void
InformUserOfCrash(const std::string& sPath);
bool
IsDebuggerPresent();
void
DebugBreak();
}
#endif /* DARWIN_CRASH_H */
| 85 |
1,993 | <filename>instrumentation/jms/src/test/java/brave/jms/ITJms_1_1_TracingMessageConsumer.java
/*
* Copyright 2013-2020 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* 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 brave.jms;
import brave.Tags;
import brave.handler.MutableSpan;
import brave.messaging.MessagingRuleSampler;
import brave.messaging.MessagingTracing;
import brave.propagation.B3SingleFormat;
import brave.propagation.SamplingFlags;
import brave.propagation.TraceContext;
import brave.sampler.Sampler;
import java.util.Collections;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import org.junit.After;
import org.junit.Before;
import org.junit.ComparisonFailure;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import static brave.Span.Kind.CONSUMER;
import static brave.jms.MessageProperties.getPropertyIfString;
import static brave.jms.MessageProperties.setStringProperty;
import static brave.messaging.MessagingRequestMatchers.channelNameEquals;
import static org.assertj.core.api.Assertions.assertThat;
/** When adding tests here, also add to {@link brave.jms.ITTracingJMSConsumer} */
public class ITJms_1_1_TracingMessageConsumer extends ITJms {
@Rule public TestName testName = new TestName();
@Rule public JmsTestRule jms = newJmsTestRule(testName);
Session tracedSession;
MessageProducer messageProducer;
MessageConsumer messageConsumer;
QueueSession tracedQueueSession;
QueueSender queueSender;
QueueReceiver queueReceiver;
TopicSession tracedTopicSession;
TopicPublisher topicPublisher;
TopicSubscriber topicSubscriber;
JmsTestRule newJmsTestRule(TestName testName) {
return new JmsTestRule.ActiveMQ(testName);
}
TextMessage message;
BytesMessage bytesMessage;
@Before public void setup() throws JMSException {
tracedSession = jmsTracing.connection(jms.connection)
.createSession(false, Session.AUTO_ACKNOWLEDGE);
tracedQueueSession = jmsTracing.queueConnection(jms.queueConnection)
.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
tracedTopicSession = jmsTracing.topicConnection(jms.topicConnection)
.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = jms.session.createProducer(jms.destination);
messageConsumer = tracedSession.createConsumer(jms.destination);
queueSender = jms.queueSession.createSender(jms.queue);
queueReceiver = tracedQueueSession.createReceiver(jms.queue);
topicPublisher = jms.topicSession.createPublisher(jms.topic);
topicSubscriber = tracedTopicSession.createSubscriber(jms.topic);
message = jms.newMessage("foo");
bytesMessage = jms.newBytesMessage("foo");
lockMessages();
}
void lockMessages() throws JMSException {
// this forces us to handle JMS write concerns!
jms.setReadOnlyProperties(message, true);
jms.setReadOnlyProperties(bytesMessage, true);
bytesMessage.reset();
}
TraceContext resetB3PropertyWithNewSampledContext(JmsTestRule jms) throws JMSException {
TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
message = jms.newMessage("foo");
bytesMessage = jms.newBytesMessage("foo");
String b3 = B3SingleFormat.writeB3SingleFormatWithoutParentId(parent);
setStringProperty(message, "b3", b3);
setStringProperty(bytesMessage, "b3", b3);
lockMessages();
return parent;
}
@After public void tearDownTraced() throws JMSException {
tracedSession.close();
tracedQueueSession.close();
tracedTopicSession.close();
}
@Test public void messageListener_runsAfterConsumer() throws JMSException {
messageListener_runsAfterConsumer(() -> messageProducer.send(message), messageConsumer);
}
@Test public void messageListener_runsAfterConsumer_queue() throws JMSException {
messageListener_runsAfterConsumer(() -> queueSender.send(message), queueReceiver);
}
@Test public void messageListener_runsAfterConsumer_topic() throws JMSException {
messageListener_runsAfterConsumer(() -> topicPublisher.send(message), topicSubscriber);
}
void messageListener_runsAfterConsumer(JMSRunnable send, MessageConsumer messageConsumer)
throws JMSException {
messageConsumer.setMessageListener(m -> {
});
send.run();
MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
MutableSpan listenerSpan = testSpanHandler.takeLocalSpan();
assertChildOf(listenerSpan, consumerSpan);
assertSequential(consumerSpan, listenerSpan);
}
@Test public void messageListener_startsNewTrace() throws JMSException {
messageListener_startsNewTrace(
() -> messageProducer.send(message),
messageConsumer,
Collections.singletonMap("jms.queue", jms.destinationName)
);
}
@Test public void messageListener_startsNewTrace_bytes() throws JMSException {
messageListener_startsNewTrace(
() -> messageProducer.send(bytesMessage),
messageConsumer,
Collections.singletonMap("jms.queue", jms.destinationName)
);
}
@Test public void messageListener_startsNewTrace_queue() throws JMSException {
messageListener_startsNewTrace(
() -> queueSender.send(message),
queueReceiver,
Collections.singletonMap("jms.queue", jms.queueName)
);
}
@Test public void messageListener_startsNewTrace_topic() throws JMSException {
messageListener_startsNewTrace(
() -> topicPublisher.send(message),
topicSubscriber,
Collections.singletonMap("jms.topic", jms.topicName)
);
}
void messageListener_startsNewTrace(JMSRunnable send, MessageConsumer messageConsumer,
Map<String, String> consumerTags) throws JMSException {
messageConsumer.setMessageListener(
m -> {
tracing.tracer().currentSpanCustomizer().name("message-listener");
// clearing headers ensures later work doesn't try to use the old parent
String b3 = getPropertyIfString(m, "b3");
tracing.tracer().currentSpanCustomizer().tag("b3", String.valueOf(b3 != null));
}
);
send.run();
MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
MutableSpan listenerSpan = testSpanHandler.takeLocalSpan();
assertThat(consumerSpan.name()).isEqualTo("receive");
assertThat(consumerSpan.parentId()).isNull(); // root span
assertThat(consumerSpan.tags()).containsAllEntriesOf(consumerTags);
assertChildOf(listenerSpan, consumerSpan);
assertThat(listenerSpan.name()).isEqualTo("message-listener"); // overridden name
assertThat(listenerSpan.tags())
.hasSize(1) // no redundant copy of consumer tags
.containsEntry("b3", "false"); // b3 header not leaked to listener
}
@Test public void messageListener_resumesTrace() throws JMSException {
messageListener_resumesTrace(() -> messageProducer.send(message), messageConsumer);
}
@Test public void messageListener_resumesTrace_bytes() throws JMSException {
messageListener_resumesTrace(() -> messageProducer.send(bytesMessage), messageConsumer);
}
@Test public void messageListener_resumesTrace_queue() throws JMSException {
messageListener_resumesTrace(() -> queueSender.send(message), queueReceiver);
}
@Test public void messageListener_resumesTrace_topic() throws JMSException {
messageListener_resumesTrace(() -> topicPublisher.send(message), topicSubscriber);
}
void messageListener_resumesTrace(JMSRunnable send, MessageConsumer messageConsumer)
throws JMSException {
messageConsumer.setMessageListener(m -> {
// clearing headers ensures later work doesn't try to use the old parent
String b3 = getPropertyIfString(m, "b3");
tracing.tracer().currentSpanCustomizer().tag("b3", String.valueOf(b3 != null));
}
);
TraceContext parent = resetB3PropertyWithNewSampledContext(jms);
send.run();
MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
MutableSpan listenerSpan = testSpanHandler.takeLocalSpan();
assertChildOf(consumerSpan, parent);
assertChildOf(listenerSpan, consumerSpan);
assertThat(listenerSpan.tags())
.hasSize(1) // no redundant copy of consumer tags
.containsEntry("b3", "false"); // b3 header not leaked to listener
}
@Test public void messageListener_readsBaggage() throws JMSException {
messageListener_readsBaggage(() -> messageProducer.send(message), messageConsumer);
}
@Test public void messageListener_readsBaggage_bytes() throws JMSException {
messageListener_readsBaggage(() -> messageProducer.send(bytesMessage), messageConsumer);
}
@Test public void messageListener_readsBaggage_queue() throws JMSException {
messageListener_readsBaggage(() -> queueSender.send(message), queueReceiver);
}
@Test public void messageListener_readsBaggage_topic() throws JMSException {
messageListener_readsBaggage(() -> topicPublisher.send(message), topicSubscriber);
}
void messageListener_readsBaggage(JMSRunnable send, MessageConsumer messageConsumer)
throws JMSException {
messageConsumer.setMessageListener(m ->
Tags.BAGGAGE_FIELD.tag(BAGGAGE_FIELD, tracing.tracer().currentSpan())
);
message = jms.newMessage("baggage");
bytesMessage = jms.newBytesMessage("baggage");
String baggage = "joey";
setStringProperty(message, BAGGAGE_FIELD_KEY, baggage);
setStringProperty(bytesMessage, BAGGAGE_FIELD_KEY, baggage);
lockMessages();
send.run();
MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
MutableSpan listenerSpan = testSpanHandler.takeLocalSpan();
assertThat(consumerSpan.parentId()).isNull();
assertChildOf(listenerSpan, consumerSpan);
assertThat(listenerSpan.tags())
.containsEntry(BAGGAGE_FIELD.name(), baggage);
}
@Test public void receive_startsNewTrace() throws JMSException {
receive_startsNewTrace(
() -> messageProducer.send(message),
messageConsumer,
Collections.singletonMap("jms.queue", jms.destinationName)
);
}
@Test public void receive_startsNewTrace_queue() throws JMSException {
receive_startsNewTrace(
() -> queueSender.send(message),
queueReceiver,
Collections.singletonMap("jms.queue", jms.queueName)
);
}
@Test public void receive_startsNewTrace_topic() throws JMSException {
receive_startsNewTrace(
() -> topicPublisher.send(message),
topicSubscriber,
Collections.singletonMap("jms.topic", jms.topicName)
);
}
void receive_startsNewTrace(JMSRunnable send, MessageConsumer messageConsumer,
Map<String, String> consumerTags) throws JMSException {
send.run();
messageConsumer.receive();
MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
assertThat(consumerSpan.name()).isEqualTo("receive");
assertThat(consumerSpan.parentId()).isNull(); // root span
assertThat(consumerSpan.tags()).containsAllEntriesOf(consumerTags);
}
@Test public void receive_resumesTrace() throws JMSException {
receive_resumesTrace(() -> messageProducer.send(message), messageConsumer);
}
@Test public void receive_resumesTrace_bytes() throws JMSException {
receive_resumesTrace(() -> messageProducer.send(bytesMessage), messageConsumer);
}
@Test public void receive_resumesTrace_queue() throws JMSException {
receive_resumesTrace(() -> queueSender.send(message), queueReceiver);
}
@Test public void receive_resumesTrace_topic() throws JMSException {
receive_resumesTrace(() -> topicPublisher.send(message), topicSubscriber);
}
void receive_resumesTrace(JMSRunnable send, MessageConsumer messageConsumer) throws JMSException {
TraceContext parent = resetB3PropertyWithNewSampledContext(jms);
send.run();
Message received = messageConsumer.receive();
MutableSpan consumerSpan = testSpanHandler.takeRemoteSpan(CONSUMER);
assertChildOf(consumerSpan, parent);
assertThat(received.getStringProperty("b3"))
.isEqualTo(parent.traceIdString() + "-" + consumerSpan.id() + "-1");
}
@Test public void receive_customSampler() throws JMSException {
queueReceiver.close();
tracedSession.close();
MessagingRuleSampler consumerSampler = MessagingRuleSampler.newBuilder()
.putRule(channelNameEquals(jms.queue.getQueueName()), Sampler.NEVER_SAMPLE)
.build();
try (MessagingTracing messagingTracing = MessagingTracing.newBuilder(tracing)
.consumerSampler(consumerSampler)
.build()) {
// JMS 1.1 didn't have auto-closeable. tearDownTraced closes these
tracedQueueSession = JmsTracing.create(messagingTracing)
.queueConnection(jms.queueConnection)
.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
messageConsumer = tracedQueueSession.createConsumer(jms.queue);
queueSender.send(message);
// Check that the message headers are not sampled
assertThat(messageConsumer.receive().getStringProperty("b3"))
.endsWith("-0");
}
// @After will also check that the consumer was not sampled
}
}
| 4,613 |
1,724 | /*
* Copyright 2008-present MongoDB, 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 org.bson.codecs.pojo.entities;
public final class ReusedGenericsModel<A, B, C> {
private A field1;
private B field2;
private C field3;
private Integer field4;
private C field5;
private B field6;
private A field7;
private String field8;
public ReusedGenericsModel() {
}
public ReusedGenericsModel(final A field1, final B field2, final C field3, final Integer field4, final C field5, final B field6,
final A field7, final String field8) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
this.field4 = field4;
this.field5 = field5;
this.field6 = field6;
this.field7 = field7;
this.field8 = field8;
}
/**
* Returns the field1
*
* @return the field1
*/
public A getField1() {
return field1;
}
public void setField1(final A field1) {
this.field1 = field1;
}
/**
* Returns the field2
*
* @return the field2
*/
public B getField2() {
return field2;
}
public void setField2(final B field2) {
this.field2 = field2;
}
/**
* Returns the field3
*
* @return the field3
*/
public C getField3() {
return field3;
}
public void setField3(final C field3) {
this.field3 = field3;
}
/**
* Returns the field4
*
* @return the field4
*/
public Integer getField4() {
return field4;
}
public void setField4(final Integer field4) {
this.field4 = field4;
}
/**
* Returns the field5
*
* @return the field5
*/
public C getField5() {
return field5;
}
public void setField5(final C field5) {
this.field5 = field5;
}
/**
* Returns the field6
*
* @return the field6
*/
public B getField6() {
return field6;
}
public void setField6(final B field6) {
this.field6 = field6;
}
/**
* Returns the field7
*
* @return the field7
*/
public A getField7() {
return field7;
}
public void setField7(final A field7) {
this.field7 = field7;
}
/**
* Returns the field8
*
* @return the field8
*/
public String getField8() {
return field8;
}
public void setField8(final String field8) {
this.field8 = field8;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ReusedGenericsModel)) {
return false;
}
ReusedGenericsModel<?, ?, ?> that = (ReusedGenericsModel<?, ?, ?>) o;
if (getField1() != null ? !getField1().equals(that.getField1()) : that.getField1() != null) {
return false;
}
if (getField2() != null ? !getField2().equals(that.getField2()) : that.getField2() != null) {
return false;
}
if (getField3() != null ? !getField3().equals(that.getField3()) : that.getField3() != null) {
return false;
}
if (getField4() != null ? !getField4().equals(that.getField4()) : that.getField4() != null) {
return false;
}
if (getField5() != null ? !getField5().equals(that.getField5()) : that.getField5() != null) {
return false;
}
if (getField6() != null ? !getField6().equals(that.getField6()) : that.getField6() != null) {
return false;
}
if (getField7() != null ? !getField7().equals(that.getField7()) : that.getField7() != null) {
return false;
}
if (getField8() != null ? !getField8().equals(that.getField8()) : that.getField8() != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = getField1() != null ? getField1().hashCode() : 0;
result = 31 * result + (getField2() != null ? getField2().hashCode() : 0);
result = 31 * result + (getField3() != null ? getField3().hashCode() : 0);
result = 31 * result + (getField4() != null ? getField4().hashCode() : 0);
result = 31 * result + (getField5() != null ? getField5().hashCode() : 0);
result = 31 * result + (getField6() != null ? getField6().hashCode() : 0);
result = 31 * result + (getField7() != null ? getField7().hashCode() : 0);
result = 31 * result + (getField8() != null ? getField8().hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ReusedGenericsModel{"
+ "field1=" + field1
+ ", field2=" + field2
+ ", field3=" + field3
+ ", field4=" + field4
+ ", field5=" + field5
+ ", field6=" + field6
+ ", field7=" + field7
+ ", field8='" + field8 + "'"
+ "}";
}
}
| 2,541 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.