repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
tzuyangliu/Xcode9-Runtime-Headers
IDEKit/IDEAppEnergyGraph.h
<filename>IDEKit/IDEAppEnergyGraph.h // // 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 <IDEKit/IDEBarGraph.h> @interface IDEAppEnergyGraph : IDEBarGraph { BOOL _hasOSXAppNapGuidance; } @property(nonatomic) BOOL hasOSXAppNapGuidance; // @synthesize hasOSXAppNapGuidance=_hasOSXAppNapGuidance; - (double)xLabelSpacing; - (Class)graphClass; @end
mmk-code/blender
source/blender/makesrna/intern/rna_mesh.c
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* note: the original vertex color stuff is now just used for * getting info on the layers themselves, accessing the data is * done through the (not yet written) mpoly interfaces.*/ /** \file * \ingroup RNA */ #include <stdlib.h> #include "MEM_guardedalloc.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_object_types.h" #include "BLI_math_base.h" #include "BLI_math_rotation.h" #include "BLI_utildefines.h" #include "BKE_editmesh.h" #include "RNA_access.h" #include "RNA_define.h" #include "RNA_types.h" #include "RNA_enum_types.h" #include "rna_internal.h" #include "WM_types.h" const EnumPropertyItem rna_enum_mesh_delimit_mode_items[] = { {BMO_DELIM_NORMAL, "NORMAL", 0, "Regular", "Delimit by face directions"}, {BMO_DELIM_MATERIAL, "MATERIAL", 0, "Material", "Delimit by face material"}, {BMO_DELIM_SEAM, "SEAM", 0, "Seam", "Delimit by edge seams"}, {BMO_DELIM_SHARP, "SHARP", 0, "Sharp", "Delimit by sharp edges"}, {BMO_DELIM_UV, "UV", 0, "UVs", "Delimit by UV coordinates"}, {0, NULL, 0, NULL, NULL}, }; #ifdef RNA_RUNTIME # include "DNA_scene_types.h" # include "BLI_math.h" # include "BKE_customdata.h" # include "BKE_main.h" # include "BKE_mesh.h" # include "BKE_mesh_runtime.h" # include "BKE_report.h" # include "DEG_depsgraph.h" # include "ED_mesh.h" /* XXX Bad level call */ # include "WM_api.h" # include "rna_mesh_utils.h" /* -------------------------------------------------------------------- */ /* Generic helpers */ static Mesh *rna_mesh(PointerRNA *ptr) { Mesh *me = (Mesh *)ptr->id.data; return me; } static CustomData *rna_mesh_vdata_helper(Mesh *me) { return (me->edit_mesh) ? &me->edit_mesh->bm->vdata : &me->vdata; } static CustomData *rna_mesh_edata_helper(Mesh *me) { return (me->edit_mesh) ? &me->edit_mesh->bm->edata : &me->edata; } static CustomData *rna_mesh_pdata_helper(Mesh *me) { return (me->edit_mesh) ? &me->edit_mesh->bm->pdata : &me->pdata; } static CustomData *rna_mesh_ldata_helper(Mesh *me) { return (me->edit_mesh) ? &me->edit_mesh->bm->ldata : &me->ldata; } static CustomData *rna_mesh_fdata_helper(Mesh *me) { return (me->edit_mesh) ? NULL : &me->fdata; } static CustomData *rna_mesh_vdata(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return rna_mesh_vdata_helper(me); } # if 0 static CustomData *rna_mesh_edata(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return rna_mesh_edata_helper(me); } # endif static CustomData *rna_mesh_pdata(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return rna_mesh_pdata_helper(me); } static CustomData *rna_mesh_ldata(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return rna_mesh_ldata_helper(me); } /* -------------------------------------------------------------------- */ /* Generic CustomData Layer Functions */ static void rna_cd_layer_name_set(CustomData *cdata, CustomDataLayer *cdl, const char *value) { BLI_strncpy_utf8(cdl->name, value, sizeof(cdl->name)); CustomData_set_layer_unique_name(cdata, cdl - cdata->layers); } /* avoid using where possible!, ideally the type is known */ static CustomData *rna_cd_from_layer(PointerRNA *ptr, CustomDataLayer *cdl) { /* find out where we come from by */ Mesh *me = ptr->id.data; CustomData *cd; /* rely on negative values wrapping */ # define TEST_CDL(cmd) \ if ((void)(cd = cmd(me)), ARRAY_HAS_ITEM(cdl, cd->layers, cd->totlayer)) \ return cd TEST_CDL(rna_mesh_vdata_helper); TEST_CDL(rna_mesh_edata_helper); TEST_CDL(rna_mesh_pdata_helper); TEST_CDL(rna_mesh_ldata_helper); TEST_CDL(rna_mesh_fdata_helper); # undef TEST_CDL /* should _never_ happen */ return NULL; } static void rna_MeshVertexLayer_name_set(PointerRNA *ptr, const char *value) { rna_cd_layer_name_set(rna_mesh_vdata(ptr), (CustomDataLayer *)ptr->data, value); } # if 0 static void rna_MeshEdgeLayer_name_set(PointerRNA *ptr, const char *value) { rna_cd_layer_name_set(rna_mesh_edata(ptr), (CustomDataLayer *)ptr->data, value); } # endif static void rna_MeshPolyLayer_name_set(PointerRNA *ptr, const char *value) { rna_cd_layer_name_set(rna_mesh_pdata(ptr), (CustomDataLayer *)ptr->data, value); } static void rna_MeshLoopLayer_name_set(PointerRNA *ptr, const char *value) { rna_cd_layer_name_set(rna_mesh_ldata(ptr), (CustomDataLayer *)ptr->data, value); } /* only for layers shared between types */ static void rna_MeshAnyLayer_name_set(PointerRNA *ptr, const char *value) { CustomData *cd = rna_cd_from_layer(ptr, (CustomDataLayer *)ptr->data); rna_cd_layer_name_set(cd, (CustomDataLayer *)ptr->data, value); } static bool rna_Mesh_has_custom_normals_get(PointerRNA *ptr) { Mesh *me = ptr->data; return BKE_mesh_has_custom_loop_normals(me); } /* -------------------------------------------------------------------- */ /* Update Callbacks */ static void rna_Mesh_update_data(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { ID *id = ptr->id.data; /* cheating way for importers to avoid slow updates */ if (id->us > 0) { DEG_id_tag_update(id, 0); WM_main_add_notifier(NC_GEOM | ND_DATA, id); } } static void rna_Mesh_update_data_edit_weight(Main *bmain, Scene *scene, PointerRNA *ptr) { BKE_mesh_batch_cache_dirty_tag(rna_mesh(ptr), BKE_MESH_BATCH_DIRTY_ALL); rna_Mesh_update_data(bmain, scene, ptr); } static void rna_Mesh_update_data_edit_active_color(Main *bmain, Scene *scene, PointerRNA *ptr) { BKE_mesh_batch_cache_dirty_tag(rna_mesh(ptr), BKE_MESH_BATCH_DIRTY_ALL); rna_Mesh_update_data(bmain, scene, ptr); } static void rna_Mesh_update_select(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { ID *id = ptr->id.data; /* cheating way for importers to avoid slow updates */ if (id->us > 0) { WM_main_add_notifier(NC_GEOM | ND_SELECT, id); } } void rna_Mesh_update_draw(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { ID *id = ptr->id.data; /* cheating way for importers to avoid slow updates */ if (id->us > 0) { WM_main_add_notifier(NC_GEOM | ND_DATA, id); } } static void rna_Mesh_update_vertmask(Main *bmain, Scene *scene, PointerRNA *ptr) { Mesh *me = ptr->data; if ((me->editflag & ME_EDIT_PAINT_VERT_SEL) && (me->editflag & ME_EDIT_PAINT_FACE_SEL)) { me->editflag &= ~ME_EDIT_PAINT_FACE_SEL; } BKE_mesh_batch_cache_dirty_tag(me, BKE_MESH_BATCH_DIRTY_ALL); rna_Mesh_update_draw(bmain, scene, ptr); } static void rna_Mesh_update_facemask(Main *bmain, Scene *scene, PointerRNA *ptr) { Mesh *me = ptr->data; if ((me->editflag & ME_EDIT_PAINT_VERT_SEL) && (me->editflag & ME_EDIT_PAINT_FACE_SEL)) { me->editflag &= ~ME_EDIT_PAINT_VERT_SEL; } BKE_mesh_batch_cache_dirty_tag(me, BKE_MESH_BATCH_DIRTY_ALL); rna_Mesh_update_draw(bmain, scene, ptr); } /* -------------------------------------------------------------------- */ /* Property get/set Callbacks */ static void rna_MeshVertex_normal_get(PointerRNA *ptr, float *value) { MVert *mvert = (MVert *)ptr->data; normal_short_to_float_v3(value, mvert->no); } static void rna_MeshVertex_normal_set(PointerRNA *ptr, const float *value) { MVert *mvert = (MVert *)ptr->data; float no[3]; copy_v3_v3(no, value); normalize_v3(no); normal_float_to_short_v3(mvert->no, no); } static float rna_MeshVertex_bevel_weight_get(PointerRNA *ptr) { MVert *mvert = (MVert *)ptr->data; return mvert->bweight / 255.0f; } static void rna_MeshVertex_bevel_weight_set(PointerRNA *ptr, float value) { MVert *mvert = (MVert *)ptr->data; mvert->bweight = round_fl_to_uchar_clamp(value * 255.0f); } static float rna_MEdge_bevel_weight_get(PointerRNA *ptr) { MEdge *medge = (MEdge *)ptr->data; return medge->bweight / 255.0f; } static void rna_MEdge_bevel_weight_set(PointerRNA *ptr, float value) { MEdge *medge = (MEdge *)ptr->data; medge->bweight = round_fl_to_uchar_clamp(value * 255.0f); } static float rna_MEdge_crease_get(PointerRNA *ptr) { MEdge *medge = (MEdge *)ptr->data; return medge->crease / 255.0f; } static void rna_MEdge_crease_set(PointerRNA *ptr, float value) { MEdge *medge = (MEdge *)ptr->data; medge->crease = round_fl_to_uchar_clamp(value * 255.0f); } static void rna_MeshLoop_normal_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); MLoop *ml = (MLoop *)ptr->data; const float(*vec)[3] = CustomData_get(&me->ldata, (int)(ml - me->mloop), CD_NORMAL); if (!vec) { zero_v3(values); } else { copy_v3_v3(values, (const float *)vec); } } static void rna_MeshLoop_normal_set(PointerRNA *ptr, const float *values) { Mesh *me = rna_mesh(ptr); MLoop *ml = (MLoop *)ptr->data; float(*vec)[3] = CustomData_get(&me->ldata, (int)(ml - me->mloop), CD_NORMAL); if (vec) { normalize_v3_v3(*vec, values); } } static void rna_MeshLoop_tangent_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); MLoop *ml = (MLoop *)ptr->data; const float(*vec)[4] = CustomData_get(&me->ldata, (int)(ml - me->mloop), CD_MLOOPTANGENT); if (!vec) { zero_v3(values); } else { copy_v3_v3(values, (const float *)vec); } } static float rna_MeshLoop_bitangent_sign_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MLoop *ml = (MLoop *)ptr->data; const float(*vec)[4] = CustomData_get(&me->ldata, (int)(ml - me->mloop), CD_MLOOPTANGENT); return (vec) ? (*vec)[3] : 0.0f; } static void rna_MeshLoop_bitangent_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); MLoop *ml = (MLoop *)ptr->data; const float(*nor)[3] = CustomData_get(&me->ldata, (int)(ml - me->mloop), CD_NORMAL); const float(*vec)[4] = CustomData_get(&me->ldata, (int)(ml - me->mloop), CD_MLOOPTANGENT); if (nor && vec) { cross_v3_v3v3(values, (const float *)nor, (const float *)vec); mul_v3_fl(values, (*vec)[3]); } else { zero_v3(values); } } static void rna_MeshPolygon_normal_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); MPoly *mp = (MPoly *)ptr->data; BKE_mesh_calc_poly_normal(mp, me->mloop + mp->loopstart, me->mvert, values); } static void rna_MeshPolygon_center_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); MPoly *mp = (MPoly *)ptr->data; BKE_mesh_calc_poly_center(mp, me->mloop + mp->loopstart, me->mvert, values); } static float rna_MeshPolygon_area_get(PointerRNA *ptr) { Mesh *me = (Mesh *)ptr->id.data; MPoly *mp = (MPoly *)ptr->data; return BKE_mesh_calc_poly_area(mp, me->mloop + mp->loopstart, me->mvert); } static void rna_MeshPolygon_flip(ID *id, MPoly *mp) { Mesh *me = (Mesh *)id; BKE_mesh_polygon_flip(mp, me->mloop, &me->ldata); BKE_mesh_tessface_clear(me); BKE_mesh_runtime_clear_geometry(me); } static void rna_MeshLoopTriangle_verts_get(PointerRNA *ptr, int *values) { Mesh *me = rna_mesh(ptr); MLoopTri *lt = (MLoopTri *)ptr->data; values[0] = me->mloop[lt->tri[0]].v; values[1] = me->mloop[lt->tri[1]].v; values[2] = me->mloop[lt->tri[2]].v; } static void rna_MeshLoopTriangle_normal_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); MLoopTri *lt = (MLoopTri *)ptr->data; unsigned int v1 = me->mloop[lt->tri[0]].v; unsigned int v2 = me->mloop[lt->tri[1]].v; unsigned int v3 = me->mloop[lt->tri[2]].v; normal_tri_v3(values, me->mvert[v1].co, me->mvert[v2].co, me->mvert[v3].co); } static void rna_MeshLoopTriangle_split_normals_get(PointerRNA *ptr, float *values) { Mesh *me = rna_mesh(ptr); const float(*lnors)[3] = CustomData_get_layer(&me->ldata, CD_NORMAL); if (!lnors) { zero_v3(values + 0); zero_v3(values + 3); zero_v3(values + 6); } else { MLoopTri *lt = (MLoopTri *)ptr->data; copy_v3_v3(values + 0, lnors[lt->tri[0]]); copy_v3_v3(values + 3, lnors[lt->tri[1]]); copy_v3_v3(values + 6, lnors[lt->tri[2]]); } } static float rna_MeshLoopTriangle_area_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MLoopTri *lt = (MLoopTri *)ptr->data; unsigned int v1 = me->mloop[lt->tri[0]].v; unsigned int v2 = me->mloop[lt->tri[1]].v; unsigned int v3 = me->mloop[lt->tri[2]].v; return area_tri_v3(me->mvert[v1].co, me->mvert[v2].co, me->mvert[v3].co); } static void rna_MeshLoopColor_color_get(PointerRNA *ptr, float *values) { MLoopCol *mlcol = (MLoopCol *)ptr->data; values[0] = mlcol->r / 255.0f; values[1] = mlcol->g / 255.0f; values[2] = mlcol->b / 255.0f; values[3] = mlcol->a / 255.0f; } static void rna_MeshLoopColor_color_set(PointerRNA *ptr, const float *values) { MLoopCol *mlcol = (MLoopCol *)ptr->data; mlcol->r = round_fl_to_uchar_clamp(values[0] * 255.0f); mlcol->g = round_fl_to_uchar_clamp(values[1] * 255.0f); mlcol->b = round_fl_to_uchar_clamp(values[2] * 255.0f); mlcol->a = round_fl_to_uchar_clamp(values[3] * 255.0f); } static int rna_Mesh_texspace_editable(PointerRNA *ptr, const char **UNUSED(r_info)) { Mesh *me = (Mesh *)ptr->data; return (me->texflag & ME_AUTOSPACE) ? 0 : PROP_EDITABLE; } static void rna_Mesh_texspace_size_get(PointerRNA *ptr, float values[3]) { Mesh *me = (Mesh *)ptr->data; if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) { BKE_mesh_texspace_calc(me); } copy_v3_v3(values, me->size); } static void rna_Mesh_texspace_loc_get(PointerRNA *ptr, float values[3]) { Mesh *me = (Mesh *)ptr->data; if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) { BKE_mesh_texspace_calc(me); } copy_v3_v3(values, me->loc); } static void rna_MeshVertex_groups_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); if (me->dvert) { MVert *mvert = (MVert *)ptr->data; MDeformVert *dvert = me->dvert + (mvert - me->mvert); rna_iterator_array_begin( iter, (void *)dvert->dw, sizeof(MDeformWeight), dvert->totweight, 0, NULL); } else rna_iterator_array_begin(iter, NULL, 0, 0, 0, NULL); } static void rna_MeshVertex_undeformed_co_get(PointerRNA *ptr, float values[3]) { Mesh *me = rna_mesh(ptr); MVert *mvert = (MVert *)ptr->data; float(*orco)[3] = CustomData_get_layer(&me->vdata, CD_ORCO); if (orco) { /* orco is normalized to 0..1, we do inverse to match mvert->co */ float loc[3], size[3]; BKE_mesh_texspace_get(me->texcomesh ? me->texcomesh : me, loc, NULL, size); madd_v3_v3v3v3(values, loc, orco[(mvert - me->mvert)], size); } else copy_v3_v3(values, mvert->co); } static int rna_CustomDataLayer_active_get(PointerRNA *ptr, CustomData *data, int type, bool render) { int n = ((CustomDataLayer *)ptr->data) - data->layers; if (render) return (n == CustomData_get_render_layer_index(data, type)); else return (n == CustomData_get_active_layer_index(data, type)); } static int rna_CustomDataLayer_clone_get(PointerRNA *ptr, CustomData *data, int type) { int n = ((CustomDataLayer *)ptr->data) - data->layers; return (n == CustomData_get_clone_layer_index(data, type)); } static void rna_CustomDataLayer_active_set( PointerRNA *ptr, CustomData *data, int value, int type, int render) { Mesh *me = ptr->id.data; int n = (((CustomDataLayer *)ptr->data) - data->layers) - CustomData_get_layer_index(data, type); if (value == 0) return; if (render) CustomData_set_layer_render(data, type, n); else CustomData_set_layer_active(data, type, n); BKE_mesh_update_customdata_pointers(me, true); } static void rna_CustomDataLayer_clone_set(PointerRNA *ptr, CustomData *data, int value, int type) { int n = ((CustomDataLayer *)ptr->data) - data->layers; if (value == 0) return; CustomData_set_layer_clone_index(data, type, n); } static bool rna_MEdge_freestyle_edge_mark_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MEdge *medge = (MEdge *)ptr->data; FreestyleEdge *fed = CustomData_get(&me->edata, (int)(medge - me->medge), CD_FREESTYLE_EDGE); return fed && (fed->flag & FREESTYLE_EDGE_MARK) != 0; } static void rna_MEdge_freestyle_edge_mark_set(PointerRNA *ptr, bool value) { Mesh *me = rna_mesh(ptr); MEdge *medge = (MEdge *)ptr->data; FreestyleEdge *fed = CustomData_get(&me->edata, (int)(medge - me->medge), CD_FREESTYLE_EDGE); if (!fed) { fed = CustomData_add_layer(&me->edata, CD_FREESTYLE_EDGE, CD_CALLOC, NULL, me->totedge); } if (value) { fed->flag |= FREESTYLE_EDGE_MARK; } else { fed->flag &= ~FREESTYLE_EDGE_MARK; } } static bool rna_MPoly_freestyle_face_mark_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MPoly *mpoly = (MPoly *)ptr->data; FreestyleFace *ffa = CustomData_get(&me->pdata, (int)(mpoly - me->mpoly), CD_FREESTYLE_FACE); return ffa && (ffa->flag & FREESTYLE_FACE_MARK) != 0; } static void rna_MPoly_freestyle_face_mark_set(PointerRNA *ptr, int value) { Mesh *me = rna_mesh(ptr); MPoly *mpoly = (MPoly *)ptr->data; FreestyleFace *ffa = CustomData_get(&me->pdata, (int)(mpoly - me->mpoly), CD_FREESTYLE_FACE); if (!ffa) { ffa = CustomData_add_layer(&me->pdata, CD_FREESTYLE_FACE, CD_CALLOC, NULL, me->totpoly); } if (value) { ffa->flag |= FREESTYLE_FACE_MARK; } else { ffa->flag &= ~FREESTYLE_FACE_MARK; } } /* Generic UV rename! */ static void rna_MeshUVLayer_name_set(PointerRNA *ptr, const char *name) { char buf[MAX_CUSTOMDATA_LAYER_NAME]; BLI_strncpy_utf8(buf, name, MAX_CUSTOMDATA_LAYER_NAME); BKE_mesh_uv_cdlayer_rename(rna_mesh(ptr), ((CustomDataLayer *)ptr->data)->name, buf, true); } /* uv_layers */ DEFINE_CUSTOMDATA_LAYER_COLLECTION(uv_layer, ldata, CD_MLOOPUV) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM(uv_layer, ldata, CD_MLOOPUV, active, MeshUVLoopLayer) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM(uv_layer, ldata, CD_MLOOPUV, clone, MeshUVLoopLayer) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM( uv_layer, ldata, CD_MLOOPUV, stencil, MeshUVLoopLayer) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM(uv_layer, ldata, CD_MLOOPUV, render, MeshUVLoopLayer) /* MeshUVLoopLayer */ static char *rna_MeshUVLoopLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("uv_layers[\"%s\"]", name_esc); } static void rna_MeshUVLoopLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin( iter, layer->data, sizeof(MLoopUV), (me->edit_mesh) ? 0 : me->totloop, 0, NULL); } static int rna_MeshUVLoopLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return (me->edit_mesh) ? 0 : me->totloop; } static bool rna_MeshUVLoopLayer_active_render_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPUV, 1); } static bool rna_MeshUVLoopLayer_active_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPUV, 0); } static bool rna_MeshUVLoopLayer_clone_get(PointerRNA *ptr) { return rna_CustomDataLayer_clone_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPUV); } static void rna_MeshUVLoopLayer_active_render_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPUV, 1); } static void rna_MeshUVLoopLayer_active_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPUV, 0); } static void rna_MeshUVLoopLayer_clone_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_clone_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPUV); } /* vertex_color_layers */ DEFINE_CUSTOMDATA_LAYER_COLLECTION(vertex_color, ldata, CD_MLOOPCOL) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM( vertex_color, ldata, CD_MLOOPCOL, active, MeshLoopColorLayer) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM( vertex_color, ldata, CD_MLOOPCOL, render, MeshLoopColorLayer) static void rna_MeshLoopColorLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin( iter, layer->data, sizeof(MLoopCol), (me->edit_mesh) ? 0 : me->totloop, 0, NULL); } static int rna_MeshLoopColorLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return (me->edit_mesh) ? 0 : me->totloop; } static bool rna_MeshLoopColorLayer_active_render_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPCOL, 1); } static bool rna_MeshLoopColorLayer_active_get(PointerRNA *ptr) { return rna_CustomDataLayer_active_get(ptr, rna_mesh_ldata(ptr), CD_MLOOPCOL, 0); } static void rna_MeshLoopColorLayer_active_render_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPCOL, 1); } static void rna_MeshLoopColorLayer_active_set(PointerRNA *ptr, bool value) { rna_CustomDataLayer_active_set(ptr, rna_mesh_ldata(ptr), value, CD_MLOOPCOL, 0); } static int rna_float_layer_check(CollectionPropertyIterator *UNUSED(iter), void *data) { CustomDataLayer *layer = (CustomDataLayer *)data; return (layer->type != CD_PROP_FLT); } static void rna_Mesh_vertex_float_layers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { CustomData *vdata = rna_mesh_vdata(ptr); rna_iterator_array_begin(iter, (void *)vdata->layers, sizeof(CustomDataLayer), vdata->totlayer, 0, rna_float_layer_check); } static void rna_Mesh_polygon_float_layers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { CustomData *pdata = rna_mesh_pdata(ptr); rna_iterator_array_begin(iter, (void *)pdata->layers, sizeof(CustomDataLayer), pdata->totlayer, 0, rna_float_layer_check); } static int rna_Mesh_vertex_float_layers_length(PointerRNA *ptr) { return CustomData_number_of_layers(rna_mesh_vdata(ptr), CD_PROP_FLT); } static int rna_Mesh_polygon_float_layers_length(PointerRNA *ptr) { return CustomData_number_of_layers(rna_mesh_pdata(ptr), CD_PROP_FLT); } static int rna_int_layer_check(CollectionPropertyIterator *UNUSED(iter), void *data) { CustomDataLayer *layer = (CustomDataLayer *)data; return (layer->type != CD_PROP_INT); } static void rna_Mesh_vertex_int_layers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { CustomData *vdata = rna_mesh_vdata(ptr); rna_iterator_array_begin(iter, (void *)vdata->layers, sizeof(CustomDataLayer), vdata->totlayer, 0, rna_int_layer_check); } static void rna_Mesh_polygon_int_layers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { CustomData *pdata = rna_mesh_pdata(ptr); rna_iterator_array_begin(iter, (void *)pdata->layers, sizeof(CustomDataLayer), pdata->totlayer, 0, rna_int_layer_check); } static int rna_Mesh_vertex_int_layers_length(PointerRNA *ptr) { return CustomData_number_of_layers(rna_mesh_vdata(ptr), CD_PROP_INT); } static int rna_Mesh_polygon_int_layers_length(PointerRNA *ptr) { return CustomData_number_of_layers(rna_mesh_pdata(ptr), CD_PROP_INT); } static int rna_string_layer_check(CollectionPropertyIterator *UNUSED(iter), void *data) { CustomDataLayer *layer = (CustomDataLayer *)data; return (layer->type != CD_PROP_STR); } static void rna_Mesh_vertex_string_layers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { CustomData *vdata = rna_mesh_vdata(ptr); rna_iterator_array_begin(iter, (void *)vdata->layers, sizeof(CustomDataLayer), vdata->totlayer, 0, rna_string_layer_check); } static void rna_Mesh_polygon_string_layers_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { CustomData *pdata = rna_mesh_pdata(ptr); rna_iterator_array_begin(iter, (void *)pdata->layers, sizeof(CustomDataLayer), pdata->totlayer, 0, rna_string_layer_check); } static int rna_Mesh_vertex_string_layers_length(PointerRNA *ptr) { return CustomData_number_of_layers(rna_mesh_vdata(ptr), CD_PROP_STR); } static int rna_Mesh_polygon_string_layers_length(PointerRNA *ptr) { return CustomData_number_of_layers(rna_mesh_pdata(ptr), CD_PROP_STR); } /* Skin vertices */ DEFINE_CUSTOMDATA_LAYER_COLLECTION(skin_vertice, vdata, CD_MVERT_SKIN) static char *rna_MeshSkinVertexLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("skin_vertices[\"%s\"]", name_esc); } static char *rna_VertCustomData_data_path(PointerRNA *ptr, const char *collection, int type); static char *rna_MeshSkinVertex_path(PointerRNA *ptr) { return rna_VertCustomData_data_path(ptr, "skin_vertices", CD_MVERT_SKIN); } static void rna_MeshSkinVertexLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MVertSkin), me->totvert, 0, NULL); } static int rna_MeshSkinVertexLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totvert; } /* End skin vertices */ /* Paint mask */ DEFINE_CUSTOMDATA_LAYER_COLLECTION(vertex_paint_mask, vdata, CD_PAINT_MASK) static char *rna_MeshPaintMaskLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("vertex_paint_masks[\"%s\"]", name_esc); } static char *rna_MeshPaintMask_path(PointerRNA *ptr) { return rna_VertCustomData_data_path(ptr, "vertex_paint_masks", CD_PAINT_MASK); } static void rna_MeshPaintMaskLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MFloatProperty), me->totvert, 0, NULL); } static int rna_MeshPaintMaskLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totvert; } /* End paint mask */ /* Face maps */ DEFINE_CUSTOMDATA_LAYER_COLLECTION(face_map, pdata, CD_FACEMAP) DEFINE_CUSTOMDATA_LAYER_COLLECTION_ACTIVEITEM( face_map, pdata, CD_FACEMAP, active, MeshFaceMapLayer) static char *rna_MeshFaceMapLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("face_maps[\"%s\"]", name_esc); } static void rna_MeshFaceMapLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(int), me->totpoly, 0, NULL); } static int rna_MeshFaceMapLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totpoly; } static PointerRNA rna_Mesh_face_map_new(struct Mesh *me, ReportList *reports, const char *name) { if (BKE_mesh_ensure_facemap_customdata(me) == false) { BKE_report(reports, RPT_ERROR, "Currently only single face-map layers are supported"); return PointerRNA_NULL; } CustomData *pdata = rna_mesh_pdata_helper(me); int index = CustomData_get_layer_index(pdata, CD_FACEMAP); BLI_assert(index != -1); CustomDataLayer *cdl = &pdata->layers[index]; rna_cd_layer_name_set(pdata, cdl, name); PointerRNA ptr; RNA_pointer_create(&me->id, &RNA_MeshFaceMapLayer, cdl, &ptr); return ptr; } static void rna_Mesh_face_map_remove(struct Mesh *me, ReportList *reports, struct CustomDataLayer *layer) { /* just for sanity check */ { CustomData *pdata = rna_mesh_pdata_helper(me); int index = CustomData_get_layer_index(pdata, CD_FACEMAP); if (index != -1) { CustomDataLayer *layer_test = &pdata->layers[index]; if (layer != layer_test) { /* don't show name, its likely freed memory */ BKE_report(reports, RPT_ERROR, "FaceMap not in mesh"); return; } } } if (BKE_mesh_clear_facemap_customdata(me) == false) { BKE_report(reports, RPT_ERROR, "Error removing face-map"); } } /* End face maps */ /* poly.vertices - this is faked loop access for convenience */ static int rna_MeshPoly_vertices_get_length(PointerRNA *ptr, int length[RNA_MAX_ARRAY_DIMENSION]) { MPoly *mp = (MPoly *)ptr->data; /* note, raw access uses dummy item, this _could_ crash, watch out for this, mface uses it but it cant work here */ return (length[0] = mp->totloop); } static void rna_MeshPoly_vertices_get(PointerRNA *ptr, int *values) { Mesh *me = rna_mesh(ptr); MPoly *mp = (MPoly *)ptr->data; MLoop *ml = &me->mloop[mp->loopstart]; unsigned int i; for (i = mp->totloop; i > 0; i--, values++, ml++) { *values = ml->v; } } static void rna_MeshPoly_vertices_set(PointerRNA *ptr, const int *values) { Mesh *me = rna_mesh(ptr); MPoly *mp = (MPoly *)ptr->data; MLoop *ml = &me->mloop[mp->loopstart]; unsigned int i; for (i = mp->totloop; i > 0; i--, values++, ml++) { ml->v = *values; } } /* disabling, some importers don't know the total material count when assigning materials */ # if 0 static void rna_MeshPoly_material_index_range( PointerRNA *ptr, int *min, int *max, int *softmin, int *softmax) { Mesh *me = rna_mesh(ptr); *min = 0; *max = max_ii(0, me->totcol - 1); } # endif static int rna_MeshVertex_index_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MVert *vert = (MVert *)ptr->data; return (int)(vert - me->mvert); } static int rna_MeshEdge_index_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MEdge *edge = (MEdge *)ptr->data; return (int)(edge - me->medge); } static int rna_MeshLoopTriangle_index_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MLoopTri *ltri = (MLoopTri *)ptr->data; return (int)(ltri - me->runtime.looptris.array); } static int rna_MeshLoopTriangle_material_index_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MLoopTri *ltri = (MLoopTri *)ptr->data; return me->mpoly[ltri->poly].mat_nr; } static bool rna_MeshLoopTriangle_use_smooth_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MLoopTri *ltri = (MLoopTri *)ptr->data; return me->mpoly[ltri->poly].flag & ME_SMOOTH; } static int rna_MeshPolygon_index_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MPoly *mpoly = (MPoly *)ptr->data; return (int)(mpoly - me->mpoly); } static int rna_MeshLoop_index_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); MLoop *mloop = (MLoop *)ptr->data; return (int)(mloop - me->mloop); } /* path construction */ static char *rna_VertexGroupElement_path(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); /* XXX not always! */ MDeformWeight *dw = (MDeformWeight *)ptr->data; MDeformVert *dvert; int a, b; for (a = 0, dvert = me->dvert; a < me->totvert; a++, dvert++) for (b = 0; b < dvert->totweight; b++) if (dw == &dvert->dw[b]) return BLI_sprintfN("vertices[%d].groups[%d]", a, b); return NULL; } static char *rna_MeshPolygon_path(PointerRNA *ptr) { return BLI_sprintfN("polygons[%d]", (int)((MPoly *)ptr->data - rna_mesh(ptr)->mpoly)); } static char *rna_MeshLoopTriangle_path(PointerRNA *ptr) { return BLI_sprintfN("loop_triangles[%d]", (int)((MLoopTri *)ptr->data - rna_mesh(ptr)->runtime.looptris.array)); } static char *rna_MeshEdge_path(PointerRNA *ptr) { return BLI_sprintfN("edges[%d]", (int)((MEdge *)ptr->data - rna_mesh(ptr)->medge)); } static char *rna_MeshLoop_path(PointerRNA *ptr) { return BLI_sprintfN("loops[%d]", (int)((MLoop *)ptr->data - rna_mesh(ptr)->mloop)); } static char *rna_MeshVertex_path(PointerRNA *ptr) { return BLI_sprintfN("vertices[%d]", (int)((MVert *)ptr->data - rna_mesh(ptr)->mvert)); } static char *rna_VertCustomData_data_path(PointerRNA *ptr, const char *collection, int type) { CustomDataLayer *cdl; Mesh *me = rna_mesh(ptr); CustomData *vdata = rna_mesh_vdata(ptr); int a, b, totvert = (me->edit_mesh) ? 0 : me->totvert; for (cdl = vdata->layers, a = 0; a < vdata->totlayer; cdl++, a++) { if (cdl->type == type) { b = ((char *)ptr->data - ((char *)cdl->data)) / CustomData_sizeof(type); if (b >= 0 && b < totvert) { char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("%s[\"%s\"].data[%d]", collection, name_esc, b); } } } return NULL; } static char *rna_PolyCustomData_data_path(PointerRNA *ptr, const char *collection, int type) { CustomDataLayer *cdl; Mesh *me = rna_mesh(ptr); CustomData *pdata = rna_mesh_pdata(ptr); int a, b, totpoly = (me->edit_mesh) ? 0 : me->totpoly; for (cdl = pdata->layers, a = 0; a < pdata->totlayer; cdl++, a++) { if (cdl->type == type) { b = ((char *)ptr->data - ((char *)cdl->data)) / CustomData_sizeof(type); if (b >= 0 && b < totpoly) { char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("%s[\"%s\"].data[%d]", collection, name_esc, b); } } } return NULL; } static char *rna_LoopCustomData_data_path(PointerRNA *ptr, const char *collection, int type) { CustomDataLayer *cdl; Mesh *me = rna_mesh(ptr); CustomData *ldata = rna_mesh_ldata(ptr); int a, b, totloop = (me->edit_mesh) ? 0 : me->totloop; for (cdl = ldata->layers, a = 0; a < ldata->totlayer; cdl++, a++) { if (cdl->type == type) { b = ((char *)ptr->data - ((char *)cdl->data)) / CustomData_sizeof(type); if (b >= 0 && b < totloop) { char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("%s[\"%s\"].data[%d]", collection, name_esc, b); } } } return NULL; } static char *rna_MeshUVLoop_path(PointerRNA *ptr) { return rna_LoopCustomData_data_path(ptr, "uv_layers", CD_MLOOPUV); } static char *rna_MeshLoopColorLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("vertex_colors[\"%s\"]", name_esc); } static char *rna_MeshColor_path(PointerRNA *ptr) { return rna_LoopCustomData_data_path(ptr, "vertex_colors", CD_MLOOPCOL); } /**** Float Property Layer API ****/ static char *rna_MeshVertexFloatPropertyLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("vertex_float_layers[\"%s\"]", name_esc); } static char *rna_MeshPolygonFloatPropertyLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("polygon_float_layers[\"%s\"]", name_esc); } static char *rna_MeshVertexFloatProperty_path(PointerRNA *ptr) { return rna_VertCustomData_data_path(ptr, "vertex_layers_float", CD_PROP_FLT); } static char *rna_MeshPolygonFloatProperty_path(PointerRNA *ptr) { return rna_PolyCustomData_data_path(ptr, "polygon_layers_float", CD_PROP_FLT); } static void rna_MeshVertexFloatPropertyLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MFloatProperty), me->totvert, 0, NULL); } static void rna_MeshPolygonFloatPropertyLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MFloatProperty), me->totpoly, 0, NULL); } static int rna_MeshVertexFloatPropertyLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totvert; } static int rna_MeshPolygonFloatPropertyLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totpoly; } /**** Int Property Layer API ****/ static char *rna_MeshVertexIntPropertyLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("vertex_int_layers[\"%s\"]", name_esc); } static char *rna_MeshPolygonIntPropertyLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("polygon_int_layers[\"%s\"]", name_esc); } static char *rna_MeshVertexIntProperty_path(PointerRNA *ptr) { return rna_VertCustomData_data_path(ptr, "vertex_layers_int", CD_PROP_INT); } static char *rna_MeshPolygonIntProperty_path(PointerRNA *ptr) { return rna_PolyCustomData_data_path(ptr, "polygon_layers_int", CD_PROP_INT); } static void rna_MeshVertexIntPropertyLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MIntProperty), me->totvert, 0, NULL); } static void rna_MeshPolygonIntPropertyLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MIntProperty), me->totpoly, 0, NULL); } static int rna_MeshVertexIntPropertyLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totvert; } static int rna_MeshPolygonIntPropertyLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totpoly; } /**** String Property Layer API ****/ static char *rna_MeshVertexStringPropertyLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("vertex_string_layers[\"%s\"]", name_esc); } static char *rna_MeshPolygonStringPropertyLayer_path(PointerRNA *ptr) { CustomDataLayer *cdl = ptr->data; char name_esc[sizeof(cdl->name) * 2]; BLI_strescape(name_esc, cdl->name, sizeof(name_esc)); return BLI_sprintfN("polygon_string_layers[\"%s\"]", name_esc); } static char *rna_MeshVertexStringProperty_path(PointerRNA *ptr) { return rna_VertCustomData_data_path(ptr, "vertex_layers_string", CD_PROP_STR); } static char *rna_MeshPolygonStringProperty_path(PointerRNA *ptr) { return rna_PolyCustomData_data_path(ptr, "polygon_layers_string", CD_PROP_STR); } static void rna_MeshVertexStringPropertyLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MStringProperty), me->totvert, 0, NULL); } static void rna_MeshPolygonStringPropertyLayer_data_begin(CollectionPropertyIterator *iter, PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); CustomDataLayer *layer = (CustomDataLayer *)ptr->data; rna_iterator_array_begin(iter, layer->data, sizeof(MStringProperty), me->totpoly, 0, NULL); } static int rna_MeshVertexStringPropertyLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totvert; } static int rna_MeshPolygonStringPropertyLayer_data_length(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->totpoly; } /* XXX, we dont have proper byte string support yet, so for now use the (bytes + 1) * bmesh API exposes correct python/bytestring access */ void rna_MeshStringProperty_s_get(PointerRNA *ptr, char *value) { MStringProperty *ms = (MStringProperty *)ptr->data; BLI_strncpy(value, ms->s, (int)ms->s_len + 1); } int rna_MeshStringProperty_s_length(PointerRNA *ptr) { MStringProperty *ms = (MStringProperty *)ptr->data; return (int)ms->s_len + 1; } void rna_MeshStringProperty_s_set(PointerRNA *ptr, const char *value) { MStringProperty *ms = (MStringProperty *)ptr->data; BLI_strncpy(ms->s, value, sizeof(ms->s)); } static char *rna_MeshFaceMap_path(PointerRNA *ptr) { return rna_PolyCustomData_data_path(ptr, "face_maps", CD_FACEMAP); } /***************************************/ static int rna_Mesh_tot_vert_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->edit_mesh ? me->edit_mesh->bm->totvertsel : 0; } static int rna_Mesh_tot_edge_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->edit_mesh ? me->edit_mesh->bm->totedgesel : 0; } static int rna_Mesh_tot_face_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return me->edit_mesh ? me->edit_mesh->bm->totfacesel : 0; } static PointerRNA rna_Mesh_vertex_color_new(struct Mesh *me, const char *name, const bool do_init) { PointerRNA ptr; CustomData *ldata; CustomDataLayer *cdl = NULL; int index = ED_mesh_color_add(me, name, false, do_init); if (index != -1) { ldata = rna_mesh_ldata_helper(me); cdl = &ldata->layers[CustomData_get_layer_index_n(ldata, CD_MLOOPCOL, index)]; } RNA_pointer_create(&me->id, &RNA_MeshLoopColorLayer, cdl, &ptr); return ptr; } static void rna_Mesh_vertex_color_remove(struct Mesh *me, ReportList *reports, CustomDataLayer *layer) { if (ED_mesh_color_remove_named(me, layer->name) == false) { BKE_reportf(reports, RPT_ERROR, "Vertex color '%s' not found", layer->name); } } # define DEFINE_CUSTOMDATA_PROPERTY_API( \ elemname, datatype, cd_prop_type, cdata, countvar, layertype) \ static PointerRNA rna_Mesh_##elemname##_##datatype##_property_new(struct Mesh *me, \ const char *name) \ { \ PointerRNA ptr; \ CustomDataLayer *cdl = NULL; \ int index; \ \ CustomData_add_layer_named(&me->cdata, cd_prop_type, CD_DEFAULT, NULL, me->countvar, name); \ index = CustomData_get_named_layer_index(&me->cdata, cd_prop_type, name); \ \ cdl = (index == -1) ? NULL : &(me->cdata.layers[index]); \ \ RNA_pointer_create(&me->id, &RNA_##layertype, cdl, &ptr); \ return ptr; \ } DEFINE_CUSTOMDATA_PROPERTY_API( vertex, float, CD_PROP_FLT, vdata, totvert, MeshVertexFloatPropertyLayer) DEFINE_CUSTOMDATA_PROPERTY_API( vertex, int, CD_PROP_INT, vdata, totvert, MeshVertexIntPropertyLayer) DEFINE_CUSTOMDATA_PROPERTY_API( vertex, string, CD_PROP_STR, vdata, totvert, MeshVertexStringPropertyLayer) DEFINE_CUSTOMDATA_PROPERTY_API( polygon, float, CD_PROP_FLT, pdata, totpoly, MeshPolygonFloatPropertyLayer) DEFINE_CUSTOMDATA_PROPERTY_API( polygon, int, CD_PROP_INT, pdata, totpoly, MeshPolygonIntPropertyLayer) DEFINE_CUSTOMDATA_PROPERTY_API( polygon, string, CD_PROP_STR, pdata, totpoly, MeshPolygonStringPropertyLayer) # undef DEFINE_CUSTOMDATA_PROPERTY_API static PointerRNA rna_Mesh_uv_layers_new(struct Mesh *me, const char *name, const bool do_init) { PointerRNA ptr; CustomData *ldata; CustomDataLayer *cdl = NULL; int index = ED_mesh_uv_texture_add(me, name, false, do_init); if (index != -1) { ldata = rna_mesh_ldata_helper(me); cdl = &ldata->layers[CustomData_get_layer_index_n(ldata, CD_MLOOPUV, index)]; } RNA_pointer_create(&me->id, &RNA_MeshUVLoopLayer, cdl, &ptr); return ptr; } static void rna_Mesh_uv_layers_remove(struct Mesh *me, ReportList *reports, CustomDataLayer *layer) { if (ED_mesh_uv_texture_remove_named(me, layer->name) == false) { BKE_reportf(reports, RPT_ERROR, "Texture layer '%s' not found", layer->name); } } static bool rna_Mesh_is_editmode_get(PointerRNA *ptr) { Mesh *me = rna_mesh(ptr); return (me->edit_mesh != NULL); } /* only to quiet warnings */ static void UNUSED_FUNCTION(rna_mesh_unused)(void) { /* unused functions made by macros */ (void)rna_Mesh_skin_vertice_index_range; (void)rna_Mesh_vertex_paint_mask_index_range; (void)rna_Mesh_uv_layer_render_get; (void)rna_Mesh_uv_layer_render_index_get; (void)rna_Mesh_uv_layer_render_index_set; (void)rna_Mesh_uv_layer_render_set; (void)rna_Mesh_vertex_color_render_get; (void)rna_Mesh_vertex_color_render_index_get; (void)rna_Mesh_vertex_color_render_index_set; (void)rna_Mesh_vertex_color_render_set; (void)rna_Mesh_face_map_index_range; (void)rna_Mesh_face_map_active_index_set; (void)rna_Mesh_face_map_active_index_get; (void)rna_Mesh_face_map_active_set; /* end unused function block */ } #else static void rna_def_mvert_group(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "VertexGroupElement", NULL); RNA_def_struct_sdna(srna, "MDeformWeight"); RNA_def_struct_path_func(srna, "rna_VertexGroupElement_path"); RNA_def_struct_ui_text( srna, "Vertex Group Element", "Weight value of a vertex in a vertex group"); RNA_def_struct_ui_icon(srna, ICON_GROUP_VERTEX); /* we can't point to actual group, it is in the object and so * there is no unique group to point to, hence the index */ prop = RNA_def_property(srna, "group", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "def_nr"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Group Index", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "weight", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Weight", "Vertex Weight"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data_edit_weight"); } static void rna_def_mvert(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshVertex", NULL); RNA_def_struct_sdna(srna, "MVert"); RNA_def_struct_ui_text(srna, "Mesh Vertex", "Vertex in a Mesh data-block"); RNA_def_struct_path_func(srna, "rna_MeshVertex_path"); RNA_def_struct_ui_icon(srna, ICON_VERTEXSEL); prop = RNA_def_property(srna, "co", PROP_FLOAT, PROP_TRANSLATION); RNA_def_property_ui_text(prop, "Location", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "normal", PROP_FLOAT, PROP_DIRECTION); /* RNA_def_property_float_sdna(prop, NULL, "no"); */ RNA_def_property_array(prop, 3); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_float_funcs( prop, "rna_MeshVertex_normal_get", "rna_MeshVertex_normal_set", NULL); RNA_def_property_ui_text(prop, "Normal", "Vertex Normal"); prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", SELECT); RNA_def_property_ui_text(prop, "Select", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "hide", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_HIDE); RNA_def_property_ui_text(prop, "Hide", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "bevel_weight", PROP_FLOAT, PROP_NONE); RNA_def_property_float_funcs( prop, "rna_MeshVertex_bevel_weight_get", "rna_MeshVertex_bevel_weight_set", NULL); RNA_def_property_ui_text( prop, "Bevel Weight", "Weight used by the Bevel modifier 'Only Vertices' option"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "groups", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_funcs(prop, "rna_MeshVertex_groups_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", NULL, NULL, NULL, NULL); RNA_def_property_struct_type(prop, "VertexGroupElement"); RNA_def_property_ui_text( prop, "Groups", "Weights for the vertex groups this vertex is member of"); prop = RNA_def_property(srna, "index", PROP_INT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_int_funcs(prop, "rna_MeshVertex_index_get", NULL, NULL); RNA_def_property_ui_text(prop, "Index", "Index of this vertex"); prop = RNA_def_property(srna, "undeformed_co", PROP_FLOAT, PROP_TRANSLATION); RNA_def_property_array(prop, 3); RNA_def_property_ui_text( prop, "Undeformed Location", "For meshes with modifiers applied, the coordinate of the vertex with no deforming " "modifiers applied, as used for generated texture coordinates"); RNA_def_property_float_funcs(prop, "rna_MeshVertex_undeformed_co_get", NULL, NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); } static void rna_def_medge(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshEdge", NULL); RNA_def_struct_sdna(srna, "MEdge"); RNA_def_struct_ui_text(srna, "Mesh Edge", "Edge in a Mesh data-block"); RNA_def_struct_path_func(srna, "rna_MeshEdge_path"); RNA_def_struct_ui_icon(srna, ICON_EDGESEL); prop = RNA_def_property(srna, "vertices", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "v1"); RNA_def_property_array(prop, 2); RNA_def_property_ui_text(prop, "Vertices", "Vertex indices"); /* XXX allows creating invalid meshes */ prop = RNA_def_property(srna, "crease", PROP_FLOAT, PROP_NONE); RNA_def_property_float_funcs(prop, "rna_MEdge_crease_get", "rna_MEdge_crease_set", NULL); RNA_def_property_ui_text( prop, "Crease", "Weight used by the Subdivision Surface modifier for creasing"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "bevel_weight", PROP_FLOAT, PROP_NONE); RNA_def_property_float_funcs( prop, "rna_MEdge_bevel_weight_get", "rna_MEdge_bevel_weight_set", NULL); RNA_def_property_ui_text(prop, "Bevel Weight", "Weight used by the Bevel modifier"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", SELECT); RNA_def_property_ui_text(prop, "Select", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "hide", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_HIDE); RNA_def_property_ui_text(prop, "Hide", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "use_seam", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_SEAM); RNA_def_property_ui_text(prop, "Seam", "Seam edge for UV unwrapping"); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "use_edge_sharp", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_SHARP); RNA_def_property_ui_text(prop, "Sharp", "Sharp edge for the Edge Split modifier"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "is_loose", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_LOOSEEDGE); RNA_def_property_ui_text(prop, "Loose", "Loose edge"); prop = RNA_def_property(srna, "use_freestyle_mark", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs( prop, "rna_MEdge_freestyle_edge_mark_get", "rna_MEdge_freestyle_edge_mark_set"); RNA_def_property_ui_text(prop, "Freestyle Edge Mark", "Edge mark for Freestyle line rendering"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "index", PROP_INT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_int_funcs(prop, "rna_MeshEdge_index_get", NULL, NULL); RNA_def_property_ui_text(prop, "Index", "Index of this edge"); } static void rna_def_mlooptri(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; const int splitnor_dim[] = {3, 3}; srna = RNA_def_struct(brna, "MeshLoopTriangle", NULL); RNA_def_struct_sdna(srna, "MLoopTri"); RNA_def_struct_ui_text(srna, "Mesh Loop Triangle", "Tessellated triangle in a Mesh data-block"); RNA_def_struct_path_func(srna, "rna_MeshLoopTriangle_path"); RNA_def_struct_ui_icon(srna, ICON_FACESEL); prop = RNA_def_property(srna, "vertices", PROP_INT, PROP_UNSIGNED); RNA_def_property_array(prop, 3); RNA_def_property_int_funcs(prop, "rna_MeshLoopTriangle_verts_get", NULL, NULL); RNA_def_property_ui_text(prop, "Vertices", "Indices of triangle vertices"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "loops", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "tri"); RNA_def_property_ui_text(prop, "Loops", "Indices of mesh loops that make up the triangle"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "polygon_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "poly"); RNA_def_property_ui_text( prop, "Polygon", "Index of mesh polygon that the triangle is a part of"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "normal", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_array(prop, 3); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshLoopTriangle_normal_get", NULL, NULL); RNA_def_property_ui_text( prop, "Triangle Normal", "Local space unit length normal vector for this triangle"); prop = RNA_def_property(srna, "split_normals", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_multi_array(prop, 2, splitnor_dim); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshLoopTriangle_split_normals_get", NULL, NULL); RNA_def_property_ui_text( prop, "Split Normals", "Local space unit length split normals vectors of the vertices of this triangle " "(must be computed beforehand using calc_normals_split or calc_tangents)"); prop = RNA_def_property(srna, "area", PROP_FLOAT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshLoopTriangle_area_get", NULL, NULL); RNA_def_property_ui_text(prop, "Triangle Area", "Area of this triangle"); prop = RNA_def_property(srna, "index", PROP_INT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_int_funcs(prop, "rna_MeshLoopTriangle_index_get", NULL, NULL); RNA_def_property_ui_text(prop, "Index", "Index of this loop triangle"); prop = RNA_def_property(srna, "material_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_int_funcs(prop, "rna_MeshLoopTriangle_material_index_get", NULL, NULL); RNA_def_property_ui_text(prop, "Material Index", ""); prop = RNA_def_property(srna, "use_smooth", PROP_BOOLEAN, PROP_NONE); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_boolean_funcs(prop, "rna_MeshLoopTriangle_use_smooth_get", NULL); RNA_def_property_ui_text(prop, "Smooth", ""); } static void rna_def_mloop(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshLoop", NULL); RNA_def_struct_sdna(srna, "MLoop"); RNA_def_struct_ui_text(srna, "Mesh Loop", "Loop in a Mesh data-block"); RNA_def_struct_path_func(srna, "rna_MeshLoop_path"); RNA_def_struct_ui_icon(srna, ICON_EDGESEL); prop = RNA_def_property(srna, "vertex_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "v"); RNA_def_property_ui_text(prop, "Vertex", "Vertex index"); prop = RNA_def_property(srna, "edge_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "e"); RNA_def_property_ui_text(prop, "Edge", "Edge index"); prop = RNA_def_property(srna, "index", PROP_INT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_int_funcs(prop, "rna_MeshLoop_index_get", NULL, NULL); RNA_def_property_ui_text(prop, "Index", "Index of this loop"); prop = RNA_def_property(srna, "normal", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_array(prop, 3); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_float_funcs(prop, "rna_MeshLoop_normal_get", "rna_MeshLoop_normal_set", NULL); RNA_def_property_ui_text( prop, "Normal", "Local space unit length split normal vector of this vertex for this polygon " "(must be computed beforehand using calc_normals_split or calc_tangents)"); prop = RNA_def_property(srna, "tangent", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_array(prop, 3); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshLoop_tangent_get", NULL, NULL); RNA_def_property_ui_text( prop, "Tangent", "Local space unit length tangent vector of this vertex for this polygon " "(must be computed beforehand using calc_tangents)"); prop = RNA_def_property(srna, "bitangent_sign", PROP_FLOAT, PROP_NONE); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshLoop_bitangent_sign_get", NULL, NULL); RNA_def_property_ui_text( prop, "Bitangent Sign", "Sign of the bitangent vector of this vertex for this polygon (must be computed " "beforehand using calc_tangents, bitangent = bitangent_sign * cross(normal, tangent))"); prop = RNA_def_property(srna, "bitangent", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_array(prop, 3); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshLoop_bitangent_get", NULL, NULL); RNA_def_property_ui_text( prop, "Bitangent", "Bitangent vector of this vertex for this polygon (must be computed beforehand using " "calc_tangents, *use it only if really needed*, slower access than bitangent_sign)"); } static void rna_def_mpolygon(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; FunctionRNA *func; srna = RNA_def_struct(brna, "MeshPolygon", NULL); RNA_def_struct_sdna(srna, "MPoly"); RNA_def_struct_ui_text(srna, "Mesh Polygon", "Polygon in a Mesh data-block"); RNA_def_struct_path_func(srna, "rna_MeshPolygon_path"); RNA_def_struct_ui_icon(srna, ICON_FACESEL); /* Faked, actually access to loop vertex values, don't this way because manually setting up * vertex/edge per loop is very low level. * Instead we setup poly sizes, assign indices, then calc edges automatic when creating * meshes from rna/py. */ prop = RNA_def_property(srna, "vertices", PROP_INT, PROP_UNSIGNED); /* Eek, this is still used in some cases but in fact we don't want to use it at all here. */ RNA_def_property_array(prop, 3); RNA_def_property_flag(prop, PROP_DYNAMIC); RNA_def_property_dynamic_array_funcs(prop, "rna_MeshPoly_vertices_get_length"); RNA_def_property_int_funcs(prop, "rna_MeshPoly_vertices_get", "rna_MeshPoly_vertices_set", NULL); RNA_def_property_ui_text(prop, "Vertices", "Vertex indices"); /* these are both very low level access */ prop = RNA_def_property(srna, "loop_start", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "loopstart"); RNA_def_property_ui_text(prop, "Loop Start", "Index of the first loop of this polygon"); /* also low level */ prop = RNA_def_property(srna, "loop_total", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "totloop"); RNA_def_property_ui_text(prop, "Loop Total", "Number of loops used by this polygon"); prop = RNA_def_property(srna, "material_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_sdna(prop, NULL, "mat_nr"); RNA_def_property_ui_text(prop, "Material Index", ""); # if 0 RNA_def_property_int_funcs(prop, NULL, NULL, "rna_MeshPoly_material_index_range"); # endif RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_FACE_SEL); RNA_def_property_ui_text(prop, "Select", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "hide", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_HIDE); RNA_def_property_ui_text(prop, "Hide", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_select"); prop = RNA_def_property(srna, "use_smooth", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_SMOOTH); RNA_def_property_ui_text(prop, "Smooth", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "use_freestyle_mark", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs( prop, "rna_MPoly_freestyle_face_mark_get", "rna_MPoly_freestyle_face_mark_set"); RNA_def_property_ui_text(prop, "Freestyle Face Mark", "Face mark for Freestyle line rendering"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "normal", PROP_FLOAT, PROP_DIRECTION); RNA_def_property_array(prop, 3); RNA_def_property_range(prop, -1.0f, 1.0f); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshPolygon_normal_get", NULL, NULL); RNA_def_property_ui_text( prop, "Polygon Normal", "Local space unit length normal vector for this polygon"); prop = RNA_def_property(srna, "center", PROP_FLOAT, PROP_XYZ); RNA_def_property_array(prop, 3); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshPolygon_center_get", NULL, NULL); RNA_def_property_ui_text(prop, "Polygon Center", "Center of this polygon"); prop = RNA_def_property(srna, "area", PROP_FLOAT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_float_funcs(prop, "rna_MeshPolygon_area_get", NULL, NULL); RNA_def_property_ui_text(prop, "Polygon Area", "Read only area of this polygon"); prop = RNA_def_property(srna, "index", PROP_INT, PROP_UNSIGNED); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_int_funcs(prop, "rna_MeshPolygon_index_get", NULL, NULL); RNA_def_property_ui_text(prop, "Index", "Index of this polygon"); func = RNA_def_function(srna, "flip", "rna_MeshPolygon_flip"); RNA_def_function_flag(func, FUNC_USE_SELF_ID); RNA_def_function_ui_description(func, "Invert winding of this polygon (flip its normal)"); } /* mesh.loop_uvs */ static void rna_def_mloopuv(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshUVLoopLayer", NULL); RNA_def_struct_sdna(srna, "CustomDataLayer"); RNA_def_struct_path_func(srna, "rna_MeshUVLoopLayer_path"); prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "MeshUVLoop"); RNA_def_property_collection_funcs(prop, "rna_MeshUVLoopLayer_data_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", "rna_MeshUVLoopLayer_data_length", NULL, NULL, NULL); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_struct_name_property(srna, prop); RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshUVLayer_name_set"); RNA_def_property_ui_text(prop, "Name", "Name of UV map"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "active", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs( prop, "rna_MeshUVLoopLayer_active_get", "rna_MeshUVLoopLayer_active_set"); RNA_def_property_ui_text(prop, "Active", "Set the map as active for display and editing"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "active_render", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "active_rnd", 0); RNA_def_property_boolean_funcs( prop, "rna_MeshUVLoopLayer_active_render_get", "rna_MeshUVLoopLayer_active_render_set"); RNA_def_property_ui_text(prop, "Active Render", "Set the map as active for rendering"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "active_clone", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "active_clone", 0); RNA_def_property_boolean_funcs( prop, "rna_MeshUVLoopLayer_clone_get", "rna_MeshUVLoopLayer_clone_set"); RNA_def_property_ui_text(prop, "Active Clone", "Set the map as active for cloning"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); srna = RNA_def_struct(brna, "MeshUVLoop", NULL); RNA_def_struct_sdna(srna, "MLoopUV"); RNA_def_struct_path_func(srna, "rna_MeshUVLoop_path"); prop = RNA_def_property(srna, "uv", PROP_FLOAT, PROP_XYZ); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "pin_uv", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MLOOPUV_PINNED); RNA_def_property_ui_text(prop, "UV Pinned", ""); prop = RNA_def_property(srna, "select", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MLOOPUV_VERTSEL); RNA_def_property_ui_text(prop, "UV Select", ""); prop = RNA_def_property(srna, "select_edge", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MLOOPUV_EDGESEL); RNA_def_property_ui_text(prop, "UV Edge Select", ""); } static void rna_def_mloopcol(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshLoopColorLayer", NULL); RNA_def_struct_ui_text( srna, "Mesh Vertex Color Layer", "Layer of vertex colors in a Mesh data-block"); RNA_def_struct_sdna(srna, "CustomDataLayer"); RNA_def_struct_path_func(srna, "rna_MeshLoopColorLayer_path"); RNA_def_struct_ui_icon(srna, ICON_GROUP_VCOL); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_struct_name_property(srna, prop); RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshLoopLayer_name_set"); RNA_def_property_ui_text(prop, "Name", "Name of Vertex color layer"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "active", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs( prop, "rna_MeshLoopColorLayer_active_get", "rna_MeshLoopColorLayer_active_set"); RNA_def_property_ui_text(prop, "Active", "Sets the layer as active for display and editing"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "active_render", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "active_rnd", 0); RNA_def_property_boolean_funcs(prop, "rna_MeshLoopColorLayer_active_render_get", "rna_MeshLoopColorLayer_active_render_set"); RNA_def_property_ui_text(prop, "Active Render", "Sets the layer as active for rendering"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "MeshLoopColor"); RNA_def_property_ui_text(prop, "Data", ""); RNA_def_property_collection_funcs(prop, "rna_MeshLoopColorLayer_data_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", "rna_MeshLoopColorLayer_data_length", NULL, NULL, NULL); srna = RNA_def_struct(brna, "MeshLoopColor", NULL); RNA_def_struct_sdna(srna, "MLoopCol"); RNA_def_struct_ui_text(srna, "Mesh Vertex Color", "Vertex loop colors in a Mesh"); RNA_def_struct_path_func(srna, "rna_MeshColor_path"); prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR); RNA_def_property_array(prop, 4); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_float_funcs( prop, "rna_MeshLoopColor_color_get", "rna_MeshLoopColor_color_set", NULL); RNA_def_property_ui_text(prop, "Color", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); } static void rna_def_mproperties(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; /* Float */ # define MESH_FLOAT_PROPERTY_LAYER(elemname) \ srna = RNA_def_struct(brna, "Mesh" elemname "FloatPropertyLayer", NULL); \ RNA_def_struct_sdna(srna, "CustomDataLayer"); \ RNA_def_struct_ui_text(srna, \ "Mesh " elemname " Float Property Layer", \ "User defined layer of floating point number values"); \ RNA_def_struct_path_func(srna, "rna_Mesh" elemname "FloatPropertyLayer_path"); \ \ prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); \ RNA_def_struct_name_property(srna, prop); \ RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshAnyLayer_name_set"); \ RNA_def_property_ui_text(prop, "Name", ""); \ RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); \ \ prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); \ RNA_def_property_struct_type(prop, "Mesh" elemname "FloatProperty"); \ RNA_def_property_ui_text(prop, "Data", ""); \ RNA_def_property_collection_funcs(prop, \ "rna_Mesh" elemname "FloatPropertyLayer_data_begin", \ "rna_iterator_array_next", \ "rna_iterator_array_end", \ "rna_iterator_array_get", \ "rna_Mesh" elemname "FloatPropertyLayer_data_length", \ NULL, \ NULL, \ NULL); \ \ srna = RNA_def_struct(brna, "Mesh" elemname "FloatProperty", NULL); \ RNA_def_struct_sdna(srna, "MFloatProperty"); \ RNA_def_struct_ui_text( \ srna, \ "Mesh " elemname " Float Property", \ "User defined floating point number value in a float properties layer"); \ RNA_def_struct_path_func(srna, "rna_Mesh" elemname "FloatProperty_path"); \ \ prop = RNA_def_property(srna, "value", PROP_FLOAT, PROP_NONE); \ RNA_def_property_float_sdna(prop, NULL, "f"); \ RNA_def_property_ui_text(prop, "Value", ""); \ RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); \ ((void)0) /* Int */ # define MESH_INT_PROPERTY_LAYER(elemname) \ srna = RNA_def_struct(brna, "Mesh" elemname "IntPropertyLayer", NULL); \ RNA_def_struct_sdna(srna, "CustomDataLayer"); \ RNA_def_struct_ui_text(srna, \ "Mesh " elemname " Int Property Layer", \ "User defined layer of integer number values"); \ RNA_def_struct_path_func(srna, "rna_Mesh" elemname "IntPropertyLayer_path"); \ \ prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); \ RNA_def_struct_name_property(srna, prop); \ RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshAnyLayer_name_set"); \ RNA_def_property_ui_text(prop, "Name", ""); \ RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); \ \ prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); \ RNA_def_property_struct_type(prop, "Mesh" elemname "IntProperty"); \ RNA_def_property_ui_text(prop, "Data", ""); \ RNA_def_property_collection_funcs(prop, \ "rna_Mesh" elemname "IntPropertyLayer_data_begin", \ "rna_iterator_array_next", \ "rna_iterator_array_end", \ "rna_iterator_array_get", \ "rna_Mesh" elemname "IntPropertyLayer_data_length", \ NULL, \ NULL, \ NULL); \ \ srna = RNA_def_struct(brna, "Mesh" elemname "IntProperty", NULL); \ RNA_def_struct_sdna(srna, "MIntProperty"); \ RNA_def_struct_ui_text(srna, \ "Mesh " elemname " Int Property", \ "User defined integer number value in an integer properties layer"); \ RNA_def_struct_path_func(srna, "rna_Mesh" elemname "IntProperty_path"); \ \ prop = RNA_def_property(srna, "value", PROP_INT, PROP_NONE); \ RNA_def_property_int_sdna(prop, NULL, "i"); \ RNA_def_property_ui_text(prop, "Value", ""); \ RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); \ ((void)0) /* String */ # define MESH_STRING_PROPERTY_LAYER(elemname) \ srna = RNA_def_struct(brna, "Mesh" elemname "StringPropertyLayer", NULL); \ RNA_def_struct_sdna(srna, "CustomDataLayer"); \ RNA_def_struct_ui_text(srna, \ "Mesh " elemname " String Property Layer", \ "User defined layer of string text values"); \ RNA_def_struct_path_func(srna, "rna_Mesh" elemname "StringPropertyLayer_path"); \ \ prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); \ RNA_def_struct_name_property(srna, prop); \ RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshAnyLayer_name_set"); \ RNA_def_property_ui_text(prop, "Name", ""); \ RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); \ \ prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); \ RNA_def_property_struct_type(prop, "Mesh" elemname "StringProperty"); \ RNA_def_property_ui_text(prop, "Data", ""); \ RNA_def_property_collection_funcs(prop, \ "rna_Mesh" elemname "StringPropertyLayer_data_begin", \ "rna_iterator_array_next", \ "rna_iterator_array_end", \ "rna_iterator_array_get", \ "rna_Mesh" elemname "StringPropertyLayer_data_length", \ NULL, \ NULL, \ NULL); \ \ srna = RNA_def_struct(brna, "Mesh" elemname "StringProperty", NULL); \ RNA_def_struct_sdna(srna, "MStringProperty"); \ RNA_def_struct_ui_text(srna, \ "Mesh " elemname " String Property", \ "User defined string text value in a string properties layer"); \ RNA_def_struct_path_func(srna, "rna_Mesh" elemname "StringProperty_path"); \ \ /* low level mesh data access, treat as bytes */ \ prop = RNA_def_property(srna, "value", PROP_STRING, PROP_BYTESTRING); \ RNA_def_property_string_sdna(prop, NULL, "s"); \ RNA_def_property_string_funcs(prop, \ "rna_MeshStringProperty_s_get", \ "rna_MeshStringProperty_s_length", \ "rna_MeshStringProperty_s_set"); \ RNA_def_property_ui_text(prop, "Value", ""); \ RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); MESH_FLOAT_PROPERTY_LAYER("Vertex"); MESH_FLOAT_PROPERTY_LAYER("Polygon"); MESH_INT_PROPERTY_LAYER("Vertex"); MESH_INT_PROPERTY_LAYER("Polygon"); MESH_STRING_PROPERTY_LAYER("Vertex"); MESH_STRING_PROPERTY_LAYER("Polygon"); # undef MESH_PROPERTY_LAYER } void rna_def_texmat_common(StructRNA *srna, const char *texspace_editable) { PropertyRNA *prop; /* texture space */ prop = RNA_def_property(srna, "auto_texspace", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "texflag", ME_AUTOSPACE); RNA_def_property_ui_text( prop, "Auto Texture Space", "Adjust active object's texture space automatically when transforming object"); prop = RNA_def_property(srna, "texspace_location", PROP_FLOAT, PROP_TRANSLATION); RNA_def_property_float_sdna(prop, NULL, "loc"); RNA_def_property_ui_text(prop, "Texture Space Location", "Texture space location"); RNA_def_property_float_funcs(prop, "rna_Mesh_texspace_loc_get", NULL, NULL); RNA_def_property_editable_func(prop, texspace_editable); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "texspace_size", PROP_FLOAT, PROP_XYZ); RNA_def_property_float_sdna(prop, NULL, "size"); RNA_def_property_flag(prop, PROP_PROPORTIONAL); RNA_def_property_ui_text(prop, "Texture Space Size", "Texture space size"); RNA_def_property_float_funcs(prop, "rna_Mesh_texspace_size_get", NULL, NULL); RNA_def_property_editable_func(prop, texspace_editable); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); /* not supported yet */ # if 0 prop = RNA_def_property(srna, "texspace_rot", PROP_FLOAT, PROP_EULER); RNA_def_property_float(prop, NULL, "rot"); RNA_def_property_ui_text(prop, "Texture Space Rotation", "Texture space rotation"); RNA_def_property_editable_func(prop, texspace_editable); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); # endif /* materials */ prop = RNA_def_property(srna, "materials", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "mat", "totcol"); RNA_def_property_struct_type(prop, "Material"); RNA_def_property_ui_text(prop, "Materials", ""); RNA_def_property_srna(prop, "IDMaterials"); /* see rna_ID.c */ RNA_def_property_collection_funcs( prop, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "rna_IDMaterials_assign_int"); } /* scene.objects */ /* mesh.vertices */ static void rna_def_mesh_vertices(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; /* PropertyRNA *prop; */ FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "MeshVertices"); srna = RNA_def_struct(brna, "MeshVertices", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Mesh Vertices", "Collection of mesh vertices"); func = RNA_def_function(srna, "add", "ED_mesh_vertices_add"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_int( func, "count", 0, 0, INT_MAX, "Count", "Number of vertices to add", 0, INT_MAX); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); # if 0 /* BMESH_TODO Remove until BMesh merge */ func = RNA_def_function(srna, "remove", "ED_mesh_vertices_remove"); RNA_def_function_flag(func, FUNC_USE_REPORTS); RNA_def_int(func, "count", 0, 0, INT_MAX, "Count", "Number of vertices to remove", 0, INT_MAX); # endif } /* mesh.edges */ static void rna_def_mesh_edges(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; /* PropertyRNA *prop; */ FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "MeshEdges"); srna = RNA_def_struct(brna, "MeshEdges", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Mesh Edges", "Collection of mesh edges"); func = RNA_def_function(srna, "add", "ED_mesh_edges_add"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_int(func, "count", 0, 0, INT_MAX, "Count", "Number of edges to add", 0, INT_MAX); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); # if 0 /* BMESH_TODO Remove until BMesh merge */ func = RNA_def_function(srna, "remove", "ED_mesh_edges_remove"); RNA_def_function_flag(func, FUNC_USE_REPORTS); RNA_def_int(func, "count", 0, 0, INT_MAX, "Count", "Number of edges to remove", 0, INT_MAX); # endif } /* mesh.loop_triangles */ static void rna_def_mesh_looptris(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; RNA_def_property_srna(cprop, "MeshLoopTriangle"); srna = RNA_def_struct(brna, "MeshLoopTriangles", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text( srna, "Mesh Loop Triangles", "Tessellation of mesh polygons into triangles"); } /* mesh.loops */ static void rna_def_mesh_loops(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; /*PropertyRNA *prop;*/ FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "MeshLoops"); srna = RNA_def_struct(brna, "MeshLoops", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Mesh Loops", "Collection of mesh loops"); func = RNA_def_function(srna, "add", "ED_mesh_loops_add"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_int(func, "count", 0, 0, INT_MAX, "Count", "Number of loops to add", 0, INT_MAX); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); } /* mesh.polygons */ static void rna_def_mesh_polygons(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; PropertyRNA *prop; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "MeshPolygons"); srna = RNA_def_struct(brna, "MeshPolygons", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Mesh Polygons", "Collection of mesh polygons"); prop = RNA_def_property(srna, "active", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "act_face"); RNA_def_property_ui_text(prop, "Active Polygon", "The active polygon for this mesh"); func = RNA_def_function(srna, "add", "ED_mesh_polys_add"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_int( func, "count", 0, 0, INT_MAX, "Count", "Number of polygons to add", 0, INT_MAX); RNA_def_parameter_flags(parm, 0, PARM_REQUIRED); } static void rna_def_loop_colors(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; PropertyRNA *prop; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "LoopColors"); srna = RNA_def_struct(brna, "LoopColors", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Loop Colors", "Collection of vertex colors"); func = RNA_def_function(srna, "new", "rna_Mesh_vertex_color_new"); RNA_def_function_ui_description(func, "Add a vertex color layer to Mesh"); RNA_def_string(func, "name", "Col", 0, "", "Vertex color name"); RNA_def_boolean(func, "do_init", true, "", "Whether new layer's data should be initialized by copying current active one"); parm = RNA_def_pointer(func, "layer", "MeshLoopColorLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "remove", "rna_Mesh_vertex_color_remove"); RNA_def_function_ui_description(func, "Remove a vertex color layer"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_pointer(func, "layer", "MeshLoopColorLayer", "", "The layer to remove"); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED); RNA_def_property_clear_flag(parm, PROP_THICK_WRAP); prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "MeshLoopColorLayer"); RNA_def_property_pointer_funcs( prop, "rna_Mesh_vertex_color_active_get", "rna_Mesh_vertex_color_active_set", NULL, NULL); RNA_def_property_flag(prop, PROP_EDITABLE | PROP_NEVER_UNLINK); RNA_def_property_ui_text(prop, "Active Vertex Color Layer", "Active vertex color layer"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data_edit_active_color"); prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_vertex_color_active_index_get", "rna_Mesh_vertex_color_active_index_set", "rna_Mesh_vertex_color_index_range"); RNA_def_property_ui_text(prop, "Active Vertex Color Index", "Active vertex color index"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data_edit_active_color"); } static void rna_def_uv_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; PropertyRNA *prop; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "UVLoopLayers"); srna = RNA_def_struct(brna, "UVLoopLayers", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "UV Loop Layers", "Collection of uv loop layers"); func = RNA_def_function(srna, "new", "rna_Mesh_uv_layers_new"); RNA_def_function_ui_description(func, "Add a UV map layer to Mesh"); RNA_def_string(func, "name", "UVMap", 0, "", "UV map name"); RNA_def_boolean(func, "do_init", true, "", "Whether new layer's data should be initialized by copying current active one, " "or if none is active, with a default UVmap"); parm = RNA_def_pointer(func, "layer", "MeshUVLoopLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "remove", "rna_Mesh_uv_layers_remove"); RNA_def_function_ui_description(func, "Remove a vertex color layer"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_pointer(func, "layer", "MeshUVLoopLayer", "", "The layer to remove"); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED); prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "MeshUVLoopLayer"); RNA_def_property_pointer_funcs( prop, "rna_Mesh_uv_layer_active_get", "rna_Mesh_uv_layer_active_set", NULL, NULL); RNA_def_property_flag(prop, PROP_EDITABLE | PROP_NEVER_UNLINK); RNA_def_property_ui_text(prop, "Active UV loop layer", "Active UV loop layer"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_uv_layer_active_index_get", "rna_Mesh_uv_layer_active_index_set", "rna_Mesh_uv_layer_index_range"); RNA_def_property_ui_text(prop, "Active UV loop layer Index", "Active UV loop layer index"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); } /* mesh float layers */ static void rna_def_vertex_float_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "VertexFloatProperties"); srna = RNA_def_struct(brna, "VertexFloatProperties", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Vertex Float Properties", "Collection of float properties"); func = RNA_def_function(srna, "new", "rna_Mesh_vertex_float_property_new"); RNA_def_function_ui_description(func, "Add a float property layer to Mesh"); RNA_def_string(func, "name", "Float Prop", 0, "", "Float property name"); parm = RNA_def_pointer( func, "layer", "MeshVertexFloatPropertyLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); } /* mesh int layers */ static void rna_def_vertex_int_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "VertexIntProperties"); srna = RNA_def_struct(brna, "VertexIntProperties", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Vertex Int Properties", "Collection of int properties"); func = RNA_def_function(srna, "new", "rna_Mesh_vertex_int_property_new"); RNA_def_function_ui_description(func, "Add a integer property layer to Mesh"); RNA_def_string(func, "name", "Int Prop", 0, "", "Int property name"); parm = RNA_def_pointer( func, "layer", "MeshVertexIntPropertyLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); } /* mesh string layers */ static void rna_def_vertex_string_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "VertexStringProperties"); srna = RNA_def_struct(brna, "VertexStringProperties", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Vertex String Properties", "Collection of string properties"); func = RNA_def_function(srna, "new", "rna_Mesh_vertex_string_property_new"); RNA_def_function_ui_description(func, "Add a string property layer to Mesh"); RNA_def_string(func, "name", "String Prop", 0, "", "String property name"); parm = RNA_def_pointer( func, "layer", "MeshVertexStringPropertyLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); } /* mesh float layers */ static void rna_def_polygon_float_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "PolygonFloatProperties"); srna = RNA_def_struct(brna, "PolygonFloatProperties", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Polygon Float Properties", "Collection of float properties"); func = RNA_def_function(srna, "new", "rna_Mesh_polygon_float_property_new"); RNA_def_function_ui_description(func, "Add a float property layer to Mesh"); RNA_def_string(func, "name", "Float Prop", 0, "", "Float property name"); parm = RNA_def_pointer( func, "layer", "MeshPolygonFloatPropertyLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); } /* mesh int layers */ static void rna_def_polygon_int_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "PolygonIntProperties"); srna = RNA_def_struct(brna, "PolygonIntProperties", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Polygon Int Properties", "Collection of int properties"); func = RNA_def_function(srna, "new", "rna_Mesh_polygon_int_property_new"); RNA_def_function_ui_description(func, "Add a integer property layer to Mesh"); RNA_def_string(func, "name", "Int Prop", 0, "", "Int property name"); parm = RNA_def_pointer( func, "layer", "MeshPolygonIntPropertyLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); } /* mesh string layers */ static void rna_def_polygon_string_layers(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; FunctionRNA *func; PropertyRNA *parm; RNA_def_property_srna(cprop, "PolygonStringProperties"); srna = RNA_def_struct(brna, "PolygonStringProperties", NULL); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Polygon String Properties", "Collection of string properties"); func = RNA_def_function(srna, "new", "rna_Mesh_polygon_string_property_new"); RNA_def_function_ui_description(func, "Add a string property layer to Mesh"); RNA_def_string(func, "name", "String Prop", 0, "", "String property name"); parm = RNA_def_pointer( func, "layer", "MeshPolygonStringPropertyLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); } static void rna_def_skin_vertices(BlenderRNA *brna, PropertyRNA *UNUSED(cprop)) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshSkinVertexLayer", NULL); RNA_def_struct_ui_text( srna, "Mesh Skin Vertex Layer", "Per-vertex skin data for use with the Skin modifier"); RNA_def_struct_sdna(srna, "CustomDataLayer"); RNA_def_struct_path_func(srna, "rna_MeshSkinVertexLayer_path"); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_struct_name_property(srna, prop); RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshVertexLayer_name_set"); RNA_def_property_ui_text(prop, "Name", "Name of skin layer"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "MeshSkinVertex"); RNA_def_property_ui_text(prop, "Data", ""); RNA_def_property_collection_funcs(prop, "rna_MeshSkinVertexLayer_data_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", "rna_MeshSkinVertexLayer_data_length", NULL, NULL, NULL); /* SkinVertex struct */ srna = RNA_def_struct(brna, "MeshSkinVertex", NULL); RNA_def_struct_sdna(srna, "MVertSkin"); RNA_def_struct_ui_text( srna, "Skin Vertex", "Per-vertex skin data for use with the Skin modifier"); RNA_def_struct_path_func(srna, "rna_MeshSkinVertex_path"); prop = RNA_def_property(srna, "radius", PROP_FLOAT, PROP_UNSIGNED); RNA_def_property_array(prop, 2); RNA_def_property_ui_range(prop, 0.001, 100.0, 1, 3); RNA_def_property_ui_text(prop, "Radius", "Radius of the skin"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); /* Flags */ prop = RNA_def_property(srna, "use_root", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MVERT_SKIN_ROOT); RNA_def_property_ui_text(prop, "Root", "Vertex is a root for rotation calculations and armature generation, " "setting this flag does not clear other roots in the same mesh island"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "use_loose", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", MVERT_SKIN_LOOSE); RNA_def_property_ui_text( prop, "Loose", "If vertex has multiple adjacent edges, it is hulled to them directly"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); } static void rna_def_paint_mask(BlenderRNA *brna, PropertyRNA *UNUSED(cprop)) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshPaintMaskLayer", NULL); RNA_def_struct_ui_text(srna, "Mesh Paint Mask Layer", "Per-vertex paint mask data"); RNA_def_struct_sdna(srna, "CustomDataLayer"); RNA_def_struct_path_func(srna, "rna_MeshPaintMaskLayer_path"); prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "MeshPaintMaskProperty"); RNA_def_property_ui_text(prop, "Data", ""); RNA_def_property_collection_funcs(prop, "rna_MeshPaintMaskLayer_data_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", "rna_MeshPaintMaskLayer_data_length", NULL, NULL, NULL); srna = RNA_def_struct(brna, "MeshPaintMaskProperty", NULL); RNA_def_struct_sdna(srna, "MFloatProperty"); RNA_def_struct_ui_text(srna, "Mesh Paint Mask Property", "Floating point paint mask value"); RNA_def_struct_path_func(srna, "rna_MeshPaintMask_path"); prop = RNA_def_property(srna, "value", PROP_FLOAT, PROP_NONE); RNA_def_property_float_sdna(prop, NULL, "f"); RNA_def_property_ui_text(prop, "Value", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); } static void rna_def_face_map(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "MeshFaceMapLayer", NULL); RNA_def_struct_ui_text(srna, "Mesh Face Map Layer", "Per-face map index"); RNA_def_struct_sdna(srna, "CustomDataLayer"); RNA_def_struct_path_func(srna, "rna_MeshFaceMapLayer_path"); prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE); RNA_def_struct_name_property(srna, prop); RNA_def_property_string_funcs(prop, NULL, NULL, "rna_MeshPolyLayer_name_set"); RNA_def_property_ui_text(prop, "Name", "Name of face-map layer"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "data", PROP_COLLECTION, PROP_NONE); RNA_def_property_struct_type(prop, "MeshFaceMap"); RNA_def_property_ui_text(prop, "Data", ""); RNA_def_property_collection_funcs(prop, "rna_MeshFaceMapLayer_data_begin", "rna_iterator_array_next", "rna_iterator_array_end", "rna_iterator_array_get", "rna_MeshFaceMapLayer_data_length", NULL, NULL, NULL); /* FaceMap struct */ srna = RNA_def_struct(brna, "MeshFaceMap", NULL); RNA_def_struct_sdna(srna, "MIntProperty"); RNA_def_struct_ui_text(srna, "Int Property", ""); RNA_def_struct_path_func(srna, "rna_MeshFaceMap_path"); prop = RNA_def_property(srna, "value", PROP_INT, PROP_NONE); RNA_def_property_int_sdna(prop, NULL, "i"); RNA_def_property_ui_text(prop, "Value", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); } static void rna_def_face_maps(BlenderRNA *brna, PropertyRNA *cprop) { StructRNA *srna; PropertyRNA *prop; RNA_def_property_srna(cprop, "MeshFaceMapLayers"); srna = RNA_def_struct(brna, "MeshFaceMapLayers", NULL); RNA_def_struct_ui_text(srna, "Mesh Face Map Layer", "Per-face map index"); RNA_def_struct_sdna(srna, "Mesh"); RNA_def_struct_ui_text(srna, "Mesh FaceMaps", "Collection of mesh face-maps"); /* add this since we only ever have one layer anyway, don't bother with active_index */ prop = RNA_def_property(srna, "active", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "MeshFaceMapLayer"); RNA_def_property_pointer_funcs(prop, "rna_Mesh_face_map_active_get", NULL, NULL, NULL); RNA_def_property_ui_text(prop, "Active FaceMap Layer", ""); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); FunctionRNA *func; PropertyRNA *parm; func = RNA_def_function(srna, "new", "rna_Mesh_face_map_new"); RNA_def_function_flag(func, FUNC_USE_REPORTS); RNA_def_function_ui_description(func, "Add a float property layer to Mesh"); RNA_def_string(func, "name", "Face Map", 0, "", "Face map name"); parm = RNA_def_pointer(func, "layer", "MeshFaceMapLayer", "", "The newly created layer"); RNA_def_parameter_flags(parm, 0, PARM_RNAPTR); RNA_def_function_return(func, parm); func = RNA_def_function(srna, "remove", "rna_Mesh_face_map_remove"); RNA_def_function_ui_description(func, "Remove a face map layer"); RNA_def_function_flag(func, FUNC_USE_REPORTS); parm = RNA_def_pointer(func, "layer", "MeshFaceMapLayer", "", "The layer to remove"); RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED); RNA_def_property_clear_flag(parm, PROP_THICK_WRAP); } static void rna_def_mesh(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna = RNA_def_struct(brna, "Mesh", "ID"); RNA_def_struct_ui_text(srna, "Mesh", "Mesh data-block defining geometric surfaces"); RNA_def_struct_ui_icon(srna, ICON_MESH_DATA); prop = RNA_def_property(srna, "vertices", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "mvert", "totvert"); RNA_def_property_struct_type(prop, "MeshVertex"); RNA_def_property_ui_text(prop, "Vertices", "Vertices of the mesh"); rna_def_mesh_vertices(brna, prop); prop = RNA_def_property(srna, "edges", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "medge", "totedge"); RNA_def_property_struct_type(prop, "MeshEdge"); RNA_def_property_ui_text(prop, "Edges", "Edges of the mesh"); rna_def_mesh_edges(brna, prop); prop = RNA_def_property(srna, "loops", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "mloop", "totloop"); RNA_def_property_struct_type(prop, "MeshLoop"); RNA_def_property_ui_text(prop, "Loops", "Loops of the mesh (polygon corners)"); rna_def_mesh_loops(brna, prop); prop = RNA_def_property(srna, "polygons", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "mpoly", "totpoly"); RNA_def_property_struct_type(prop, "MeshPolygon"); RNA_def_property_ui_text(prop, "Polygons", "Polygons of the mesh"); rna_def_mesh_polygons(brna, prop); prop = RNA_def_property(srna, "loop_triangles", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "runtime.looptris.array", "runtime.looptris.len"); RNA_def_property_struct_type(prop, "MeshLoopTriangle"); RNA_def_property_ui_text(prop, "Loop Triangles", "Tessellation of mesh polygons into triangles"); rna_def_mesh_looptris(brna, prop); /* TODO, should this be allowed to be its self? */ prop = RNA_def_property(srna, "texture_mesh", PROP_POINTER, PROP_NONE); RNA_def_property_pointer_sdna(prop, NULL, "texcomesh"); RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_SELF_CHECK); RNA_def_property_ui_text( prop, "Texture Mesh", "Use another mesh for texture indices (vertex indices must be aligned)"); /* UV loop layers */ prop = RNA_def_property(srna, "uv_layers", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "ldata.layers", "ldata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_uv_layers_begin", NULL, NULL, NULL, "rna_Mesh_uv_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshUVLoopLayer"); RNA_def_property_ui_text(prop, "UV Loop Layers", "All UV loop layers"); rna_def_uv_layers(brna, prop); prop = RNA_def_property(srna, "uv_layer_clone", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "MeshUVLoopLayer"); RNA_def_property_pointer_funcs( prop, "rna_Mesh_uv_layer_clone_get", "rna_Mesh_uv_layer_clone_set", NULL, NULL); RNA_def_property_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text( prop, "Clone UV loop layer", "UV loop layer to be used as cloning source"); prop = RNA_def_property(srna, "uv_layer_clone_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_uv_layer_clone_index_get", "rna_Mesh_uv_layer_clone_index_set", "rna_Mesh_uv_layer_index_range"); RNA_def_property_ui_text(prop, "Clone UV loop layer Index", "Clone UV loop layer index"); prop = RNA_def_property(srna, "uv_layer_stencil", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "MeshUVLoopLayer"); RNA_def_property_pointer_funcs( prop, "rna_Mesh_uv_layer_stencil_get", "rna_Mesh_uv_layer_stencil_set", NULL, NULL); RNA_def_property_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Mask UV loop layer", "UV loop layer to mask the painted area"); prop = RNA_def_property(srna, "uv_layer_stencil_index", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_uv_layer_stencil_index_get", "rna_Mesh_uv_layer_stencil_index_set", "rna_Mesh_uv_layer_index_range"); RNA_def_property_ui_text(prop, "Mask UV loop layer Index", "Mask UV loop layer index"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); /* Vertex colors */ prop = RNA_def_property(srna, "vertex_colors", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "ldata.layers", "ldata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_vertex_colors_begin", NULL, NULL, NULL, "rna_Mesh_vertex_colors_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshLoopColorLayer"); RNA_def_property_ui_text(prop, "Vertex Colors", "All vertex colors"); rna_def_loop_colors(brna, prop); /* TODO, edge customdata layers (bmesh py api can access already) */ prop = RNA_def_property(srna, "vertex_layers_float", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "vdata.layers", "vdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_vertex_float_layers_begin", NULL, NULL, NULL, "rna_Mesh_vertex_float_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshVertexFloatPropertyLayer"); RNA_def_property_ui_text(prop, "Float Property Layers", ""); rna_def_vertex_float_layers(brna, prop); prop = RNA_def_property(srna, "vertex_layers_int", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "vdata.layers", "vdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_vertex_int_layers_begin", NULL, NULL, NULL, "rna_Mesh_vertex_int_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshVertexIntPropertyLayer"); RNA_def_property_ui_text(prop, "Int Property Layers", ""); rna_def_vertex_int_layers(brna, prop); prop = RNA_def_property(srna, "vertex_layers_string", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "vdata.layers", "vdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_vertex_string_layers_begin", NULL, NULL, NULL, "rna_Mesh_vertex_string_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshVertexStringPropertyLayer"); RNA_def_property_ui_text(prop, "String Property Layers", ""); rna_def_vertex_string_layers(brna, prop); prop = RNA_def_property(srna, "polygon_layers_float", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "pdata.layers", "pdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_polygon_float_layers_begin", NULL, NULL, NULL, "rna_Mesh_polygon_float_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshPolygonFloatPropertyLayer"); RNA_def_property_ui_text(prop, "Float Property Layers", ""); rna_def_polygon_float_layers(brna, prop); prop = RNA_def_property(srna, "polygon_layers_int", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "pdata.layers", "pdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_polygon_int_layers_begin", NULL, NULL, NULL, "rna_Mesh_polygon_int_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshPolygonIntPropertyLayer"); RNA_def_property_ui_text(prop, "Int Property Layers", ""); rna_def_polygon_int_layers(brna, prop); prop = RNA_def_property(srna, "polygon_layers_string", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "pdata.layers", "pdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_polygon_string_layers_begin", NULL, NULL, NULL, "rna_Mesh_polygon_string_layers_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshPolygonStringPropertyLayer"); RNA_def_property_ui_text(prop, "String Property Layers", ""); rna_def_polygon_string_layers(brna, prop); /* face-maps */ prop = RNA_def_property(srna, "face_maps", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "pdata.layers", "pdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_face_maps_begin", NULL, NULL, NULL, "rna_Mesh_face_maps_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshFaceMapLayer"); RNA_def_property_ui_text(prop, "FaceMap", ""); rna_def_face_maps(brna, prop); /* Skin vertices */ prop = RNA_def_property(srna, "skin_vertices", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "vdata.layers", "vdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_skin_vertices_begin", NULL, NULL, NULL, "rna_Mesh_skin_vertices_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshSkinVertexLayer"); RNA_def_property_ui_text(prop, "Skin Vertices", "All skin vertices"); rna_def_skin_vertices(brna, prop); /* End skin vertices */ /* Paint mask */ prop = RNA_def_property(srna, "vertex_paint_masks", PROP_COLLECTION, PROP_NONE); RNA_def_property_collection_sdna(prop, NULL, "vdata.layers", "vdata.totlayer"); RNA_def_property_collection_funcs(prop, "rna_Mesh_vertex_paint_masks_begin", NULL, NULL, NULL, "rna_Mesh_vertex_paint_masks_length", NULL, NULL, NULL); RNA_def_property_struct_type(prop, "MeshPaintMaskLayer"); RNA_def_property_ui_text(prop, "Vertex Paint Mask", "Vertex paint mask"); rna_def_paint_mask(brna, prop); /* End paint mask */ prop = RNA_def_property(srna, "use_auto_smooth", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_AUTOSMOOTH); RNA_def_property_ui_text( prop, "Auto Smooth", "Auto smooth (based on smooth/sharp faces/edges and angle between faces), " "or use custom split normals data if available"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "auto_smooth_angle", PROP_FLOAT, PROP_ANGLE); RNA_def_property_float_sdna(prop, NULL, "smoothresh"); RNA_def_property_float_default(prop, DEG2RADF(180.0f)); RNA_def_property_range(prop, 0.0f, DEG2RADF(180.0f)); RNA_def_property_ui_text(prop, "Auto Smooth Angle", "Maximum angle between face normals that will be considered as smooth " "(unused if custom split normals data are available)"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); RNA_define_verify_sdna(false); prop = RNA_def_property(srna, "has_custom_normals", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "", 0); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text( prop, "Has Custom Normals", "True if there are custom split normals data in this mesh"); RNA_def_property_boolean_funcs(prop, "rna_Mesh_has_custom_normals_get", NULL); RNA_define_verify_sdna(true); prop = RNA_def_property(srna, "show_double_sided", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", ME_TWOSIDED); RNA_def_property_ui_text( prop, "Double Sided", "Display the mesh with double or single sided lighting (OpenGL only)"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); prop = RNA_def_property(srna, "texco_mesh", PROP_POINTER, PROP_NONE); RNA_def_property_pointer_sdna(prop, NULL, "texcomesh"); RNA_def_property_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text( prop, "Texture Space Mesh", "Derive texture coordinates from another mesh"); prop = RNA_def_property(srna, "shape_keys", PROP_POINTER, PROP_NONE); RNA_def_property_pointer_sdna(prop, NULL, "key"); RNA_def_property_ui_text(prop, "Shape Keys", ""); /* texture space */ prop = RNA_def_property(srna, "use_auto_texspace", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "texflag", ME_AUTOSPACE); RNA_def_property_ui_text( prop, "Auto Texture Space", "Adjust active object's texture space automatically when transforming object"); RNA_def_property_update(prop, 0, "rna_Mesh_update_data"); # if 0 prop = RNA_def_property(srna, "texspace_location", PROP_FLOAT, PROP_TRANSLATION); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Texture Space Location", "Texture space location"); RNA_def_property_editable_func(prop, "rna_Mesh_texspace_editable"); RNA_def_property_float_funcs( prop, "rna_Mesh_texspace_loc_get", "rna_Mesh_texspace_loc_set", NULL); RNA_def_property_update(prop, 0, "rna_Mesh_update_draw"); # endif /* not supported yet */ # if 0 prop = RNA_def_property(srna, "texspace_rot", PROP_FLOAT, PROP_EULER); RNA_def_property_float(prop, NULL, "rot"); RNA_def_property_ui_text(prop, "Texture Space Rotation", "Texture space rotation"); RNA_def_property_editable_func(prop, texspace_editable); RNA_def_property_update(prop, 0, "rna_Mesh_update_draw"); # endif /* editflag */ prop = RNA_def_property(srna, "use_mirror_x", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "editflag", ME_EDIT_MIRROR_X); RNA_def_property_ui_text(prop, "X Mirror", "X Axis mirror editing"); RNA_def_property_update(prop, 0, "rna_Mesh_update_draw"); # if 0 prop = RNA_def_property(srna, "use_mirror_y", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "editflag", ME_EDIT_MIRROR_Y); RNA_def_property_ui_text(prop, "Y Mirror", "Y Axis mirror editing"); prop = RNA_def_property(srna, "use_mirror_z", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "editflag", ME_EDIT_MIRROR_Z); RNA_def_property_ui_text(prop, "Z Mirror", "Z Axis mirror editing"); # endif prop = RNA_def_property(srna, "use_mirror_topology", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "editflag", ME_EDIT_MIRROR_TOPO); RNA_def_property_ui_text(prop, "Topology Mirror", "Use topology based mirroring " "(for when both sides of mesh have matching, unique topology)"); prop = RNA_def_property(srna, "use_paint_mask", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "editflag", ME_EDIT_PAINT_FACE_SEL); RNA_def_property_ui_text(prop, "Paint Mask", "Face selection masking for painting"); RNA_def_property_ui_icon(prop, ICON_FACESEL, 0); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_Mesh_update_facemask"); prop = RNA_def_property(srna, "use_paint_mask_vertex", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "editflag", ME_EDIT_PAINT_VERT_SEL); RNA_def_property_ui_text( prop, "Vertex Selection", "Vertex selection masking for painting (weight paint only)"); RNA_def_property_ui_icon(prop, ICON_VERTEXSEL, 0); RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_Mesh_update_vertmask"); /* customdata flags */ prop = RNA_def_property(srna, "use_customdata_vertex_bevel", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "cd_flag", ME_CDFLAG_VERT_BWEIGHT); RNA_def_property_ui_text(prop, "Store Vertex Bevel Weight", ""); prop = RNA_def_property(srna, "use_customdata_edge_bevel", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "cd_flag", ME_CDFLAG_EDGE_BWEIGHT); RNA_def_property_ui_text(prop, "Store Edge Bevel Weight", ""); prop = RNA_def_property(srna, "use_customdata_edge_crease", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "cd_flag", ME_CDFLAG_EDGE_CREASE); RNA_def_property_ui_text(prop, "Store Edge Crease", ""); /* readonly editmesh info - use for extrude menu */ prop = RNA_def_property(srna, "total_vert_sel", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_tot_vert_get", NULL, NULL); RNA_def_property_ui_text(prop, "Selected Vert Total", "Selected vertex count in editmode"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "total_edge_sel", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_tot_edge_get", NULL, NULL); RNA_def_property_ui_text(prop, "Selected Edge Total", "Selected edge count in editmode"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "total_face_sel", PROP_INT, PROP_UNSIGNED); RNA_def_property_int_funcs(prop, "rna_Mesh_tot_face_get", NULL, NULL); RNA_def_property_ui_text(prop, "Selected Face Total", "Selected face count in editmode"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); prop = RNA_def_property(srna, "is_editmode", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs(prop, "rna_Mesh_is_editmode_get", NULL); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Is Editmode", "True when used in editmode"); /* pointers */ rna_def_animdata_common(srna); rna_def_texmat_common(srna, "rna_Mesh_texspace_editable"); RNA_api_mesh(srna); } void RNA_def_mesh(BlenderRNA *brna) { rna_def_mesh(brna); rna_def_mvert(brna); rna_def_mvert_group(brna); rna_def_medge(brna); rna_def_mlooptri(brna); rna_def_mloop(brna); rna_def_mpolygon(brna); rna_def_mloopuv(brna); rna_def_mloopcol(brna); rna_def_mproperties(brna); rna_def_face_map(brna); } #endif
gmlueck/llvm-test-suite
SYCL/ESIMD/reduction.cpp
//==---------------- reduction.cpp - DPC++ ESIMD on-device test //------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // REQUIRES: gpu // UNSUPPORTED: cuda || hip // RUN: %clangxx -fsycl %s -o %t.out // RUN: %HOST_RUN_PLACEHOLDER %t.out // RUN: %GPU_RUN_PLACEHOLDER %t.out #include "esimd_test_utils.hpp" #include <CL/sycl.hpp> #include <iostream> #include <sycl/ext/intel/experimental/esimd.hpp> using namespace cl::sycl; typedef short TYPE; int main(void) { constexpr unsigned InputSize = 32; constexpr unsigned OutputSize = 4; constexpr unsigned VL = 32; constexpr unsigned GroupSize = 1; queue q(esimd_test::ESIMDSelector{}, esimd_test::createExceptionHandler()); auto dev = q.get_device(); std::cout << "Running on " << dev.get_info<info::device::name>() << "\n"; TYPE *A = malloc_shared<TYPE>(InputSize, q); int *B = malloc_shared<int>(OutputSize, q); for (unsigned i = 0; i < InputSize; ++i) { if (i == 19) { A[i] = 32767; } else { A[i] = i; } } try { range<1> GroupRange{InputSize / VL}; range<1> TaskRange{GroupSize}; nd_range<1> Range(GroupRange, TaskRange); auto e = q.submit([&](handler &cgh) { cgh.parallel_for<class Test>( GroupRange * TaskRange, [=](id<1> i) SYCL_ESIMD_KERNEL { using namespace sycl::ext::intel::experimental::esimd; simd<TYPE, VL> va; va.copy_from(A + i * VL); simd<int, OutputSize> vb; vb[0] = reduce<int>(va, std::plus<>()); vb[1] = reduce<int>(va, std::multiplies<>()); vb[2] = hmax<int>(va); vb[3] = hmin<int>(va); vb.copy_to(B + i * VL); }); }); e.wait(); } catch (sycl::exception const &e) { std::cout << "SYCL exception caught: " << e.what() << '\n'; free(A, q); free(B, q); return 1; } auto compute_reduce_sum = [](TYPE A[InputSize]) -> int { int retv = A[0]; for (int i = 1; i < InputSize; i++) { retv += A[i]; } return retv; }; auto compute_reduce_prod = [](TYPE A[InputSize]) -> int { int retv = A[0]; for (int i = 1; i < InputSize; i++) { retv *= A[i]; } return retv; }; auto compute_reduce_max = [](TYPE A[InputSize]) -> int { int retv = A[0]; for (int i = 1; i < InputSize; i++) { if (A[i] > retv) { retv = A[i]; } } return retv; }; auto compute_reduce_min = [](TYPE A[InputSize]) -> int { int retv = A[0]; for (int i = 1; i < InputSize; i++) { if (A[i] < retv) { retv = A[i]; } } return retv; }; bool TestPass = true; int ref = compute_reduce_sum(A); if (B[0] != ref) { std::cout << "Incorrect sum " << B[0] << ", expected " << ref << "\n"; TestPass = false; } ref = compute_reduce_prod(A); if (B[1] != ref) { std::cout << "Incorrect prod " << B[1] << ", expected " << ref << "\n"; TestPass = false; } ref = compute_reduce_max(A); if (B[2] != ref) { std::cout << "Incorrect max " << B[2] << ", expected " << ref << "\n"; TestPass = false; } ref = compute_reduce_min(A); if (B[3] != ref) { std::cout << "Incorrect min " << B[3] << ", expected " << ref << "\n"; TestPass = false; } free(A, q); free(B, q); if (!TestPass) { std::cout << "Failed\n"; return 1; } std::cout << "Passed\n"; return 0; }
joseabelramirezfrontany/forkify
node_modules/@parcel/transformer-typescript-types/lib/TSModuleGraph.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSModuleGraph = void 0; var _nullthrows = _interopRequireDefault(require("nullthrows")); var _assert = _interopRequireDefault(require("assert")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } class TSModuleGraph { constructor(ts, mainModuleName) { _defineProperty(this, "ts", void 0); _defineProperty(this, "modules", void 0); _defineProperty(this, "mainModuleName", void 0); _defineProperty(this, "mainModule", void 0); this.ts = ts; this.modules = new Map(); this.mainModuleName = mainModuleName; this.mainModule = null; } addModule(name, module) { this.modules.set(name, module); if (name === this.mainModuleName) { this.mainModule = module; } } getModule(name) { return this.modules.get(name); } markUsed(module, name, context) { let { ts } = this; // If name is imported, mark used in the original module if (module.imports.has(name)) { module.used.add(name); let { specifier, imported } = (0, _nullthrows.default)(module.imports.get(name)); let m = this.getModule(specifier); if (!m) { return; } return this.markUsed(m, imported, context); } if (module.used.has(name)) { return; } module.used.add(name); // Visit all child nodes of the original binding and mark any referenced types as used. let visit = node => { if (ts.isQualifiedName(node) && ts.isIdentifier(node.left)) { let resolved = this.resolveImport(module, node.left.text, node.right.text); if (resolved) { this.markUsed(resolved.module, resolved.imported, context); } } else if (ts.isIdentifier(node)) { this.markUsed(module, node.text, context); } return ts.visitEachChild(node, visit, context); }; let node = module.bindings.get(name); if (node) { ts.visitEachChild(node, visit, context); } } getExport(m, e) { (0, _assert.default)(e.name != null); let exportName = e.name; // Re-export if (e.specifier && e.imported) { let m = this.getModule(e.specifier); if (!m) { return null; } let exp = this.resolveExport(m, e.imported); if (!exp) { return null; } return { module: exp.module, imported: exp.name, name: exportName }; } // Import and then export if (m.imports.has(exportName)) { let imp = this.resolveImport(m, exportName); if (!imp) { return null; } return { module: imp.module, imported: imp.name, name: exportName }; } // Named export return { module: m, name: m.getName(exportName), imported: e.imported || exportName }; } resolveImport(module, local, imported) { let i = module.imports.get(local); if (!i) { return null; } let m = this.getModule(i.specifier); if (!m) { // External module. pass through the import. return { module, name: local, imported: imported || i.imported }; } return this.resolveExport(m, imported || i.imported); } resolveExport(module, name) { for (let e of module.exports) { if (e.name === name) { return this.getExport(module, e); } else if (e.specifier) { return this.resolveExport((0, _nullthrows.default)(this.getModule(e.specifier)), name); } } } getAllExports(module = (0, _nullthrows.default)(this.mainModule), excludeDefault = false) { let res = []; for (let e of module.exports) { if (e.name && (!excludeDefault || e.name !== 'default')) { let exp = this.getExport(module, e); if (exp) { res.push(exp); } } else if (e.specifier) { let m = this.getModule(e.specifier); if (m) { res.push(...this.getAllExports(m, true)); } } } return res; } getAllImports() { // Build a map of all imports for external modules let importsBySpecifier = new Map(); for (let module of this.modules.values()) { for (let [name, imp] of module.imports) { if (module.used.has(name) && !this.modules.has(imp.specifier)) { let importMap = importsBySpecifier.get(imp.specifier); if (!importMap) { importMap = new Map(); importsBySpecifier.set(imp.specifier, importMap); } name = module.getName(name); importMap.set(name, imp.imported); } } } return importsBySpecifier; } propagate(context) { // Resolve all exported values, and mark them as used. let names = Object.create(null); let exportedNames = new Map(); for (let e of this.getAllExports()) { this.markUsed(e.module, e.imported, context); e.module.names.set(e.imported, e.name); names[e.name] = 1; exportedNames.set(e.name, e.module); } // Assign unique names across all modules for (let m of this.modules.values()) { for (let [orig, name] of m.names) { if (exportedNames.has(name) && exportedNames.get(name) === m) { continue; } if (!m.used.has(orig) || m.imports.get(orig)) { continue; } if (names[name]) { m.names.set(name, `_${name}${names[name]++}`); } else { names[name] = 1; } } } return exportedNames; } } exports.TSModuleGraph = TSModuleGraph;
T-head-Semi/csi-nn2
tests/validation/batch_norm_i8.c
/* * Copyright (C) 2016-2022 T-Head Semiconductor Co., Ltd. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * 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. */ /* CSI-NN2 version 1.12.x */ #include "test_utils.h" #include "csi_nn.h" #include "math_snr.h" int main(int argc, char** argv) { init_testsuite("Testing function of batch normalization i8.\n"); struct csi_tensor *input = csi_alloc_tensor(NULL); struct csi_tensor *mean = csi_alloc_tensor(NULL); struct csi_tensor *variance = csi_alloc_tensor(NULL); struct csi_tensor *beta = csi_alloc_tensor(NULL); struct csi_tensor *gamma = csi_alloc_tensor(NULL); struct csi_tensor *output = csi_alloc_tensor(NULL); struct csi_tensor *reference = csi_alloc_tensor(NULL); struct bn_params params; int size = 1; int zp, quantized_multiplier, shift; float max_value, min_value, scale; float error[5] = {0}; float max_error; int *buffer = read_input_data_f32(argv[1]); /* get the dim para */ output->dim_count = input->dim_count = buffer[0]; for (int i = 0; i < input->dim_count; ++i) { output->dim[i] = input->dim[i] = buffer[1 + i]; } for (int i = 0; i < input->dim_count; ++i) { size *= input->dim[i]; } mean->dim_count = 1; variance->dim_count = 1; gamma->dim_count = 1; beta->dim_count = 1; mean->dim[0] = input->dim[input->dim_count - 1]; variance->dim[0] = input->dim[input->dim_count - 1]; gamma->dim[0] = input->dim[input->dim_count - 1]; beta->dim[0] = input->dim[input->dim_count - 1]; input->dtype = CSINN_DTYPE_INT8; input->layout = CSINN_LAYOUT_NHWC; input->is_const = 0; input->quant_channel = 1; output->dtype = CSINN_DTYPE_INT8; output->layout = CSINN_LAYOUT_NHWC; output->is_const = 0; output->quant_channel = 1; mean->dtype = CSINN_DTYPE_INT8; mean->layout = CSINN_LAYOUT_O; mean->is_const = 0; mean->quant_channel = 1; variance->dtype = CSINN_DTYPE_INT8; variance->layout = CSINN_LAYOUT_O; variance->is_const = 0; variance->quant_channel = 1; gamma->dtype = CSINN_DTYPE_INT8; gamma->layout = CSINN_LAYOUT_O; gamma->is_const = 0; gamma->quant_channel = 1; beta->dtype = CSINN_DTYPE_INT8; beta->layout = CSINN_LAYOUT_O; beta->is_const = 0; beta->quant_channel = 1; params.base.layout = CSINN_LAYOUT_NHWC; params.epsilon = *(float *)&buffer[1 + input->dim_count]; csi_quantize_multiplier(params.epsilon, &quantized_multiplier, &shift); params.epsilon_multiplier = quantized_multiplier; params.epsilon_shift = shift; params.base.api = CSINN_API; params.base.run_mode = CSINN_RM_LAYER; float *src_in = (float *)(buffer + 2 + input->dim_count); float *mean_in = (float *)(buffer + 2 + input->dim_count + size); float *var_in = (float *)(buffer + 2 + input->dim_count + size + input->dim[input->dim_count - 1]); float *gamma_in = (float *)(buffer + 2 + input->dim_count + size + 2 * input->dim[input->dim_count - 1]); float *beta_in = (float *)(buffer + 2 + input->dim_count + size + 3 * input->dim[input->dim_count - 1]); float *ref = (float *)(buffer + 2 + input->dim_count + size + 4 * input->dim[input->dim_count - 1]); int8_t *input_tmp = malloc(size * sizeof(char)); int8_t *mean_tmp = malloc(input->dim[input->dim_count - 1] * sizeof(char)); int8_t *var_tmp = malloc(input->dim[input->dim_count - 1] * sizeof(char)); int8_t *gamma_tmp = malloc(input->dim[input->dim_count - 1] * sizeof(char)); int8_t *beta_tmp = malloc(input->dim[input->dim_count - 1] * sizeof(char)); input->data = src_in; get_quant_info(input); for(int i = 0; i < size; i++) { input_tmp[i] = csi_ref_quantize_f32_to_i8(src_in[i], input->qinfo); } /* compute the max quantize error */ for(int i = 0; i < size; i++) { float error1; float output_tmp = csi_ref_dequantize_i8_to_f32(src_in[i], input->qinfo); if(isinf(src_in[i]) || isnan(src_in[i])){ continue; } else { error1 = fabs(src_in[i] -output_tmp); if(error1 > 1e-6) { error1 = fabs(src_in[i] - output_tmp)/fabs(src_in[i] + 1e-9); } } if(error1 > error[0]) { error[0] = error1; } } mean->data = mean_in; get_quant_info(mean); for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { mean_tmp[i] = csi_ref_quantize_f32_to_i8(mean_in[i], mean->qinfo); } /* compute the max quantize error */ for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { float error1; float output_tmp = csi_ref_dequantize_i8_to_f32(mean_in[i], mean->qinfo); if(isinf(mean_in[i]) || isnan(mean_in[i])){ continue; } else { error1 = fabs(mean_in[i] -output_tmp); if(error1 > 1e-6) { error1 = fabs(mean_in[i] - output_tmp)/fabs(mean_in[i] + 1e-9); } } if(error1 > error[1]) { error[1] = error1; } } variance->data = var_in; get_quant_info(variance); for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { var_tmp[i] = csi_ref_quantize_f32_to_i8(var_in[i], variance->qinfo); } gamma->data = gamma_in; get_quant_info(gamma); for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { gamma_tmp[i] = csi_ref_quantize_f32_to_i8(gamma_in[i], gamma->qinfo); } /* compute the max quantize error */ for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { float error1; float output_tmp = csi_ref_dequantize_i8_to_f32(mean_in[i], gamma->qinfo); if(isinf(mean_in[i]) || isnan(mean_in[i])){ continue; } else { error1 = fabs(mean_in[i] -output_tmp); if(error1 > 1e-6) { error1 = fabs(mean_in[i] - output_tmp)/fabs(mean_in[i] + 1e-9); } } if(error1 > error[2]) { error[2] = error1; } } max_error = (error[0] + error[1]) * fabs(max_value); beta->data = beta_in; get_quant_info(beta); for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { beta_tmp[i] = csi_ref_quantize_f32_to_i8(beta_in[i], beta->qinfo); } /* compute the max quantize error */ for(int i = 0; i < input->dim[input->dim_count - 1]; i++) { float error1; float output_tmp = csi_ref_dequantize_i8_to_f32(mean_in[i], beta->qinfo); if(isinf(mean_in[i]) || isnan(mean_in[i])){ continue; } else { error1 = fabs(mean_in[i] -output_tmp); if(error1 > 1e-6) { error1 = fabs(mean_in[i] - output_tmp)/fabs(mean_in[i] + 1e-9); } } if(error1 > error[3]) { error[3] = error1; } } max_error += error[3]; output->data = ref; get_quant_info(output); input->data = input_tmp; mean->data = mean_tmp; variance->data = var_tmp; gamma->data = gamma_tmp; beta->data = beta_tmp; reference->data = ref; output->data = malloc(size * sizeof(char)); float difference = argc > 2 ? atof(argv[2]) : 0.9; if (csi_batch_normalization_init(input, mean, variance, gamma, beta, output, &params) == CSINN_TRUE) { csi_batch_normalization(input, mean, variance, gamma, beta, output, &params); } result_verify_8(reference->data, output, input->data, difference, size, false); free(buffer); free(input_tmp); free(mean_tmp); free(var_tmp); free(gamma_tmp); free(beta_tmp); free(output->data); return done_testing(); }
taolinqu/ds4p
DS4P/consent2share/core/src/test/java/gov/samhsa/consent2share/service/account/AccountVerificationServiceImplTest.java
package gov.samhsa.consent2share.service.account; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import javax.mail.MessagingException; import gov.samhsa.consent2share.domain.account.EmailToken; import gov.samhsa.consent2share.domain.account.EmailTokenRepository; import gov.samhsa.consent2share.domain.account.TokenGenerator; import gov.samhsa.consent2share.domain.account.UsersRepository; import gov.samhsa.consent2share.domain.commondomainservices.EmailSender; import gov.samhsa.consent2share.domain.patient.PatientRepository; import gov.samhsa.consent2share.infrastructure.security.TokenExpiredException; import gov.samhsa.consent2share.infrastructure.security.TokenNotExistException; import gov.samhsa.consent2share.infrastructure.security.UsernameNotExistException; import gov.samhsa.consent2share.service.dto.AccountVerificationDto; import org.junit.Before; import org.junit.Test; public class AccountVerificationServiceImplTest { private AccountVerificationServiceImpl sut; private PatientRepository patientRepository; private TokenGenerator tokenGenerator; private Integer accountVerificationTokenExpireInHours; private EmailTokenRepository emailTokenRepository; private EmailSender emailSender; private UsersRepository usersRepository; @Before public void setUp() { // Mock dependencies and create sut // Just to save a few lines of code for each individual test // But independency, clarity of the unit tests are much more important // than code reuse usersRepository = mock(UsersRepository.class); patientRepository = mock(PatientRepository.class); tokenGenerator = mock(TokenGenerator.class); accountVerificationTokenExpireInHours = 8; emailTokenRepository = mock(EmailTokenRepository.class); emailSender = mock(EmailSender.class); sut = new AccountVerificationServiceImpl(usersRepository, patientRepository, tokenGenerator, accountVerificationTokenExpireInHours, emailTokenRepository, emailSender); } @Test(expected = IllegalArgumentException.class) public void testIsEmailTokenExpired_Throws_Exception_When_Token_Has_Whitespaces_Only() throws TokenNotExistException { sut.isAccountVerificationTokenExpired(" "); } @Test(expected = IllegalArgumentException.class) public void testIsEmailTokenExpired_Throws_Exception_When_Token_Is_Null() throws TokenNotExistException { sut.isAccountVerificationTokenExpired(null); } @Test(expected = TokenNotExistException.class) public void testIsEmailTokenExpired_Throws_Exception_When_PasswordToken_Not_Exist() throws TokenNotExistException { // Arrange final String token = "TheToken"; when(emailTokenRepository.findByToken(token)).thenReturn(null); // Act sut.isAccountVerificationTokenExpired(token); } @Test public void testIsEmailTokenExpired_Returns_True_Successfully() throws TokenNotExistException { // Arrange final String token = "TheToken"; EmailToken passwordResetToken = mock(EmailToken.class); when(passwordResetToken.isTokenExpired()).thenReturn(true); when(emailTokenRepository.findByToken(token)).thenReturn( passwordResetToken); // Act Boolean result = sut.isAccountVerificationTokenExpired(token); // Assert assertTrue(result); } @Test public void testIsEmailTokenExpired_Returns_False_Successfully() throws TokenNotExistException { // Arrange final String token = "TheToken"; EmailToken passwordResetToken = mock(EmailToken.class); when(passwordResetToken.isTokenExpired()).thenReturn(false); when(emailTokenRepository.findByToken(token)).thenReturn( passwordResetToken); // Act Boolean result = sut.isAccountVerificationTokenExpired(token); // Assert assertFalse(result); } @Test(expected = IllegalArgumentException.class) public void testEnableAccount_When_Account_Verification_Dto_Is_Null() throws TokenNotExistException, TokenExpiredException, UsernameNotExistException, MessagingException { sut.enableAccount(null, "linkUrl"); } @Test(expected = TokenNotExistException.class) public void testEnableAccount_Expired_Token() throws TokenNotExistException, TokenExpiredException, UsernameNotExistException, MessagingException { AccountVerificationDto accountVerificationDto = mock(AccountVerificationDto.class); sut.enableAccount(accountVerificationDto, "linkUrl"); } }
mP1/walkingkooka-net
src/test/java/walkingkooka/net/http/HttpStatusTest.java
<reponame>mP1/walkingkooka-net /* * Copyright 2019 <NAME> (github.com/mP1) * * 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 walkingkooka.net.http; import org.junit.jupiter.api.Test; import walkingkooka.HashCodeEqualsDefinedTesting2; import walkingkooka.InvalidCharacterException; import walkingkooka.ToStringTesting; import walkingkooka.reflect.ClassTesting2; import walkingkooka.reflect.JavaVisibility; import walkingkooka.text.CharSequences; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; final public class HttpStatusTest implements ClassTesting2<HttpStatus>, HashCodeEqualsDefinedTesting2<HttpStatus>, ToStringTesting<HttpStatus> { // firstLineOfText.................................................................................................. @Test public void testFirstLineOfTextNullFails() { assertThrows(NullPointerException.class, () -> HttpStatus.firstLineOfText(null)); } @Test public void testFirstLineOfTextEmptyString() { this.firstLineOfTextAndCheck(""); } @Test public void testFirstLineOfTextWithoutLineEnding() { this.firstLineOfTextAndCheck("abc123"); } @Test public void testFirstLineOfTextIncludesCr() { this.firstLineOfTextAndCheck("abc\r123", "abc"); } @Test public void testFirstLineOfTextIncludesCrNl() { this.firstLineOfTextAndCheck("abc\r\n123", "abc"); } @Test public void testFirstLineOfTextIncludesNl() { this.firstLineOfTextAndCheck("abc\n123", "abc"); } private void firstLineOfTextAndCheck(final String text) { this.firstLineOfTextAndCheck(text, text); } private void firstLineOfTextAndCheck(final String text, final String first) { this.checkEquals( first, HttpStatus.firstLineOfText(text), () -> CharSequences.escape(text).toString() ); } // constants private final static HttpStatusCode CODE = HttpStatusCode.OK; private final static String MESSAGE = "OK"; @Test public void testWithMessagesIncludeCrFails() { assertThrows(InvalidCharacterException.class, () -> HttpStatus.with(HttpStatusCode.OK, "message\r123")); } @Test public void testWithMessagesIncludeNlFails() { assertThrows(InvalidCharacterException.class, () -> HttpStatus.with(HttpStatusCode.OK, "message\n123")); } @Test public void testWith() { this.check(this.status(), CODE, MESSAGE); } // setCode ................................................................ @Test public void testSetCodeNullFails() { assertThrows(NullPointerException.class, () -> status().setCode(null)); } @Test public void testSetCodeSame() { final HttpStatus status = this.status(); assertSame(status, status.setCode(CODE)); } @Test public void testSetCodeDifferent() { final HttpStatus status = this.status(); final HttpStatusCode code = HttpStatusCode.BAD_REQUEST; final HttpStatus different = status.setCode(code); assertNotSame(status, different); this.check(different, code, MESSAGE); } // setMessage ................................................................ @Test public void testSetMessageNullFails() { assertThrows(NullPointerException.class, () -> status().setMessage(null)); } @Test public void testSetMessageEmptyFails() { assertThrows(IllegalArgumentException.class, () -> status().setMessage("")); } @Test public void testSetMessageSame() { final HttpStatus status = this.status(); assertSame(status, status.setMessage(MESSAGE)); } @Test public void testSetMessageDifferent() { final HttpStatus status = this.status(); final String message = "different"; final HttpStatus different = status.setMessage(message); assertNotSame(status, different); this.check(different, CODE, message); } @Test public void testEqualsNonConstantStatusCode() { final int code = 999; this.checkEquals(HttpStatus.with(HttpStatusCode.withCode(code), MESSAGE), HttpStatus.with(HttpStatusCode.withCode(code), MESSAGE)); } @Test public void testEqualsDifferentCode() { this.checkNotEquals(HttpStatus.with(HttpStatusCode.BAD_GATEWAY, MESSAGE)); } @Test public void testEqualsFoundAndMovedTemporarily() { final HttpStatusCode found = HttpStatusCode.FOUND; final HttpStatusCode movedTemp = HttpStatusCode.MOVED_TEMPORARILY; this.checkEquals(found.code(), movedTemp.code(), "code"); this.checkNotEquals(found, movedTemp, "HttpStatusCode"); this.checkEquals(found.setMessage(MESSAGE), movedTemp.setMessage(MESSAGE)); } @Test public void testEqualsDifferentMessage() { this.checkNotEquals(HttpStatus.with(CODE, "different")); } // helpers .................................. private HttpStatus status() { return HttpStatus.with(CODE, MESSAGE); } private void check(final HttpStatus status, final HttpStatusCode code, final String message) { this.checkEquals(code, status.value(), "value"); this.checkEquals(message, status.message(), "message"); } @Test public void testToString() { this.toStringAndCheck(this.status(), "200 OK"); } @Override public Class<HttpStatus> type() { return HttpStatus.class; } @Override public JavaVisibility typeVisibility() { return JavaVisibility.PUBLIC; } @Override public HttpStatus createObject() { return this.status(); } }
vipcxj/beanknife
beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/AnnotationBeanView.java
<reponame>vipcxj/beanknife package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.DocumentedTypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation2; import io.github.vipcxj.beanknife.cases.annotations.InheritableTypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation2; import io.github.vipcxj.beanknife.cases.annotations.TypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.ValueAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.ValueAnnotation2; import io.github.vipcxj.beanknife.cases.models.AEnum; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = AnnotationBean.class, configClass = AnnotationBeanViewConfigure.class) @InheritableTypeAnnotation( annotation = @ValueAnnotation1(type = { int.class }), annotations = { @ValueAnnotation1(type = { void.class }), @ValueAnnotation1(type = { String.class }), @ValueAnnotation1(type = { int[][][].class }), @ValueAnnotation1(type = { Void.class }), @ValueAnnotation1(type = { Void[].class }) } ) @TypeAnnotation(Date.class) @DocumentedTypeAnnotation( enumValue = AEnum.B, enumValues = { AEnum.C, AEnum.B, AEnum.A } ) public class AnnotationBeanView { @FieldAnnotation1(enumClassArray = { AEnum.class, AEnum.class }) private Class<?> type; @FieldAnnotation1(doubleArray = { 1.0 }) private String a; private String b; @FieldAnnotation1(charValue = '0') @FieldAnnotation2(stringArray = { "5" }) private String[] c; private int d; @PropertyAnnotation2(stringValue = "config_e") private Date e; @PropertyAnnotation2(stringValue = "field_f") private List<String> f; @PropertyAnnotation1(stringValue = "field_g") private short g; public AnnotationBeanView() { } public AnnotationBeanView( Class<?> type, String a, String b, String[] c, int d, Date e, List<String> f, short g ) { this.type = type; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; this.g = g; } public AnnotationBeanView(AnnotationBeanView source) { this.type = source.type; this.a = source.a; this.b = source.b; this.c = source.c; this.d = source.d; this.e = source.e; this.f = source.f; this.g = source.g; } public AnnotationBeanView(AnnotationBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.AnnotationBeanView should not be null."); } this.type = source.type; this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); this.d = source.getD(); this.e = source.getE(); this.f = source.getF(); this.g = source.getG(); } public static AnnotationBeanView read(AnnotationBean source) { if (source == null) { return null; } return new AnnotationBeanView(source); } public static AnnotationBeanView[] read(AnnotationBean[] sources) { if (sources == null) { return null; } AnnotationBeanView[] results = new AnnotationBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<AnnotationBeanView> read(List<AnnotationBean> sources) { if (sources == null) { return null; } List<AnnotationBeanView> results = new ArrayList<>(); for (AnnotationBean source : sources) { results.add(read(source)); } return results; } public static Set<AnnotationBeanView> read(Set<AnnotationBean> sources) { if (sources == null) { return null; } Set<AnnotationBeanView> results = new HashSet<>(); for (AnnotationBean source : sources) { results.add(read(source)); } return results; } public static Stack<AnnotationBeanView> read(Stack<AnnotationBean> sources) { if (sources == null) { return null; } Stack<AnnotationBeanView> results = new Stack<>(); for (AnnotationBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, AnnotationBeanView> read(Map<K, AnnotationBean> sources) { if (sources == null) { return null; } Map<K, AnnotationBeanView> results = new HashMap<>(); for (Map.Entry<K, AnnotationBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public Class<?> getType() { return this.type; } public String getA() { return this.a; } public String getB() { return this.b; } public String[] getC() { return this.c; } @PropertyAnnotation1 @MethodAnnotation1( charValue = 'a', annotations = { @ValueAnnotation1, @ValueAnnotation1(annotations = { @ValueAnnotation2 }) } ) public int getD() { return this.d; } public Date getE() { return this.e; } public List<String> getF() { return this.f; } @PropertyAnnotation1(stringValue = "getter_g") public short getG() { return this.g; } }
godcong/leetcode
code/0132.minCut.go
<reponame>godcong/leetcode<gh_stars>1-10 package code import "math" /* 132. 分割回文串 II 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。 返回符合要求的 最少分割次数 。 示例 1: 输入:s = "aab" 输出:1 解释:只需一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。 示例 2: 输入:s = "a" 输出:0 示例 3: 输入:s = "ab" 输出:1 提示: 1 <= s.length <= 2000 s 仅由小写英文字母组成 */ func minCut(s string) int { n := len(s) g := make([][]bool, n) for i := range g { g[i] = make([]bool, n) for j := range g[i] { g[i][j] = true } } for i := n - 1; i >= 0; i-- { for j := i + 1; j < n; j++ { g[i][j] = s[i] == s[j] && g[i+1][j-1] } } f := make([]int, n) for i := range f { if g[0][i] { continue } f[i] = math.MaxInt64 for j := 0; j < i; j++ { if g[j+1][i] && f[j]+1 < f[i] { f[i] = f[j] + 1 } } } return f[n-1] }
Lokiy/XParser
xparser/src/main/java/com/lokiy/x/db/DBEntryMap.java
/** * Copyright (C) 2014 Luki(<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lokiy.x.db; import android.content.Context; import android.text.TextUtils; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Database entry map. * * @author Luki */ public class DBEntryMap { private static Map<String, DBHelper> helperMap = new HashMap<>(); private static final String DEFAULT_DATABASE_NAME = "xdb"; /** * create a DBHelper. * * @param context context * @param dbName dbName * @return DBHelper */ public static DBHelper getDBHelper(Context context, String dbName) { if (TextUtils.isEmpty(dbName) || TextUtils.isEmpty(dbName.trim())) { dbName = DEFAULT_DATABASE_NAME; } DBHelper dbHelper; if ((dbHelper = helperMap.get(dbName)) == null) { synchronized (DBEntryMap.class) { if (helperMap.get(dbName) == null) { dbHelper = new XDBHelper(dbName, context); helperMap.put(dbName, dbHelper); } } } return dbHelper; } /** * destroy the DBHelper * * @param dbName dbName */ public static void destroy(String dbName) { DBHelper dbHelper = helperMap.remove(dbName); if (dbHelper != null && dbHelper.isOpen()) { dbHelper.close(); } } public static void destroy() { String[] keySet = new String[helperMap.keySet().size()]; helperMap.keySet().toArray(keySet); for (String dbName : keySet) { destroy(dbName); } } }
bingchunjin/1806_SDK
linux-4.14.90-dev/linux-4.14.90/drivers/mmc/host/omap_hsmmc.c
<gh_stars>1-10 /* * drivers/mmc/host/omap_hsmmc.c * * Driver for OMAP2430/3430 MMC controller. * * Copyright (C) 2007 Texas Instruments. * * Authors: * <NAME> <<EMAIL>> * Madhusudhan <<EMAIL>> * <NAME> <<EMAIL>> * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. */ #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/debugfs.h> #include <linux/dmaengine.h> #include <linux/seq_file.h> #include <linux/sizes.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/platform_device.h> #include <linux/timer.h> #include <linux/clk.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_gpio.h> #include <linux/of_device.h> #include <linux/mmc/host.h> #include <linux/mmc/core.h> #include <linux/mmc/mmc.h> #include <linux/mmc/slot-gpio.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/gpio.h> #include <linux/regulator/consumer.h> #include <linux/pinctrl/consumer.h> #include <linux/pm_runtime.h> #include <linux/pm_wakeirq.h> #include <linux/platform_data/hsmmc-omap.h> /* OMAP HSMMC Host Controller Registers */ #define OMAP_HSMMC_SYSSTATUS 0x0014 #define OMAP_HSMMC_CON 0x002C #define OMAP_HSMMC_SDMASA 0x0100 #define OMAP_HSMMC_BLK 0x0104 #define OMAP_HSMMC_ARG 0x0108 #define OMAP_HSMMC_CMD 0x010C #define OMAP_HSMMC_RSP10 0x0110 #define OMAP_HSMMC_RSP32 0x0114 #define OMAP_HSMMC_RSP54 0x0118 #define OMAP_HSMMC_RSP76 0x011C #define OMAP_HSMMC_DATA 0x0120 #define OMAP_HSMMC_PSTATE 0x0124 #define OMAP_HSMMC_HCTL 0x0128 #define OMAP_HSMMC_SYSCTL 0x012C #define OMAP_HSMMC_STAT 0x0130 #define OMAP_HSMMC_IE 0x0134 #define OMAP_HSMMC_ISE 0x0138 #define OMAP_HSMMC_AC12 0x013C #define OMAP_HSMMC_CAPA 0x0140 #define VS18 (1 << 26) #define VS30 (1 << 25) #define HSS (1 << 21) #define SDVS18 (0x5 << 9) #define SDVS30 (0x6 << 9) #define SDVS33 (0x7 << 9) #define SDVS_MASK 0x00000E00 #define SDVSCLR 0xFFFFF1FF #define SDVSDET 0x00000400 #define AUTOIDLE 0x1 #define SDBP (1 << 8) #define DTO 0xe #define ICE 0x1 #define ICS 0x2 #define CEN (1 << 2) #define CLKD_MAX 0x3FF /* max clock divisor: 1023 */ #define CLKD_MASK 0x0000FFC0 #define CLKD_SHIFT 6 #define DTO_MASK 0x000F0000 #define DTO_SHIFT 16 #define INIT_STREAM (1 << 1) #define ACEN_ACMD23 (2 << 2) #define DP_SELECT (1 << 21) #define DDIR (1 << 4) #define DMAE 0x1 #define MSBS (1 << 5) #define BCE (1 << 1) #define FOUR_BIT (1 << 1) #define HSPE (1 << 2) #define IWE (1 << 24) #define DDR (1 << 19) #define CLKEXTFREE (1 << 16) #define CTPL (1 << 11) #define DW8 (1 << 5) #define OD 0x1 #define STAT_CLEAR 0xFFFFFFFF #define INIT_STREAM_CMD 0x00000000 #define DUAL_VOLT_OCR_BIT 7 #define SRC (1 << 25) #define SRD (1 << 26) #define SOFTRESET (1 << 1) /* PSTATE */ #define DLEV_DAT(x) (1 << (20 + (x))) /* Interrupt masks for IE and ISE register */ #define CC_EN (1 << 0) #define TC_EN (1 << 1) #define BWR_EN (1 << 4) #define BRR_EN (1 << 5) #define CIRQ_EN (1 << 8) #define ERR_EN (1 << 15) #define CTO_EN (1 << 16) #define CCRC_EN (1 << 17) #define CEB_EN (1 << 18) #define CIE_EN (1 << 19) #define DTO_EN (1 << 20) #define DCRC_EN (1 << 21) #define DEB_EN (1 << 22) #define ACE_EN (1 << 24) #define CERR_EN (1 << 28) #define BADA_EN (1 << 29) #define INT_EN_MASK (BADA_EN | CERR_EN | ACE_EN | DEB_EN | DCRC_EN |\ DTO_EN | CIE_EN | CEB_EN | CCRC_EN | CTO_EN | \ BRR_EN | BWR_EN | TC_EN | CC_EN) #define CNI (1 << 7) #define ACIE (1 << 4) #define ACEB (1 << 3) #define ACCE (1 << 2) #define ACTO (1 << 1) #define ACNE (1 << 0) #define MMC_AUTOSUSPEND_DELAY 100 #define MMC_TIMEOUT_MS 20 /* 20 mSec */ #define MMC_TIMEOUT_US 20000 /* 20000 micro Sec */ #define OMAP_MMC_MIN_CLOCK 400000 #define OMAP_MMC_MAX_CLOCK 52000000 #define DRIVER_NAME "omap_hsmmc" #define VDD_1V8 1800000 /* 180000 uV */ #define VDD_3V0 3000000 /* 300000 uV */ #define VDD_165_195 (ffs(MMC_VDD_165_195) - 1) /* * One controller can have multiple slots, like on some omap boards using * omap.c controller driver. Luckily this is not currently done on any known * omap_hsmmc.c device. */ #define mmc_pdata(host) host->pdata /* * MMC Host controller read/write API's */ #define OMAP_HSMMC_READ(base, reg) \ __raw_readl((base) + OMAP_HSMMC_##reg) #define OMAP_HSMMC_WRITE(base, reg, val) \ __raw_writel((val), (base) + OMAP_HSMMC_##reg) struct omap_hsmmc_next { unsigned int dma_len; s32 cookie; }; struct omap_hsmmc_host { struct device *dev; struct mmc_host *mmc; struct mmc_request *mrq; struct mmc_command *cmd; struct mmc_data *data; struct clk *fclk; struct clk *dbclk; struct regulator *pbias; bool pbias_enabled; void __iomem *base; int vqmmc_enabled; resource_size_t mapbase; spinlock_t irq_lock; /* Prevent races with irq handler */ unsigned int dma_len; unsigned int dma_sg_idx; unsigned char bus_mode; unsigned char power_mode; int suspended; u32 con; u32 hctl; u32 sysctl; u32 capa; int irq; int wake_irq; int use_dma, dma_ch; struct dma_chan *tx_chan; struct dma_chan *rx_chan; int response_busy; int context_loss; int protect_card; int reqs_blocked; int req_in_progress; unsigned long clk_rate; unsigned int flags; #define AUTO_CMD23 (1 << 0) /* Auto CMD23 support */ #define HSMMC_SDIO_IRQ_ENABLED (1 << 1) /* SDIO irq enabled */ struct omap_hsmmc_next next_data; struct omap_hsmmc_platform_data *pdata; /* return MMC cover switch state, can be NULL if not supported. * * possible return values: * 0 - closed * 1 - open */ int (*get_cover_state)(struct device *dev); int (*card_detect)(struct device *dev); }; struct omap_mmc_of_data { u32 reg_offset; u8 controller_flags; }; static void omap_hsmmc_start_dma_transfer(struct omap_hsmmc_host *host); static int omap_hsmmc_card_detect(struct device *dev) { struct omap_hsmmc_host *host = dev_get_drvdata(dev); return mmc_gpio_get_cd(host->mmc); } static int omap_hsmmc_get_cover_state(struct device *dev) { struct omap_hsmmc_host *host = dev_get_drvdata(dev); return mmc_gpio_get_cd(host->mmc); } static int omap_hsmmc_enable_supply(struct mmc_host *mmc) { int ret; struct omap_hsmmc_host *host = mmc_priv(mmc); struct mmc_ios *ios = &mmc->ios; if (!IS_ERR(mmc->supply.vmmc)) { ret = mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, ios->vdd); if (ret) return ret; } /* Enable interface voltage rail, if needed */ if (!IS_ERR(mmc->supply.vqmmc) && !host->vqmmc_enabled) { ret = regulator_enable(mmc->supply.vqmmc); if (ret) { dev_err(mmc_dev(mmc), "vmmc_aux reg enable failed\n"); goto err_vqmmc; } host->vqmmc_enabled = 1; } return 0; err_vqmmc: if (!IS_ERR(mmc->supply.vmmc)) mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0); return ret; } static int omap_hsmmc_disable_supply(struct mmc_host *mmc) { int ret; int status; struct omap_hsmmc_host *host = mmc_priv(mmc); if (!IS_ERR(mmc->supply.vqmmc) && host->vqmmc_enabled) { ret = regulator_disable(mmc->supply.vqmmc); if (ret) { dev_err(mmc_dev(mmc), "vmmc_aux reg disable failed\n"); return ret; } host->vqmmc_enabled = 0; } if (!IS_ERR(mmc->supply.vmmc)) { ret = mmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0); if (ret) goto err_set_ocr; } return 0; err_set_ocr: if (!IS_ERR(mmc->supply.vqmmc)) { status = regulator_enable(mmc->supply.vqmmc); if (status) dev_err(mmc_dev(mmc), "vmmc_aux re-enable failed\n"); } return ret; } static int omap_hsmmc_set_pbias(struct omap_hsmmc_host *host, bool power_on, int vdd) { int ret; if (IS_ERR(host->pbias)) return 0; if (power_on) { if (vdd <= VDD_165_195) ret = regulator_set_voltage(host->pbias, VDD_1V8, VDD_1V8); else ret = regulator_set_voltage(host->pbias, VDD_3V0, VDD_3V0); if (ret < 0) { dev_err(host->dev, "pbias set voltage fail\n"); return ret; } if (host->pbias_enabled == 0) { ret = regulator_enable(host->pbias); if (ret) { dev_err(host->dev, "pbias reg enable fail\n"); return ret; } host->pbias_enabled = 1; } } else { if (host->pbias_enabled == 1) { ret = regulator_disable(host->pbias); if (ret) { dev_err(host->dev, "pbias reg disable fail\n"); return ret; } host->pbias_enabled = 0; } } return 0; } static int omap_hsmmc_set_power(struct omap_hsmmc_host *host, int power_on, int vdd) { struct mmc_host *mmc = host->mmc; int ret = 0; /* * If we don't see a Vcc regulator, assume it's a fixed * voltage always-on regulator. */ if (IS_ERR(mmc->supply.vmmc)) return 0; ret = omap_hsmmc_set_pbias(host, false, 0); if (ret) return ret; /* * Assume Vcc regulator is used only to power the card ... OMAP * VDDS is used to power the pins, optionally with a transceiver to * support cards using voltages other than VDDS (1.8V nominal). When a * transceiver is used, DAT3..7 are muxed as transceiver control pins. * * In some cases this regulator won't support enable/disable; * e.g. it's a fixed rail for a WLAN chip. * * In other cases vcc_aux switches interface power. Example, for * eMMC cards it represents VccQ. Sometimes transceivers or SDIO * chips/cards need an interface voltage rail too. */ if (power_on) { ret = omap_hsmmc_enable_supply(mmc); if (ret) return ret; ret = omap_hsmmc_set_pbias(host, true, vdd); if (ret) goto err_set_voltage; } else { ret = omap_hsmmc_disable_supply(mmc); if (ret) return ret; } return 0; err_set_voltage: omap_hsmmc_disable_supply(mmc); return ret; } static int omap_hsmmc_disable_boot_regulator(struct regulator *reg) { int ret; if (IS_ERR(reg)) return 0; if (regulator_is_enabled(reg)) { ret = regulator_enable(reg); if (ret) return ret; ret = regulator_disable(reg); if (ret) return ret; } return 0; } static int omap_hsmmc_disable_boot_regulators(struct omap_hsmmc_host *host) { struct mmc_host *mmc = host->mmc; int ret; /* * disable regulators enabled during boot and get the usecount * right so that regulators can be enabled/disabled by checking * the return value of regulator_is_enabled */ ret = omap_hsmmc_disable_boot_regulator(mmc->supply.vmmc); if (ret) { dev_err(host->dev, "fail to disable boot enabled vmmc reg\n"); return ret; } ret = omap_hsmmc_disable_boot_regulator(mmc->supply.vqmmc); if (ret) { dev_err(host->dev, "fail to disable boot enabled vmmc_aux reg\n"); return ret; } ret = omap_hsmmc_disable_boot_regulator(host->pbias); if (ret) { dev_err(host->dev, "failed to disable boot enabled pbias reg\n"); return ret; } return 0; } static int omap_hsmmc_reg_get(struct omap_hsmmc_host *host) { int ret; struct mmc_host *mmc = host->mmc; ret = mmc_regulator_get_supply(mmc); if (ret == -EPROBE_DEFER) return ret; /* Allow an aux regulator */ if (IS_ERR(mmc->supply.vqmmc)) { mmc->supply.vqmmc = devm_regulator_get_optional(host->dev, "vmmc_aux"); if (IS_ERR(mmc->supply.vqmmc)) { ret = PTR_ERR(mmc->supply.vqmmc); if ((ret != -ENODEV) && host->dev->of_node) return ret; dev_dbg(host->dev, "unable to get vmmc_aux regulator %ld\n", PTR_ERR(mmc->supply.vqmmc)); } } host->pbias = devm_regulator_get_optional(host->dev, "pbias"); if (IS_ERR(host->pbias)) { ret = PTR_ERR(host->pbias); if ((ret != -ENODEV) && host->dev->of_node) { dev_err(host->dev, "SD card detect fail? enable CONFIG_REGULATOR_PBIAS\n"); return ret; } dev_dbg(host->dev, "unable to get pbias regulator %ld\n", PTR_ERR(host->pbias)); } /* For eMMC do not power off when not in sleep state */ if (mmc_pdata(host)->no_regulator_off_init) return 0; ret = omap_hsmmc_disable_boot_regulators(host); if (ret) return ret; return 0; } static irqreturn_t omap_hsmmc_cover_irq(int irq, void *dev_id); static int omap_hsmmc_gpio_init(struct mmc_host *mmc, struct omap_hsmmc_host *host, struct omap_hsmmc_platform_data *pdata) { int ret; if (gpio_is_valid(pdata->gpio_cod)) { ret = mmc_gpio_request_cd(mmc, pdata->gpio_cod, 0); if (ret) return ret; host->get_cover_state = omap_hsmmc_get_cover_state; mmc_gpio_set_cd_isr(mmc, omap_hsmmc_cover_irq); } else if (gpio_is_valid(pdata->gpio_cd)) { ret = mmc_gpio_request_cd(mmc, pdata->gpio_cd, 0); if (ret) return ret; host->card_detect = omap_hsmmc_card_detect; } if (gpio_is_valid(pdata->gpio_wp)) { ret = mmc_gpio_request_ro(mmc, pdata->gpio_wp); if (ret) return ret; } return 0; } /* * Start clock to the card */ static void omap_hsmmc_start_clock(struct omap_hsmmc_host *host) { OMAP_HSMMC_WRITE(host->base, SYSCTL, OMAP_HSMMC_READ(host->base, SYSCTL) | CEN); } /* * Stop clock to the card */ static void omap_hsmmc_stop_clock(struct omap_hsmmc_host *host) { OMAP_HSMMC_WRITE(host->base, SYSCTL, OMAP_HSMMC_READ(host->base, SYSCTL) & ~CEN); if ((OMAP_HSMMC_READ(host->base, SYSCTL) & CEN) != 0x0) dev_dbg(mmc_dev(host->mmc), "MMC Clock is not stopped\n"); } static void omap_hsmmc_enable_irq(struct omap_hsmmc_host *host, struct mmc_command *cmd) { u32 irq_mask = INT_EN_MASK; unsigned long flags; if (host->use_dma) irq_mask &= ~(BRR_EN | BWR_EN); /* Disable timeout for erases */ if (cmd->opcode == MMC_ERASE) irq_mask &= ~DTO_EN; spin_lock_irqsave(&host->irq_lock, flags); OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); OMAP_HSMMC_WRITE(host->base, ISE, irq_mask); /* latch pending CIRQ, but don't signal MMC core */ if (host->flags & HSMMC_SDIO_IRQ_ENABLED) irq_mask |= CIRQ_EN; OMAP_HSMMC_WRITE(host->base, IE, irq_mask); spin_unlock_irqrestore(&host->irq_lock, flags); } static void omap_hsmmc_disable_irq(struct omap_hsmmc_host *host) { u32 irq_mask = 0; unsigned long flags; spin_lock_irqsave(&host->irq_lock, flags); /* no transfer running but need to keep cirq if enabled */ if (host->flags & HSMMC_SDIO_IRQ_ENABLED) irq_mask |= CIRQ_EN; OMAP_HSMMC_WRITE(host->base, ISE, irq_mask); OMAP_HSMMC_WRITE(host->base, IE, irq_mask); OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); spin_unlock_irqrestore(&host->irq_lock, flags); } /* Calculate divisor for the given clock frequency */ static u16 calc_divisor(struct omap_hsmmc_host *host, struct mmc_ios *ios) { u16 dsor = 0; if (ios->clock) { dsor = DIV_ROUND_UP(clk_get_rate(host->fclk), ios->clock); if (dsor > CLKD_MAX) dsor = CLKD_MAX; } return dsor; } static void omap_hsmmc_set_clock(struct omap_hsmmc_host *host) { struct mmc_ios *ios = &host->mmc->ios; unsigned long regval; unsigned long timeout; unsigned long clkdiv; dev_vdbg(mmc_dev(host->mmc), "Set clock to %uHz\n", ios->clock); omap_hsmmc_stop_clock(host); regval = OMAP_HSMMC_READ(host->base, SYSCTL); regval = regval & ~(CLKD_MASK | DTO_MASK); clkdiv = calc_divisor(host, ios); regval = regval | (clkdiv << 6) | (DTO << 16); OMAP_HSMMC_WRITE(host->base, SYSCTL, regval); OMAP_HSMMC_WRITE(host->base, SYSCTL, OMAP_HSMMC_READ(host->base, SYSCTL) | ICE); /* Wait till the ICS bit is set */ timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS); while ((OMAP_HSMMC_READ(host->base, SYSCTL) & ICS) != ICS && time_before(jiffies, timeout)) cpu_relax(); /* * Enable High-Speed Support * Pre-Requisites * - Controller should support High-Speed-Enable Bit * - Controller should not be using DDR Mode * - Controller should advertise that it supports High Speed * in capabilities register * - MMC/SD clock coming out of controller > 25MHz */ if ((mmc_pdata(host)->features & HSMMC_HAS_HSPE_SUPPORT) && (ios->timing != MMC_TIMING_MMC_DDR52) && (ios->timing != MMC_TIMING_UHS_DDR50) && ((OMAP_HSMMC_READ(host->base, CAPA) & HSS) == HSS)) { regval = OMAP_HSMMC_READ(host->base, HCTL); if (clkdiv && (clk_get_rate(host->fclk)/clkdiv) > 25000000) regval |= HSPE; else regval &= ~HSPE; OMAP_HSMMC_WRITE(host->base, HCTL, regval); } omap_hsmmc_start_clock(host); } static void omap_hsmmc_set_bus_width(struct omap_hsmmc_host *host) { struct mmc_ios *ios = &host->mmc->ios; u32 con; con = OMAP_HSMMC_READ(host->base, CON); if (ios->timing == MMC_TIMING_MMC_DDR52 || ios->timing == MMC_TIMING_UHS_DDR50) con |= DDR; /* configure in DDR mode */ else con &= ~DDR; switch (ios->bus_width) { case MMC_BUS_WIDTH_8: OMAP_HSMMC_WRITE(host->base, CON, con | DW8); break; case MMC_BUS_WIDTH_4: OMAP_HSMMC_WRITE(host->base, CON, con & ~DW8); OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) | FOUR_BIT); break; case MMC_BUS_WIDTH_1: OMAP_HSMMC_WRITE(host->base, CON, con & ~DW8); OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) & ~FOUR_BIT); break; } } static void omap_hsmmc_set_bus_mode(struct omap_hsmmc_host *host) { struct mmc_ios *ios = &host->mmc->ios; u32 con; con = OMAP_HSMMC_READ(host->base, CON); if (ios->bus_mode == MMC_BUSMODE_OPENDRAIN) OMAP_HSMMC_WRITE(host->base, CON, con | OD); else OMAP_HSMMC_WRITE(host->base, CON, con & ~OD); } #ifdef CONFIG_PM /* * Restore the MMC host context, if it was lost as result of a * power state change. */ static int omap_hsmmc_context_restore(struct omap_hsmmc_host *host) { struct mmc_ios *ios = &host->mmc->ios; u32 hctl, capa; unsigned long timeout; if (host->con == OMAP_HSMMC_READ(host->base, CON) && host->hctl == OMAP_HSMMC_READ(host->base, HCTL) && host->sysctl == OMAP_HSMMC_READ(host->base, SYSCTL) && host->capa == OMAP_HSMMC_READ(host->base, CAPA)) return 0; host->context_loss++; if (host->pdata->controller_flags & OMAP_HSMMC_SUPPORTS_DUAL_VOLT) { if (host->power_mode != MMC_POWER_OFF && (1 << ios->vdd) <= MMC_VDD_23_24) hctl = SDVS18; else hctl = SDVS30; capa = VS30 | VS18; } else { hctl = SDVS18; capa = VS18; } if (host->mmc->caps & MMC_CAP_SDIO_IRQ) hctl |= IWE; OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) | hctl); OMAP_HSMMC_WRITE(host->base, CAPA, OMAP_HSMMC_READ(host->base, CAPA) | capa); OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) | SDBP); timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS); while ((OMAP_HSMMC_READ(host->base, HCTL) & SDBP) != SDBP && time_before(jiffies, timeout)) ; OMAP_HSMMC_WRITE(host->base, ISE, 0); OMAP_HSMMC_WRITE(host->base, IE, 0); OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); /* Do not initialize card-specific things if the power is off */ if (host->power_mode == MMC_POWER_OFF) goto out; omap_hsmmc_set_bus_width(host); omap_hsmmc_set_clock(host); omap_hsmmc_set_bus_mode(host); out: dev_dbg(mmc_dev(host->mmc), "context is restored: restore count %d\n", host->context_loss); return 0; } /* * Save the MMC host context (store the number of power state changes so far). */ static void omap_hsmmc_context_save(struct omap_hsmmc_host *host) { host->con = OMAP_HSMMC_READ(host->base, CON); host->hctl = OMAP_HSMMC_READ(host->base, HCTL); host->sysctl = OMAP_HSMMC_READ(host->base, SYSCTL); host->capa = OMAP_HSMMC_READ(host->base, CAPA); } #else static int omap_hsmmc_context_restore(struct omap_hsmmc_host *host) { return 0; } static void omap_hsmmc_context_save(struct omap_hsmmc_host *host) { } #endif /* * Send init stream sequence to card * before sending IDLE command */ static void send_init_stream(struct omap_hsmmc_host *host) { int reg = 0; unsigned long timeout; if (host->protect_card) return; disable_irq(host->irq); OMAP_HSMMC_WRITE(host->base, IE, INT_EN_MASK); OMAP_HSMMC_WRITE(host->base, CON, OMAP_HSMMC_READ(host->base, CON) | INIT_STREAM); OMAP_HSMMC_WRITE(host->base, CMD, INIT_STREAM_CMD); timeout = jiffies + msecs_to_jiffies(MMC_TIMEOUT_MS); while ((reg != CC_EN) && time_before(jiffies, timeout)) reg = OMAP_HSMMC_READ(host->base, STAT) & CC_EN; OMAP_HSMMC_WRITE(host->base, CON, OMAP_HSMMC_READ(host->base, CON) & ~INIT_STREAM); OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); OMAP_HSMMC_READ(host->base, STAT); enable_irq(host->irq); } static inline int omap_hsmmc_cover_is_closed(struct omap_hsmmc_host *host) { int r = 1; if (host->get_cover_state) r = host->get_cover_state(host->dev); return r; } static ssize_t omap_hsmmc_show_cover_switch(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_host *mmc = container_of(dev, struct mmc_host, class_dev); struct omap_hsmmc_host *host = mmc_priv(mmc); return sprintf(buf, "%s\n", omap_hsmmc_cover_is_closed(host) ? "closed" : "open"); } static DEVICE_ATTR(cover_switch, S_IRUGO, omap_hsmmc_show_cover_switch, NULL); static ssize_t omap_hsmmc_show_slot_name(struct device *dev, struct device_attribute *attr, char *buf) { struct mmc_host *mmc = container_of(dev, struct mmc_host, class_dev); struct omap_hsmmc_host *host = mmc_priv(mmc); return sprintf(buf, "%s\n", mmc_pdata(host)->name); } static DEVICE_ATTR(slot_name, S_IRUGO, omap_hsmmc_show_slot_name, NULL); /* * Configure the response type and send the cmd. */ static void omap_hsmmc_start_command(struct omap_hsmmc_host *host, struct mmc_command *cmd, struct mmc_data *data) { int cmdreg = 0, resptype = 0, cmdtype = 0; dev_vdbg(mmc_dev(host->mmc), "%s: CMD%d, argument 0x%08x\n", mmc_hostname(host->mmc), cmd->opcode, cmd->arg); host->cmd = cmd; omap_hsmmc_enable_irq(host, cmd); host->response_busy = 0; if (cmd->flags & MMC_RSP_PRESENT) { if (cmd->flags & MMC_RSP_136) resptype = 1; else if (cmd->flags & MMC_RSP_BUSY) { resptype = 3; host->response_busy = 1; } else resptype = 2; } /* * Unlike OMAP1 controller, the cmdtype does not seem to be based on * ac, bc, adtc, bcr. Only commands ending an open ended transfer need * a val of 0x3, rest 0x0. */ if (cmd == host->mrq->stop) cmdtype = 0x3; cmdreg = (cmd->opcode << 24) | (resptype << 16) | (cmdtype << 22); if ((host->flags & AUTO_CMD23) && mmc_op_multi(cmd->opcode) && host->mrq->sbc) { cmdreg |= ACEN_ACMD23; OMAP_HSMMC_WRITE(host->base, SDMASA, host->mrq->sbc->arg); } if (data) { cmdreg |= DP_SELECT | MSBS | BCE; if (data->flags & MMC_DATA_READ) cmdreg |= DDIR; else cmdreg &= ~(DDIR); } if (host->use_dma) cmdreg |= DMAE; host->req_in_progress = 1; OMAP_HSMMC_WRITE(host->base, ARG, cmd->arg); OMAP_HSMMC_WRITE(host->base, CMD, cmdreg); } static struct dma_chan *omap_hsmmc_get_dma_chan(struct omap_hsmmc_host *host, struct mmc_data *data) { return data->flags & MMC_DATA_WRITE ? host->tx_chan : host->rx_chan; } static void omap_hsmmc_request_done(struct omap_hsmmc_host *host, struct mmc_request *mrq) { int dma_ch; unsigned long flags; spin_lock_irqsave(&host->irq_lock, flags); host->req_in_progress = 0; dma_ch = host->dma_ch; spin_unlock_irqrestore(&host->irq_lock, flags); omap_hsmmc_disable_irq(host); /* Do not complete the request if DMA is still in progress */ if (mrq->data && host->use_dma && dma_ch != -1) return; host->mrq = NULL; mmc_request_done(host->mmc, mrq); } /* * Notify the transfer complete to MMC core */ static void omap_hsmmc_xfer_done(struct omap_hsmmc_host *host, struct mmc_data *data) { if (!data) { struct mmc_request *mrq = host->mrq; /* TC before CC from CMD6 - don't know why, but it happens */ if (host->cmd && host->cmd->opcode == 6 && host->response_busy) { host->response_busy = 0; return; } omap_hsmmc_request_done(host, mrq); return; } host->data = NULL; if (!data->error) data->bytes_xfered += data->blocks * (data->blksz); else data->bytes_xfered = 0; if (data->stop && (data->error || !host->mrq->sbc)) omap_hsmmc_start_command(host, data->stop, NULL); else omap_hsmmc_request_done(host, data->mrq); } /* * Notify the core about command completion */ static void omap_hsmmc_cmd_done(struct omap_hsmmc_host *host, struct mmc_command *cmd) { if (host->mrq->sbc && (host->cmd == host->mrq->sbc) && !host->mrq->sbc->error && !(host->flags & AUTO_CMD23)) { host->cmd = NULL; omap_hsmmc_start_dma_transfer(host); omap_hsmmc_start_command(host, host->mrq->cmd, host->mrq->data); return; } host->cmd = NULL; if (cmd->flags & MMC_RSP_PRESENT) { if (cmd->flags & MMC_RSP_136) { /* response type 2 */ cmd->resp[3] = OMAP_HSMMC_READ(host->base, RSP10); cmd->resp[2] = OMAP_HSMMC_READ(host->base, RSP32); cmd->resp[1] = OMAP_HSMMC_READ(host->base, RSP54); cmd->resp[0] = OMAP_HSMMC_READ(host->base, RSP76); } else { /* response types 1, 1b, 3, 4, 5, 6 */ cmd->resp[0] = OMAP_HSMMC_READ(host->base, RSP10); } } if ((host->data == NULL && !host->response_busy) || cmd->error) omap_hsmmc_request_done(host, host->mrq); } /* * DMA clean up for command errors */ static void omap_hsmmc_dma_cleanup(struct omap_hsmmc_host *host, int errno) { int dma_ch; unsigned long flags; host->data->error = errno; spin_lock_irqsave(&host->irq_lock, flags); dma_ch = host->dma_ch; host->dma_ch = -1; spin_unlock_irqrestore(&host->irq_lock, flags); if (host->use_dma && dma_ch != -1) { struct dma_chan *chan = omap_hsmmc_get_dma_chan(host, host->data); dmaengine_terminate_all(chan); dma_unmap_sg(chan->device->dev, host->data->sg, host->data->sg_len, mmc_get_dma_dir(host->data)); host->data->host_cookie = 0; } host->data = NULL; } /* * Readable error output */ #ifdef CONFIG_MMC_DEBUG static void omap_hsmmc_dbg_report_irq(struct omap_hsmmc_host *host, u32 status) { /* --- means reserved bit without definition at documentation */ static const char *omap_hsmmc_status_bits[] = { "CC" , "TC" , "BGE", "---", "BWR" , "BRR" , "---" , "---" , "CIRQ", "OBI" , "---", "---", "---" , "---" , "---" , "ERRI", "CTO" , "CCRC", "CEB", "CIE", "DTO" , "DCRC", "DEB" , "---" , "ACE" , "---" , "---", "---", "CERR", "BADA", "---" , "---" }; char res[256]; char *buf = res; int len, i; len = sprintf(buf, "MMC IRQ 0x%x :", status); buf += len; for (i = 0; i < ARRAY_SIZE(omap_hsmmc_status_bits); i++) if (status & (1 << i)) { len = sprintf(buf, " %s", omap_hsmmc_status_bits[i]); buf += len; } dev_vdbg(mmc_dev(host->mmc), "%s\n", res); } #else static inline void omap_hsmmc_dbg_report_irq(struct omap_hsmmc_host *host, u32 status) { } #endif /* CONFIG_MMC_DEBUG */ /* * MMC controller internal state machines reset * * Used to reset command or data internal state machines, using respectively * SRC or SRD bit of SYSCTL register * Can be called from interrupt context */ static inline void omap_hsmmc_reset_controller_fsm(struct omap_hsmmc_host *host, unsigned long bit) { unsigned long i = 0; unsigned long limit = MMC_TIMEOUT_US; OMAP_HSMMC_WRITE(host->base, SYSCTL, OMAP_HSMMC_READ(host->base, SYSCTL) | bit); /* * OMAP4 ES2 and greater has an updated reset logic. * Monitor a 0->1 transition first */ if (mmc_pdata(host)->features & HSMMC_HAS_UPDATED_RESET) { while ((!(OMAP_HSMMC_READ(host->base, SYSCTL) & bit)) && (i++ < limit)) udelay(1); } i = 0; while ((OMAP_HSMMC_READ(host->base, SYSCTL) & bit) && (i++ < limit)) udelay(1); if (OMAP_HSMMC_READ(host->base, SYSCTL) & bit) dev_err(mmc_dev(host->mmc), "Timeout waiting on controller reset in %s\n", __func__); } static void hsmmc_command_incomplete(struct omap_hsmmc_host *host, int err, int end_cmd) { if (end_cmd) { omap_hsmmc_reset_controller_fsm(host, SRC); if (host->cmd) host->cmd->error = err; } if (host->data) { omap_hsmmc_reset_controller_fsm(host, SRD); omap_hsmmc_dma_cleanup(host, err); } else if (host->mrq && host->mrq->cmd) host->mrq->cmd->error = err; } static void omap_hsmmc_do_irq(struct omap_hsmmc_host *host, int status) { struct mmc_data *data; int end_cmd = 0, end_trans = 0; int error = 0; data = host->data; dev_vdbg(mmc_dev(host->mmc), "IRQ Status is %x\n", status); if (status & ERR_EN) { omap_hsmmc_dbg_report_irq(host, status); if (status & (CTO_EN | CCRC_EN | CEB_EN)) end_cmd = 1; if (host->data || host->response_busy) { end_trans = !end_cmd; host->response_busy = 0; } if (status & (CTO_EN | DTO_EN)) hsmmc_command_incomplete(host, -ETIMEDOUT, end_cmd); else if (status & (CCRC_EN | DCRC_EN | DEB_EN | CEB_EN | BADA_EN)) hsmmc_command_incomplete(host, -EILSEQ, end_cmd); if (status & ACE_EN) { u32 ac12; ac12 = OMAP_HSMMC_READ(host->base, AC12); if (!(ac12 & ACNE) && host->mrq->sbc) { end_cmd = 1; if (ac12 & ACTO) error = -ETIMEDOUT; else if (ac12 & (ACCE | ACEB | ACIE)) error = -EILSEQ; host->mrq->sbc->error = error; hsmmc_command_incomplete(host, error, end_cmd); } dev_dbg(mmc_dev(host->mmc), "AC12 err: 0x%x\n", ac12); } } OMAP_HSMMC_WRITE(host->base, STAT, status); if (end_cmd || ((status & CC_EN) && host->cmd)) omap_hsmmc_cmd_done(host, host->cmd); if ((end_trans || (status & TC_EN)) && host->mrq) omap_hsmmc_xfer_done(host, data); } /* * MMC controller IRQ handler */ static irqreturn_t omap_hsmmc_irq(int irq, void *dev_id) { struct omap_hsmmc_host *host = dev_id; int status; status = OMAP_HSMMC_READ(host->base, STAT); while (status & (INT_EN_MASK | CIRQ_EN)) { if (host->req_in_progress) omap_hsmmc_do_irq(host, status); if (status & CIRQ_EN) mmc_signal_sdio_irq(host->mmc); /* Flush posted write */ status = OMAP_HSMMC_READ(host->base, STAT); } return IRQ_HANDLED; } static void set_sd_bus_power(struct omap_hsmmc_host *host) { unsigned long i; OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) | SDBP); for (i = 0; i < loops_per_jiffy; i++) { if (OMAP_HSMMC_READ(host->base, HCTL) & SDBP) break; cpu_relax(); } } /* * Switch MMC interface voltage ... only relevant for MMC1. * * MMC2 and MMC3 use fixed 1.8V levels, and maybe a transceiver. * The MMC2 transceiver controls are used instead of DAT4..DAT7. * Some chips, like eMMC ones, use internal transceivers. */ static int omap_hsmmc_switch_opcond(struct omap_hsmmc_host *host, int vdd) { u32 reg_val = 0; int ret; /* Disable the clocks */ if (host->dbclk) clk_disable_unprepare(host->dbclk); /* Turn the power off */ ret = omap_hsmmc_set_power(host, 0, 0); /* Turn the power ON with given VDD 1.8 or 3.0v */ if (!ret) ret = omap_hsmmc_set_power(host, 1, vdd); if (host->dbclk) clk_prepare_enable(host->dbclk); if (ret != 0) goto err; OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) & SDVSCLR); reg_val = OMAP_HSMMC_READ(host->base, HCTL); /* * If a MMC dual voltage card is detected, the set_ios fn calls * this fn with VDD bit set for 1.8V. Upon card removal from the * slot, omap_hsmmc_set_ios sets the VDD back to 3V on MMC_POWER_OFF. * * Cope with a bit of slop in the range ... per data sheets: * - "1.8V" for vdds_mmc1/vdds_mmc1a can be up to 2.45V max, * but recommended values are 1.71V to 1.89V * - "3.0V" for vdds_mmc1/vdds_mmc1a can be up to 3.5V max, * but recommended values are 2.7V to 3.3V * * Board setup code shouldn't permit anything very out-of-range. * TWL4030-family VMMC1 and VSIM regulators are fine (avoiding the * middle range) but VSIM can't power DAT4..DAT7 at more than 3V. */ if ((1 << vdd) <= MMC_VDD_23_24) reg_val |= SDVS18; else reg_val |= SDVS30; OMAP_HSMMC_WRITE(host->base, HCTL, reg_val); set_sd_bus_power(host); return 0; err: dev_err(mmc_dev(host->mmc), "Unable to switch operating voltage\n"); return ret; } /* Protect the card while the cover is open */ static void omap_hsmmc_protect_card(struct omap_hsmmc_host *host) { if (!host->get_cover_state) return; host->reqs_blocked = 0; if (host->get_cover_state(host->dev)) { if (host->protect_card) { dev_info(host->dev, "%s: cover is closed, " "card is now accessible\n", mmc_hostname(host->mmc)); host->protect_card = 0; } } else { if (!host->protect_card) { dev_info(host->dev, "%s: cover is open, " "card is now inaccessible\n", mmc_hostname(host->mmc)); host->protect_card = 1; } } } /* * irq handler when (cell-phone) cover is mounted/removed */ static irqreturn_t omap_hsmmc_cover_irq(int irq, void *dev_id) { struct omap_hsmmc_host *host = dev_id; sysfs_notify(&host->mmc->class_dev.kobj, NULL, "cover_switch"); omap_hsmmc_protect_card(host); mmc_detect_change(host->mmc, (HZ * 200) / 1000); return IRQ_HANDLED; } static void omap_hsmmc_dma_callback(void *param) { struct omap_hsmmc_host *host = param; struct dma_chan *chan; struct mmc_data *data; int req_in_progress; spin_lock_irq(&host->irq_lock); if (host->dma_ch < 0) { spin_unlock_irq(&host->irq_lock); return; } data = host->mrq->data; chan = omap_hsmmc_get_dma_chan(host, data); if (!data->host_cookie) dma_unmap_sg(chan->device->dev, data->sg, data->sg_len, mmc_get_dma_dir(data)); req_in_progress = host->req_in_progress; host->dma_ch = -1; spin_unlock_irq(&host->irq_lock); /* If DMA has finished after TC, complete the request */ if (!req_in_progress) { struct mmc_request *mrq = host->mrq; host->mrq = NULL; mmc_request_done(host->mmc, mrq); } } static int omap_hsmmc_pre_dma_transfer(struct omap_hsmmc_host *host, struct mmc_data *data, struct omap_hsmmc_next *next, struct dma_chan *chan) { int dma_len; if (!next && data->host_cookie && data->host_cookie != host->next_data.cookie) { dev_warn(host->dev, "[%s] invalid cookie: data->host_cookie %d" " host->next_data.cookie %d\n", __func__, data->host_cookie, host->next_data.cookie); data->host_cookie = 0; } /* Check if next job is already prepared */ if (next || data->host_cookie != host->next_data.cookie) { dma_len = dma_map_sg(chan->device->dev, data->sg, data->sg_len, mmc_get_dma_dir(data)); } else { dma_len = host->next_data.dma_len; host->next_data.dma_len = 0; } if (dma_len == 0) return -EINVAL; if (next) { next->dma_len = dma_len; data->host_cookie = ++next->cookie < 0 ? 1 : next->cookie; } else host->dma_len = dma_len; return 0; } /* * Routine to configure and start DMA for the MMC card */ static int omap_hsmmc_setup_dma_transfer(struct omap_hsmmc_host *host, struct mmc_request *req) { struct dma_async_tx_descriptor *tx; int ret = 0, i; struct mmc_data *data = req->data; struct dma_chan *chan; struct dma_slave_config cfg = { .src_addr = host->mapbase + OMAP_HSMMC_DATA, .dst_addr = host->mapbase + OMAP_HSMMC_DATA, .src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES, .dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES, .src_maxburst = data->blksz / 4, .dst_maxburst = data->blksz / 4, }; /* Sanity check: all the SG entries must be aligned by block size. */ for (i = 0; i < data->sg_len; i++) { struct scatterlist *sgl; sgl = data->sg + i; if (sgl->length % data->blksz) return -EINVAL; } if ((data->blksz % 4) != 0) /* REVISIT: The MMC buffer increments only when MSB is written. * Return error for blksz which is non multiple of four. */ return -EINVAL; BUG_ON(host->dma_ch != -1); chan = omap_hsmmc_get_dma_chan(host, data); ret = dmaengine_slave_config(chan, &cfg); if (ret) return ret; ret = omap_hsmmc_pre_dma_transfer(host, data, NULL, chan); if (ret) return ret; tx = dmaengine_prep_slave_sg(chan, data->sg, data->sg_len, data->flags & MMC_DATA_WRITE ? DMA_MEM_TO_DEV : DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!tx) { dev_err(mmc_dev(host->mmc), "prep_slave_sg() failed\n"); /* FIXME: cleanup */ return -1; } tx->callback = omap_hsmmc_dma_callback; tx->callback_param = host; /* Does not fail */ dmaengine_submit(tx); host->dma_ch = 1; return 0; } static void set_data_timeout(struct omap_hsmmc_host *host, unsigned long long timeout_ns, unsigned int timeout_clks) { unsigned long long timeout = timeout_ns; unsigned int cycle_ns; uint32_t reg, clkd, dto = 0; reg = OMAP_HSMMC_READ(host->base, SYSCTL); clkd = (reg & CLKD_MASK) >> CLKD_SHIFT; if (clkd == 0) clkd = 1; cycle_ns = 1000000000 / (host->clk_rate / clkd); do_div(timeout, cycle_ns); timeout += timeout_clks; if (timeout) { while ((timeout & 0x80000000) == 0) { dto += 1; timeout <<= 1; } dto = 31 - dto; timeout <<= 1; if (timeout && dto) dto += 1; if (dto >= 13) dto -= 13; else dto = 0; if (dto > 14) dto = 14; } reg &= ~DTO_MASK; reg |= dto << DTO_SHIFT; OMAP_HSMMC_WRITE(host->base, SYSCTL, reg); } static void omap_hsmmc_start_dma_transfer(struct omap_hsmmc_host *host) { struct mmc_request *req = host->mrq; struct dma_chan *chan; if (!req->data) return; OMAP_HSMMC_WRITE(host->base, BLK, (req->data->blksz) | (req->data->blocks << 16)); set_data_timeout(host, req->data->timeout_ns, req->data->timeout_clks); chan = omap_hsmmc_get_dma_chan(host, req->data); dma_async_issue_pending(chan); } /* * Configure block length for MMC/SD cards and initiate the transfer. */ static int omap_hsmmc_prepare_data(struct omap_hsmmc_host *host, struct mmc_request *req) { int ret; unsigned long long timeout; host->data = req->data; if (req->data == NULL) { OMAP_HSMMC_WRITE(host->base, BLK, 0); if (req->cmd->flags & MMC_RSP_BUSY) { timeout = req->cmd->busy_timeout * NSEC_PER_MSEC; /* * Set an arbitrary 100ms data timeout for commands with * busy signal and no indication of busy_timeout. */ if (!timeout) timeout = 100000000U; set_data_timeout(host, timeout, 0); } return 0; } if (host->use_dma) { ret = omap_hsmmc_setup_dma_transfer(host, req); if (ret != 0) { dev_err(mmc_dev(host->mmc), "MMC start dma failure\n"); return ret; } } return 0; } static void omap_hsmmc_post_req(struct mmc_host *mmc, struct mmc_request *mrq, int err) { struct omap_hsmmc_host *host = mmc_priv(mmc); struct mmc_data *data = mrq->data; if (host->use_dma && data->host_cookie) { struct dma_chan *c = omap_hsmmc_get_dma_chan(host, data); dma_unmap_sg(c->device->dev, data->sg, data->sg_len, mmc_get_dma_dir(data)); data->host_cookie = 0; } } static void omap_hsmmc_pre_req(struct mmc_host *mmc, struct mmc_request *mrq) { struct omap_hsmmc_host *host = mmc_priv(mmc); if (mrq->data->host_cookie) { mrq->data->host_cookie = 0; return ; } if (host->use_dma) { struct dma_chan *c = omap_hsmmc_get_dma_chan(host, mrq->data); if (omap_hsmmc_pre_dma_transfer(host, mrq->data, &host->next_data, c)) mrq->data->host_cookie = 0; } } /* * Request function. for read/write operation */ static void omap_hsmmc_request(struct mmc_host *mmc, struct mmc_request *req) { struct omap_hsmmc_host *host = mmc_priv(mmc); int err; BUG_ON(host->req_in_progress); BUG_ON(host->dma_ch != -1); if (host->protect_card) { if (host->reqs_blocked < 3) { /* * Ensure the controller is left in a consistent * state by resetting the command and data state * machines. */ omap_hsmmc_reset_controller_fsm(host, SRD); omap_hsmmc_reset_controller_fsm(host, SRC); host->reqs_blocked += 1; } req->cmd->error = -EBADF; if (req->data) req->data->error = -EBADF; req->cmd->retries = 0; mmc_request_done(mmc, req); return; } else if (host->reqs_blocked) host->reqs_blocked = 0; WARN_ON(host->mrq != NULL); host->mrq = req; host->clk_rate = clk_get_rate(host->fclk); err = omap_hsmmc_prepare_data(host, req); if (err) { req->cmd->error = err; if (req->data) req->data->error = err; host->mrq = NULL; mmc_request_done(mmc, req); return; } if (req->sbc && !(host->flags & AUTO_CMD23)) { omap_hsmmc_start_command(host, req->sbc, NULL); return; } omap_hsmmc_start_dma_transfer(host); omap_hsmmc_start_command(host, req->cmd, req->data); } /* Routine to configure clock values. Exposed API to core */ static void omap_hsmmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct omap_hsmmc_host *host = mmc_priv(mmc); int do_send_init_stream = 0; if (ios->power_mode != host->power_mode) { switch (ios->power_mode) { case MMC_POWER_OFF: omap_hsmmc_set_power(host, 0, 0); break; case MMC_POWER_UP: omap_hsmmc_set_power(host, 1, ios->vdd); break; case MMC_POWER_ON: do_send_init_stream = 1; break; } host->power_mode = ios->power_mode; } /* FIXME: set registers based only on changes to ios */ omap_hsmmc_set_bus_width(host); if (host->pdata->controller_flags & OMAP_HSMMC_SUPPORTS_DUAL_VOLT) { /* Only MMC1 can interface at 3V without some flavor * of external transceiver; but they all handle 1.8V. */ if ((OMAP_HSMMC_READ(host->base, HCTL) & SDVSDET) && (ios->vdd == DUAL_VOLT_OCR_BIT)) { /* * The mmc_select_voltage fn of the core does * not seem to set the power_mode to * MMC_POWER_UP upon recalculating the voltage. * vdd 1.8v. */ if (omap_hsmmc_switch_opcond(host, ios->vdd) != 0) dev_dbg(mmc_dev(host->mmc), "Switch operation failed\n"); } } omap_hsmmc_set_clock(host); if (do_send_init_stream) send_init_stream(host); omap_hsmmc_set_bus_mode(host); } static int omap_hsmmc_get_cd(struct mmc_host *mmc) { struct omap_hsmmc_host *host = mmc_priv(mmc); if (!host->card_detect) return -ENOSYS; return host->card_detect(host->dev); } static void omap_hsmmc_init_card(struct mmc_host *mmc, struct mmc_card *card) { struct omap_hsmmc_host *host = mmc_priv(mmc); if (mmc_pdata(host)->init_card) mmc_pdata(host)->init_card(card); } static void omap_hsmmc_enable_sdio_irq(struct mmc_host *mmc, int enable) { struct omap_hsmmc_host *host = mmc_priv(mmc); u32 irq_mask, con; unsigned long flags; spin_lock_irqsave(&host->irq_lock, flags); con = OMAP_HSMMC_READ(host->base, CON); irq_mask = OMAP_HSMMC_READ(host->base, ISE); if (enable) { host->flags |= HSMMC_SDIO_IRQ_ENABLED; irq_mask |= CIRQ_EN; con |= CTPL | CLKEXTFREE; } else { host->flags &= ~HSMMC_SDIO_IRQ_ENABLED; irq_mask &= ~CIRQ_EN; con &= ~(CTPL | CLKEXTFREE); } OMAP_HSMMC_WRITE(host->base, CON, con); OMAP_HSMMC_WRITE(host->base, IE, irq_mask); /* * if enable, piggy back detection on current request * but always disable immediately */ if (!host->req_in_progress || !enable) OMAP_HSMMC_WRITE(host->base, ISE, irq_mask); /* flush posted write */ OMAP_HSMMC_READ(host->base, IE); spin_unlock_irqrestore(&host->irq_lock, flags); } static int omap_hsmmc_configure_wake_irq(struct omap_hsmmc_host *host) { int ret; /* * For omaps with wake-up path, wakeirq will be irq from pinctrl and * for other omaps, wakeirq will be from GPIO (dat line remuxed to * gpio). wakeirq is needed to detect sdio irq in runtime suspend state * with functional clock disabled. */ if (!host->dev->of_node || !host->wake_irq) return -ENODEV; ret = dev_pm_set_dedicated_wake_irq(host->dev, host->wake_irq); if (ret) { dev_err(mmc_dev(host->mmc), "Unable to request wake IRQ\n"); goto err; } /* * Some omaps don't have wake-up path from deeper idle states * and need to remux SDIO DAT1 to GPIO for wake-up from idle. */ if (host->pdata->controller_flags & OMAP_HSMMC_SWAKEUP_MISSING) { struct pinctrl *p = devm_pinctrl_get(host->dev); if (IS_ERR(p)) { ret = PTR_ERR(p); goto err_free_irq; } if (IS_ERR(pinctrl_lookup_state(p, PINCTRL_STATE_DEFAULT))) { dev_info(host->dev, "missing default pinctrl state\n"); devm_pinctrl_put(p); ret = -EINVAL; goto err_free_irq; } if (IS_ERR(pinctrl_lookup_state(p, PINCTRL_STATE_IDLE))) { dev_info(host->dev, "missing idle pinctrl state\n"); devm_pinctrl_put(p); ret = -EINVAL; goto err_free_irq; } devm_pinctrl_put(p); } OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) | IWE); return 0; err_free_irq: dev_pm_clear_wake_irq(host->dev); err: dev_warn(host->dev, "no SDIO IRQ support, falling back to polling\n"); host->wake_irq = 0; return ret; } static void omap_hsmmc_conf_bus_power(struct omap_hsmmc_host *host) { u32 hctl, capa, value; /* Only MMC1 supports 3.0V */ if (host->pdata->controller_flags & OMAP_HSMMC_SUPPORTS_DUAL_VOLT) { hctl = SDVS30; capa = VS30 | VS18; } else { hctl = SDVS18; capa = VS18; } value = OMAP_HSMMC_READ(host->base, HCTL) & ~SDVS_MASK; OMAP_HSMMC_WRITE(host->base, HCTL, value | hctl); value = OMAP_HSMMC_READ(host->base, CAPA); OMAP_HSMMC_WRITE(host->base, CAPA, value | capa); /* Set SD bus power bit */ set_sd_bus_power(host); } static int omap_hsmmc_multi_io_quirk(struct mmc_card *card, unsigned int direction, int blk_size) { /* This controller can't do multiblock reads due to hw bugs */ if (direction == MMC_DATA_READ) return 1; return blk_size; } static struct mmc_host_ops omap_hsmmc_ops = { .post_req = omap_hsmmc_post_req, .pre_req = omap_hsmmc_pre_req, .request = omap_hsmmc_request, .set_ios = omap_hsmmc_set_ios, .get_cd = omap_hsmmc_get_cd, .get_ro = mmc_gpio_get_ro, .init_card = omap_hsmmc_init_card, .enable_sdio_irq = omap_hsmmc_enable_sdio_irq, }; #ifdef CONFIG_DEBUG_FS static int omap_hsmmc_regs_show(struct seq_file *s, void *data) { struct mmc_host *mmc = s->private; struct omap_hsmmc_host *host = mmc_priv(mmc); seq_printf(s, "mmc%d:\n", mmc->index); seq_printf(s, "sdio irq mode\t%s\n", (mmc->caps & MMC_CAP_SDIO_IRQ) ? "interrupt" : "polling"); if (mmc->caps & MMC_CAP_SDIO_IRQ) { seq_printf(s, "sdio irq \t%s\n", (host->flags & HSMMC_SDIO_IRQ_ENABLED) ? "enabled" : "disabled"); } seq_printf(s, "ctx_loss:\t%d\n", host->context_loss); pm_runtime_get_sync(host->dev); seq_puts(s, "\nregs:\n"); seq_printf(s, "CON:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, CON)); seq_printf(s, "PSTATE:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, PSTATE)); seq_printf(s, "HCTL:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, HCTL)); seq_printf(s, "SYSCTL:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, SYSCTL)); seq_printf(s, "IE:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, IE)); seq_printf(s, "ISE:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, ISE)); seq_printf(s, "CAPA:\t\t0x%08x\n", OMAP_HSMMC_READ(host->base, CAPA)); pm_runtime_mark_last_busy(host->dev); pm_runtime_put_autosuspend(host->dev); return 0; } static int omap_hsmmc_regs_open(struct inode *inode, struct file *file) { return single_open(file, omap_hsmmc_regs_show, inode->i_private); } static const struct file_operations mmc_regs_fops = { .open = omap_hsmmc_regs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static void omap_hsmmc_debugfs(struct mmc_host *mmc) { if (mmc->debugfs_root) debugfs_create_file("regs", S_IRUSR, mmc->debugfs_root, mmc, &mmc_regs_fops); } #else static void omap_hsmmc_debugfs(struct mmc_host *mmc) { } #endif #ifdef CONFIG_OF static const struct omap_mmc_of_data omap3_pre_es3_mmc_of_data = { /* See 35xx errata 2.1.1.128 in SPRZ278F */ .controller_flags = OMAP_HSMMC_BROKEN_MULTIBLOCK_READ, }; static const struct omap_mmc_of_data omap4_mmc_of_data = { .reg_offset = 0x100, }; static const struct omap_mmc_of_data am33xx_mmc_of_data = { .reg_offset = 0x100, .controller_flags = OMAP_HSMMC_SWAKEUP_MISSING, }; static const struct of_device_id omap_mmc_of_match[] = { { .compatible = "ti,omap2-hsmmc", }, { .compatible = "ti,omap3-pre-es3-hsmmc", .data = &omap3_pre_es3_mmc_of_data, }, { .compatible = "ti,omap3-hsmmc", }, { .compatible = "ti,omap4-hsmmc", .data = &omap4_mmc_of_data, }, { .compatible = "ti,am33xx-hsmmc", .data = &am33xx_mmc_of_data, }, {}, }; MODULE_DEVICE_TABLE(of, omap_mmc_of_match); static struct omap_hsmmc_platform_data *of_get_hsmmc_pdata(struct device *dev) { struct omap_hsmmc_platform_data *pdata, *legacy; struct device_node *np = dev->of_node; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) return ERR_PTR(-ENOMEM); /* out of memory */ legacy = dev_get_platdata(dev); if (legacy && legacy->name) pdata->name = legacy->name; if (of_find_property(np, "ti,dual-volt", NULL)) pdata->controller_flags |= OMAP_HSMMC_SUPPORTS_DUAL_VOLT; pdata->gpio_cd = -EINVAL; pdata->gpio_cod = -EINVAL; pdata->gpio_wp = -EINVAL; if (of_find_property(np, "ti,non-removable", NULL)) { pdata->nonremovable = true; pdata->no_regulator_off_init = true; } if (of_find_property(np, "ti,needs-special-reset", NULL)) pdata->features |= HSMMC_HAS_UPDATED_RESET; if (of_find_property(np, "ti,needs-special-hs-handling", NULL)) pdata->features |= HSMMC_HAS_HSPE_SUPPORT; return pdata; } #else static inline struct omap_hsmmc_platform_data *of_get_hsmmc_pdata(struct device *dev) { return ERR_PTR(-EINVAL); } #endif static int omap_hsmmc_probe(struct platform_device *pdev) { struct omap_hsmmc_platform_data *pdata = pdev->dev.platform_data; struct mmc_host *mmc; struct omap_hsmmc_host *host = NULL; struct resource *res; int ret, irq; const struct of_device_id *match; const struct omap_mmc_of_data *data; void __iomem *base; match = of_match_device(of_match_ptr(omap_mmc_of_match), &pdev->dev); if (match) { pdata = of_get_hsmmc_pdata(&pdev->dev); if (IS_ERR(pdata)) return PTR_ERR(pdata); if (match->data) { data = match->data; pdata->reg_offset = data->reg_offset; pdata->controller_flags |= data->controller_flags; } } if (pdata == NULL) { dev_err(&pdev->dev, "Platform Data is missing\n"); return -ENXIO; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); irq = platform_get_irq(pdev, 0); if (res == NULL || irq < 0) return -ENXIO; base = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(base)) return PTR_ERR(base); mmc = mmc_alloc_host(sizeof(struct omap_hsmmc_host), &pdev->dev); if (!mmc) { ret = -ENOMEM; goto err; } ret = mmc_of_parse(mmc); if (ret) goto err1; host = mmc_priv(mmc); host->mmc = mmc; host->pdata = pdata; host->dev = &pdev->dev; host->use_dma = 1; host->dma_ch = -1; host->irq = irq; host->mapbase = res->start + pdata->reg_offset; host->base = base + pdata->reg_offset; host->power_mode = MMC_POWER_OFF; host->next_data.cookie = 1; host->pbias_enabled = 0; host->vqmmc_enabled = 0; ret = omap_hsmmc_gpio_init(mmc, host, pdata); if (ret) goto err_gpio; platform_set_drvdata(pdev, host); if (pdev->dev.of_node) host->wake_irq = irq_of_parse_and_map(pdev->dev.of_node, 1); mmc->ops = &omap_hsmmc_ops; mmc->f_min = OMAP_MMC_MIN_CLOCK; if (pdata->max_freq > 0) mmc->f_max = pdata->max_freq; else if (mmc->f_max == 0) mmc->f_max = OMAP_MMC_MAX_CLOCK; spin_lock_init(&host->irq_lock); host->fclk = devm_clk_get(&pdev->dev, "fck"); if (IS_ERR(host->fclk)) { ret = PTR_ERR(host->fclk); host->fclk = NULL; goto err1; } if (host->pdata->controller_flags & OMAP_HSMMC_BROKEN_MULTIBLOCK_READ) { dev_info(&pdev->dev, "multiblock reads disabled due to 35xx erratum 2.1.1.128; MMC read performance may suffer\n"); omap_hsmmc_ops.multi_io_quirk = omap_hsmmc_multi_io_quirk; } device_init_wakeup(&pdev->dev, true); pm_runtime_enable(host->dev); pm_runtime_get_sync(host->dev); pm_runtime_set_autosuspend_delay(host->dev, MMC_AUTOSUSPEND_DELAY); pm_runtime_use_autosuspend(host->dev); omap_hsmmc_context_save(host); host->dbclk = devm_clk_get(&pdev->dev, "mmchsdb_fck"); /* * MMC can still work without debounce clock. */ if (IS_ERR(host->dbclk)) { host->dbclk = NULL; } else if (clk_prepare_enable(host->dbclk) != 0) { dev_warn(mmc_dev(host->mmc), "Failed to enable debounce clk\n"); host->dbclk = NULL; } /* Set this to a value that allows allocating an entire descriptor * list within a page (zero order allocation). */ mmc->max_segs = 64; mmc->max_blk_size = 512; /* Block Length at max can be 1024 */ mmc->max_blk_count = 0xFFFF; /* No. of Blocks is 16 bits */ mmc->max_req_size = mmc->max_blk_size * mmc->max_blk_count; mmc->max_seg_size = mmc->max_req_size; mmc->caps |= MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED | MMC_CAP_WAIT_WHILE_BUSY | MMC_CAP_ERASE | MMC_CAP_CMD23; mmc->caps |= mmc_pdata(host)->caps; if (mmc->caps & MMC_CAP_8_BIT_DATA) mmc->caps |= MMC_CAP_4_BIT_DATA; if (mmc_pdata(host)->nonremovable) mmc->caps |= MMC_CAP_NONREMOVABLE; mmc->pm_caps |= mmc_pdata(host)->pm_caps; omap_hsmmc_conf_bus_power(host); host->rx_chan = dma_request_chan(&pdev->dev, "rx"); if (IS_ERR(host->rx_chan)) { dev_err(mmc_dev(host->mmc), "RX DMA channel request failed\n"); ret = PTR_ERR(host->rx_chan); goto err_irq; } host->tx_chan = dma_request_chan(&pdev->dev, "tx"); if (IS_ERR(host->tx_chan)) { dev_err(mmc_dev(host->mmc), "TX DMA channel request failed\n"); ret = PTR_ERR(host->tx_chan); goto err_irq; } /* Request IRQ for MMC operations */ ret = devm_request_irq(&pdev->dev, host->irq, omap_hsmmc_irq, 0, mmc_hostname(mmc), host); if (ret) { dev_err(mmc_dev(host->mmc), "Unable to grab HSMMC IRQ\n"); goto err_irq; } ret = omap_hsmmc_reg_get(host); if (ret) goto err_irq; if (!mmc->ocr_avail) mmc->ocr_avail = mmc_pdata(host)->ocr_mask; omap_hsmmc_disable_irq(host); /* * For now, only support SDIO interrupt if we have a separate * wake-up interrupt configured from device tree. This is because * the wake-up interrupt is needed for idle state and some * platforms need special quirks. And we don't want to add new * legacy mux platform init code callbacks any longer as we * are moving to DT based booting anyways. */ ret = omap_hsmmc_configure_wake_irq(host); if (!ret) mmc->caps |= MMC_CAP_SDIO_IRQ; omap_hsmmc_protect_card(host); mmc_add_host(mmc); if (mmc_pdata(host)->name != NULL) { ret = device_create_file(&mmc->class_dev, &dev_attr_slot_name); if (ret < 0) goto err_slot_name; } if (host->get_cover_state) { ret = device_create_file(&mmc->class_dev, &dev_attr_cover_switch); if (ret < 0) goto err_slot_name; } omap_hsmmc_debugfs(mmc); pm_runtime_mark_last_busy(host->dev); pm_runtime_put_autosuspend(host->dev); return 0; err_slot_name: mmc_remove_host(mmc); err_irq: device_init_wakeup(&pdev->dev, false); if (!IS_ERR_OR_NULL(host->tx_chan)) dma_release_channel(host->tx_chan); if (!IS_ERR_OR_NULL(host->rx_chan)) dma_release_channel(host->rx_chan); pm_runtime_dont_use_autosuspend(host->dev); pm_runtime_put_sync(host->dev); pm_runtime_disable(host->dev); if (host->dbclk) clk_disable_unprepare(host->dbclk); err1: err_gpio: mmc_free_host(mmc); err: return ret; } static int omap_hsmmc_remove(struct platform_device *pdev) { struct omap_hsmmc_host *host = platform_get_drvdata(pdev); pm_runtime_get_sync(host->dev); mmc_remove_host(host->mmc); dma_release_channel(host->tx_chan); dma_release_channel(host->rx_chan); dev_pm_clear_wake_irq(host->dev); pm_runtime_dont_use_autosuspend(host->dev); pm_runtime_put_sync(host->dev); pm_runtime_disable(host->dev); device_init_wakeup(&pdev->dev, false); if (host->dbclk) clk_disable_unprepare(host->dbclk); mmc_free_host(host->mmc); return 0; } #ifdef CONFIG_PM_SLEEP static int omap_hsmmc_suspend(struct device *dev) { struct omap_hsmmc_host *host = dev_get_drvdata(dev); if (!host) return 0; pm_runtime_get_sync(host->dev); if (!(host->mmc->pm_flags & MMC_PM_KEEP_POWER)) { OMAP_HSMMC_WRITE(host->base, ISE, 0); OMAP_HSMMC_WRITE(host->base, IE, 0); OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); OMAP_HSMMC_WRITE(host->base, HCTL, OMAP_HSMMC_READ(host->base, HCTL) & ~SDBP); } if (host->dbclk) clk_disable_unprepare(host->dbclk); pm_runtime_put_sync(host->dev); return 0; } /* Routine to resume the MMC device */ static int omap_hsmmc_resume(struct device *dev) { struct omap_hsmmc_host *host = dev_get_drvdata(dev); if (!host) return 0; pm_runtime_get_sync(host->dev); if (host->dbclk) clk_prepare_enable(host->dbclk); if (!(host->mmc->pm_flags & MMC_PM_KEEP_POWER)) omap_hsmmc_conf_bus_power(host); omap_hsmmc_protect_card(host); pm_runtime_mark_last_busy(host->dev); pm_runtime_put_autosuspend(host->dev); return 0; } #endif static int omap_hsmmc_runtime_suspend(struct device *dev) { struct omap_hsmmc_host *host; unsigned long flags; int ret = 0; host = platform_get_drvdata(to_platform_device(dev)); omap_hsmmc_context_save(host); dev_dbg(dev, "disabled\n"); spin_lock_irqsave(&host->irq_lock, flags); if ((host->mmc->caps & MMC_CAP_SDIO_IRQ) && (host->flags & HSMMC_SDIO_IRQ_ENABLED)) { /* disable sdio irq handling to prevent race */ OMAP_HSMMC_WRITE(host->base, ISE, 0); OMAP_HSMMC_WRITE(host->base, IE, 0); if (!(OMAP_HSMMC_READ(host->base, PSTATE) & DLEV_DAT(1))) { /* * dat1 line low, pending sdio irq * race condition: possible irq handler running on * multi-core, abort */ dev_dbg(dev, "pending sdio irq, abort suspend\n"); OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); OMAP_HSMMC_WRITE(host->base, ISE, CIRQ_EN); OMAP_HSMMC_WRITE(host->base, IE, CIRQ_EN); pm_runtime_mark_last_busy(dev); ret = -EBUSY; goto abort; } pinctrl_pm_select_idle_state(dev); } else { pinctrl_pm_select_idle_state(dev); } abort: spin_unlock_irqrestore(&host->irq_lock, flags); return ret; } static int omap_hsmmc_runtime_resume(struct device *dev) { struct omap_hsmmc_host *host; unsigned long flags; host = platform_get_drvdata(to_platform_device(dev)); omap_hsmmc_context_restore(host); dev_dbg(dev, "enabled\n"); spin_lock_irqsave(&host->irq_lock, flags); if ((host->mmc->caps & MMC_CAP_SDIO_IRQ) && (host->flags & HSMMC_SDIO_IRQ_ENABLED)) { pinctrl_pm_select_default_state(host->dev); /* irq lost, if pinmux incorrect */ OMAP_HSMMC_WRITE(host->base, STAT, STAT_CLEAR); OMAP_HSMMC_WRITE(host->base, ISE, CIRQ_EN); OMAP_HSMMC_WRITE(host->base, IE, CIRQ_EN); } else { pinctrl_pm_select_default_state(host->dev); } spin_unlock_irqrestore(&host->irq_lock, flags); return 0; } static const struct dev_pm_ops omap_hsmmc_dev_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(omap_hsmmc_suspend, omap_hsmmc_resume) .runtime_suspend = omap_hsmmc_runtime_suspend, .runtime_resume = omap_hsmmc_runtime_resume, }; static struct platform_driver omap_hsmmc_driver = { .probe = omap_hsmmc_probe, .remove = omap_hsmmc_remove, .driver = { .name = DRIVER_NAME, .pm = &omap_hsmmc_dev_pm_ops, .of_match_table = of_match_ptr(omap_mmc_of_match), }, }; module_platform_driver(omap_hsmmc_driver); MODULE_DESCRIPTION("OMAP High Speed Multimedia Card driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRIVER_NAME); MODULE_AUTHOR("Texas Instruments Inc");
nokia-wroclaw/innovativeproject-check-room
frontend/src/components/NavBar/Google/MyGoogleLogout.js
import React, { useContext } from 'react'; import PropTypes from 'prop-types'; import { GoogleLogout } from 'react-google-login'; import { constants } from '../../../assets/configs/constants'; import BackendContext from '../../../services/communication/BackendContext'; const MyGoogleLogout = ( { render } ) => { const backend = useContext( BackendContext ); const logoutSucceeded = () => backend.auth.logout(); return backend.auth.user ? ( <GoogleLogout render={ render } clientId={ constants.google.CLIENT_ID } onLogoutSuccess={ logoutSucceeded } /> ) : null; }; MyGoogleLogout.propTypes = { render: PropTypes.func.isRequired, }; export default MyGoogleLogout;
Nike-Inc/knockoff-factory
tests/knockoff/sdk/test_blueprint.py
<reponame>Nike-Inc/knockoff-factory<filename>tests/knockoff/sdk/test_blueprint.py # Copyright 2021-present, Nike, Inc. # All rights reserved. # # This source code is licensed under the Apache-2.0 license found in # the LICENSE file in the root directory of this source tree. from mock import MagicMock from knockoff.sdk.blueprint import Blueprint, noplan class TestBlueprint(object): def test_blueprint_from_plan_package_name(self): blueprint = Blueprint.from_plan_package_name("knockoff.sdk.blueprint:noplan") assert blueprint.plan == noplan def test_construct(self): knockoff_db = MagicMock() plan = MagicMock(side_effect=knockoff_db) blueprint = Blueprint(plan) response = blueprint.construct(knockoff_db) plan.assert_called_once_with(knockoff_db) response.knockoff_db.build.assert_called_once()
DavidBerdik/dictances
tests/utils/__init__.py
from .compare_metrics import compare_metrics from .bhattacharyya_reference import bhattacharyya_distance from .chi_square_reference import chi_square_distance from .jensen_shannon_divergence import jensen_shannon_divergence from .normal_chi_square_reference import normal_chi_square_distance __all__ = ["compare_metrics", "bhattacharyya_distance", "chi_square_distance", "jensen_shannon_divergence", "normal_chi_square_distance"]
sourcecodeexamples/ecommerce-spring-reactjs
src/main/java/com/gmail/merikbest2015/ecommerce/service/OrderService.java
<filename>src/main/java/com/gmail/merikbest2015/ecommerce/service/OrderService.java package com.gmail.merikbest2015.ecommerce.service; import com.gmail.merikbest2015.ecommerce.domain.Order; import com.gmail.merikbest2015.ecommerce.domain.User; import com.gmail.merikbest2015.ecommerce.service.Impl.OrderServiceImpl; import java.util.List; /** * The service layer interface describes a set of methods for working with objects of the {@link Order} class. * * @author <NAME> (<EMAIL>) * @version 1.0 * @see Order * @see OrderServiceImpl */ public interface OrderService { /** * Return list of all user orders. * * @return list of user {@link Order}. */ List<Order> findAll(); /** * Save order info. * * @param order order object to return. * @return The {@link Order} class object which will be saved in the database. */ Order save(Order order); /** * Returns list of orders authenticated user. * * @param user name of authenticated user. * @return An object of type {@link List} is a list of orders of authenticated user. */ List<Order> findOrderByUser(User user); /** * Saves the user order and send message with order params to email address. * * @param validOrder requested valid order. * @param userSession requested authenticated user. * @return The {@link Order} class object which will be saved in the database. */ Order postOrder(Order validOrder, User userSession); }
atlarge-research/opencraft
src/test/java/science/atlarge/opencraft/opencraft/net/codec/play/game/UnloadChunkCodecTest.java
<reponame>atlarge-research/opencraft package science.atlarge.opencraft.opencraft.net.codec.play.game; import com.flowpowered.network.Codec; import science.atlarge.opencraft.opencraft.net.codec.CodecTest; import science.atlarge.opencraft.opencraft.net.message.play.game.UnloadChunkMessage; public class UnloadChunkCodecTest extends CodecTest<UnloadChunkMessage> { @Override protected Codec<UnloadChunkMessage> createCodec() { return new UnloadChunkCodec(); } @Override protected UnloadChunkMessage createMessage() { return new UnloadChunkMessage(1, 2); } }
priojeetpriyom/competitive-programming
PRE CODE/order statistics tree using bit.cpp
// C++ program to find rank of an element // and k-th smallest element. #include <bits/stdc++.h> using namespace std; const int MAX_VAL = 1000001; /* Updates element at index 'i' of BIT. */ void update(int i, int add, vector<int>& BIT) { while (i > 0 && i < BIT.size()) { BIT[i] += add; i = i + (i & (-i)); } } /* Returns cumulative sum of all elements of fenwick tree/BIT from start upto and including element at index 'i'. */ int sum(int i, vector<int>& BIT) { int ans = 0; while (i > 0) { ans += BIT[i]; i = i - (i & (-i)); } return ans; } // Returns lower bound for k in BIT. int findKthSmallest(int k, vector<int> &BIT) { // Do binary search in BIT[] for given // value k. int l = 0; int h = BIT.size(); while (l < h) { int mid = (l + h) / 2; if (k <= sum(mid, BIT)) h = mid; else l = mid+1; } return l; } // Insert x into BIT. We masically increment // rank of all elements greater than x. void insertElement(int x, vector<int> &BIT) { update(x, 1, BIT); } // Delete x from BIT. We masically decreases // rank of all elements greater than x. void deleteElement(int x, vector<int> &BIT) { update(x, -1, BIT); } // Returns rank of element. We basically // return sum of elements from start to // index x. int findRank(int x, vector<int> &BIT) { return sum(x, BIT); } // Driver code int main() { vector<int> BIT(MAX_VAL); insertElement(20, BIT); insertElement(50, BIT); insertElement(30, BIT); insertElement(40, BIT); cout << "2nd Smallest element is " << findKthSmallest(2, BIT) << endl; cout << "Rank of 40 is " << findRank(40, BIT) << endl; deleteElement(40, BIT); cout << "Rank of 50 is " << findRank(50, BIT) << endl; return 0; }
djxf/CampusAssi
app/src/main/java/cn/nicolite/huthelper/network/api/ElectricAPI.java
package cn.nicolite.huthelper.network.api; import cn.nicolite.huthelper.model.bean.Electric; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; /** * 电费API接口 * Created by nicolite on 17-10-31. * Observable Rxjava形式 */ public interface ElectricAPI { @GET("/api/v3/get/power_e/{part}/{buildingNo}/{roomNo}/{xh}/{rememberCode}/{enc}") Observable<Electric> getElectric(@Path("part")String part,@Path("buildingNo") String buildingNo, @Path("roomNo") String roomNo, @Path("xh") String xh, @Path("rememberCode") String rememberCode, @Path("enc") String enc); }
yiyi7817/dacia-commons
src/main/java/org/gensis0/lib/dacia/commons/data/database/DatabaseConnection.java
<gh_stars>0 package org.gensis0.lib.dacia.commons.data.database; import org.gensis0.lib.dacia.commons.data.connection.DACIADataConnection; public class DatabaseConnection implements DACIADataConnection { @Override public String getPath() { // TODO Auto-generated method stub return null; } }
Franckyi/IBE-Editor
gameadapter-fabric/src/main/java/com/github/franckyi/gameadapter/fabric/common/IFabricStyle.java
package com.github.franckyi.gameadapter.fabric.common; import com.github.franckyi.gameadapter.api.internal.IStyle; import net.minecraft.text.Style; public interface IFabricStyle extends IStyle { Style withUnderlineCommon(Boolean underlined); Style withStrikethrough(Boolean strikethrough); Style withObfuscated(Boolean obfuscated); }
akai10tsuki/vsutillib
vsutillib/vsutillib-pyqt6/vsutillib/pyqt6/classes/QFileListWidget.py
""" Sub-class of QTextEdit accepts drag and drop """ import logging from pathlib import Path from natsort import natsorted, ns #from PySide2.QtCore import Slot, Signal #from PySide2.QtWidgets import QMenu from PySide6.QtCore import Slot, Signal from PySide6.QtWidgets import QMenu from .QOutputTextWidget import QOutputTextWidget MODULELOG = logging.getLogger(__name__) MODULELOG.addHandler(logging.NullHandler()) class QFileListWidget(QOutputTextWidget): """ QTextEdit subclass that accepts dropped files displays only the name of the files. The full path is save and use internally. """ filesDroppedUpdateSignal = Signal(list) def __init__(self, parent): super().__init__(parent) # self.setDragEnabled(True) self.fileList = [] self.bBlockDrops = False self.bFilesDropped = False def clear(self): self.fileList = [] self.bBlockDrops = False self.bFilesDropped = False super().setAcceptDrops(True) super().clear() def dragEnterEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == "file": event.acceptProposedAction() def dragMoveEvent(self, event): data = event.mimeData() urls = data.urls() if urls and urls[0].scheme() == "file": event.acceptProposedAction() def dropEvent(self, event): data = event.mimeData() urls = data.urls() bUpdate = False for f in urls: filePath = str(f.path())[1:] fPath = Path(filePath) if fPath.is_dir(): files = [x for x in fPath.glob("*.*") if x.is_file()] files = natsorted(files, alg=ns.PATH) for x in files: if x not in self.fileList: self.fileList.append(x) bUpdate = True elif fPath.is_file(): if fPath not in self.fileList: self.fileList.append(fPath) bUpdate = True if bUpdate: if not self.bFilesDropped: self.bFilesDropped = True self._displayFiles() self.filesDroppedUpdateSignal.emit(self.fileList) def contextMenuEvent(self, event): if self.bFilesDropped and self.fileList: menu = QMenu(self) clearAction = menu.addAction(Actions.Clear) sortAction = menu.addAction(Actions.Sort) action = menu.exec_(self.mapToGlobal(event.pos())) if action == clearAction: self.clear() self.filesDroppedUpdateSignal.emit(self.fileList) elif action == sortAction: if self.fileList: self.fileList.sort(key=str) self._displayFiles() self.filesDroppedUpdateSignal.emit(self.fileList) def setAcceptDrops(self, value): if not self.bBlockDrops: # don't check for type to raise error super().setAcceptDrops(value) @Slot(list) def setFileList(self, filesList=None): """ Set the files manually Args: filesList (list, optional): file list to display. Defaults to None. """ if filesList: self.bBlockDrops = True self.bFilesDropped = False super().setAcceptDrops(False) self.fileList = [] for f in filesList: self.fileList.append(f) self._displayFiles() def _displayFiles(self): """display the files on QTextEdit box""" super().clear() for f in self.fileList: self.insertPlainText(f.name + "\n") class Actions: """ Actions labels for context menu """ Clear = "Clear" Sort = "Sort"
goodix/amazon-freertos
vendors/goodix/GR551x_SDK_V1_00/components/libraries/app_queue/app_queue.h
<filename>vendors/goodix/GR551x_SDK_V1_00/components/libraries/app_queue/app_queue.h /** ***************************************************************************************** * * @file app_queue.h * * @brief Header file - APP QUEUE APIs * ***************************************************************************************** * @attention #####Copyright (c) 2019 GOODIX All rights reserved. ***************************************************************************************** */ #ifndef __APP_QUEUE_H__ #define __APP_QUEUE_H__ #include "gr55xx_sys.h" #include <stdint.h> #include <stdbool.h> /** * @defgroup APP_QUEUE_STRUCT Structures * @{ */ /**@brief App queue instance information. */ typedef struct { uint16_t element_size; /**< Size of app queue element. */ uint16_t queue_size; /**< Size of app queue buffer. */ void *p_buffer; /**< Pointer to app queue buffer. */ uint16_t start_idx; /**< Start index of app queue. */ uint16_t end_idx; /**< End index of app queue. */ } app_queue_t; /** @} */ /** * @defgroup APP_QUEUE_FUNCTION Functions * @{ */ /** ***************************************************************************************** * @brief Initialize one app queue instance. * * @param[in] p_queue: Pointer to app queue instance. * @param[in] p_buffer: Pointer to queue buffer. * @param[in] queue_size: Size of queue buffer. * @param[in] element_size: Size of queue element * * @return Result of initializing app queue. ***************************************************************************************** */ sdk_err_t app_queue_init(app_queue_t *p_queue, void *p_buffer, uint16_t queue_size, uint16_t element_size); /** ***************************************************************************************** * @brief Push one element to tail of app queue. * * @param[in] p_queue: Pointer to app queue instance. * @param[in] p_elemment: Pointer to the element that will be stored in the queue. * * @return Result of element push. ***************************************************************************************** */ sdk_err_t app_queue_push(app_queue_t *p_queue, void const *p_elemment); /** ***************************************************************************************** * @brief Push some elements to tail of app queue. * * @param[in] p_queue: Pointer to app queue instance. * @param[in] p_elemment: Pointer to the elements that will be stored in the queue. * @param[in] amount: Amount of the elements that wants be stored in the queue. * * @return Amount of writen elements. ***************************************************************************************** */ uint16_t app_queue_multi_push(app_queue_t *p_queue, void const *p_elemment, uint16_t amount); /** ***************************************************************************************** * @brief Peek one element from tail of app queue. * * @param[in] p_queue: Pointer to app queue instance. * @param[out] p_elemment: Pointer to where the element will be copied. * * @return Result of element peek. ***************************************************************************************** */ sdk_err_t app_queue_peek(app_queue_t *p_queue, void *p_elemment); /** ***************************************************************************************** * @brief Pop one element from tail of app queue. * * @param[in] p_queue: Pointer to app queue instance. * @param[out] p_elemment: Pointer to where the element will be copied. * * @return Result of element pop. ***************************************************************************************** */ sdk_err_t app_queue_pop(app_queue_t *p_queue, void *p_elemment); /** ***************************************************************************************** * @brief Check app queue is full or not. * * @param[in] p_queue: Pointer to app queue instance. * * @return Result of check. ***************************************************************************************** */ bool app_queue_is_full(app_queue_t *p_queue); /** ***************************************************************************************** * @brief Check app queue is empty or not. * * @param[in] p_queue: Pointer to app queue instance. * * @return Result of check. ***************************************************************************************** */ bool app_queue_is_empty(app_queue_t *p_queue); /** ***************************************************************************************** * @brief Get surplus space of one app queue. * * @param[in] p_queue: Pointer to app queue instance. * * @retval Size of surplus space. ***************************************************************************************** */ uint16_t app_queue_surplus_space_get(app_queue_t *p_queue); /** ***************************************************************************************** * @brief Get availdble data from one ring buffer. * * @param[in] p_queue: Pointer to app queue instance. * * @retval Count of availdble items. ***************************************************************************************** */ uint16_t app_queue_items_count_get(app_queue_t *p_queue); /** ***************************************************************************************** * @brief Clean one app queue. * * @param[in] p_queue: Pointer to app queue instance. ***************************************************************************************** */ void app_queue_clean(app_queue_t *p_queue); /** @} */ #endif
bossenti/incubator-streampipes-extensions
streampipes-processors-pattern-detection-flink/src/main/java/org/apache/streampipes/processors/pattern/detection/flink/processor/and/AndParameters.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.streampipes.processors.pattern.detection.flink.processor.and; import org.apache.streampipes.model.graph.DataProcessorInvocation; import org.apache.streampipes.wrapper.params.binding.EventProcessorBindingParams; import java.util.List; public class AndParameters extends EventProcessorBindingParams { private TimeUnit timeUnit; private Integer timeWindow; private List<String> leftMappings; private List<String> rightMappings; public AndParameters(DataProcessorInvocation invocationGraph, TimeUnit timeUnit, Integer timeWindow, List<String> leftMappings, List<String> rightMappings) { super(invocationGraph); this.timeUnit = timeUnit; this.timeWindow = timeWindow; this.leftMappings = leftMappings; this.rightMappings = rightMappings; } public TimeUnit getTimeUnit() { return timeUnit; } public Integer getTimeWindow() { return timeWindow; } public List<String> getLeftMappings() { return leftMappings; } public List<String> getRightMappings() { return rightMappings; } }
mtoquinn/Hike-Five
validation/matchData.js
<reponame>mtoquinn/Hike-Five const Validator = require('validator'); const isEmpty = require('./is-empty'); module.exports = function validateMatchInput(data) { let errors = {}; if (Validator.isEmpty(data.skillMin)) { errors.skillMin = 'Skill Min field is required'; } if (Validator.equals(data.skillMin, '0')) { errors.skillMin = 'Skill Min field is required'; } if (Validator.isEmpty(data.skillMax)) { errors.skillMax = 'Skill Max field is required'; } if (Validator.equals(data.skillMax, '0')) { errors.skillMax = 'Skill Max field is required'; } if (Validator.isEmpty(data.travel)) { errors.travel = 'Travel field is required'; } if (Validator.equals(data.travel, '0')) { errors.travel = 'Travel field is required'; } if (Validator.isEmpty(data.camp)) { errors.camp = 'Camp field is required'; } if (Validator.equals(data.camp, '0')) { errors.camp = 'Camp field is required'; } if (Validator.isEmpty(data.climber)) { errors.climber = 'Climb field is required'; } if (Validator.equals(data.climber, '0')) { errors.climber = 'Climb field is required'; } return { errors, isValid: isEmpty(errors) }; };
OctopusLian/kaikeba-courses
C/2-math-calcul/volume.c
<filename>C/2-math-calcul/volume.c //计算球的大致体积 #include <stdio.h> #include <math.h> #define PI 3.14 int main() { double radius; radius = 12.0; printf("%g",4.0 / 3 * PI * pow(radius,3)); return 0; }
Glease/Railcraft
src/main/java/mods/railcraft/common/util/sounds/SoundHelper.java
/* * Copyright (c) CovertJaguar, 2014 http://railcraft.info * * This code is the property of CovertJaguar * and may only be used with explicit written * permission unless otherwise specified on the * license page at http://railcraft.info/wiki/info:license. */ package mods.railcraft.common.util.sounds; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import java.util.HashMap; import java.util.Map; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import mods.railcraft.common.core.RailcraftConfig; import net.minecraft.block.Block; import net.minecraft.block.Block.SoundType; /** * * @author CovertJaguar <http://www.railcraft.info> */ public class SoundHelper { public static final String SOUND_LOCOMOTIVE_STEAM_WHISTLE = "railcraft:locomotive.steam.whistle"; public static final String SOUND_LOCOMOTIVE_ELECTRIC_WHISTLE = "railcraft:locomotive.electric.whistle"; public static final String SOUND_STEAM_BURST = "railcraft:machine.steamburst"; public static final String SOUND_STEAM_HISS = "railcraft:machine.steamhiss"; private static final Map<String, Integer> soundLimiterClient = new HashMap<String, Integer>(); private static final Map<String, Integer> soundLimiterServer = new HashMap<String, Integer>(); private static Map<String, Integer> getSoundLimiter(){ if(FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) return soundLimiterClient; return soundLimiterServer; } private static boolean canPlaySound(String name) { if (!RailcraftConfig.playSounds()) return false; Integer limit = getSoundLimiter().get(name); return limit == null || limit <= 10; } private static void incrementLimiter(String name) { Integer limit = getSoundLimiter().get(name); if (limit == null) limit = 0; limit++; getSoundLimiter().put(name, limit); } public static void decrementLimiters() { for (Map.Entry<String, Integer> entry : getSoundLimiter().entrySet()) { Integer limit = entry.getValue(); if (limit > 0) { limit--; entry.setValue(limit); } } } public static void playSound(World world, int x, int y, int z, String name, float volume, float pitch) { if (canPlaySound(name)) { incrementLimiter(name); world.playSoundEffect(x, y, z, name, volume, pitch); } } public static void playSoundClient(World world, int x, int y, int z, String name, float volume, float pitch) { if (canPlaySound(name)) { incrementLimiter(name); world.playSound(x, y, z, name, volume, pitch, false); } } public static void playSoundAtEntity(Entity entity, String name, float volume, float pitch) { if (canPlaySound(name)) { incrementLimiter(name); entity.worldObj.playSoundAtEntity(entity, name, volume, pitch); } } public static void playBlockSound(World world, int x, int y, int z, String soundName, float volume, float pitch, Block block, int meta) { if (world != null && soundName != null) { if (soundName.contains("railcraft")) { SoundType sound = SoundRegistry.getSound(block, meta); if (sound != null) { String newName = soundName.contains("dig") ? sound.getBreakSound() : soundName.contains("step") ? sound.getStepResourcePath() : sound.func_150496_b(); world.playSoundEffect(x, y, z, newName, volume, pitch * sound.getPitch()); } } world.playSoundEffect(x, y, z, soundName, volume, pitch); } } public static void playFX(World world, EntityPlayer player, int id, int x, int y, int z, int data) { if (RailcraftConfig.playSounds()) world.playAuxSFXAtEntity(player, id, x, y, z, data); } }
jackh001/Aspose
Examples/src/main/java/com/aspose/pdf/examples/AsposePdfExamples/Text/ReplaceOnlyFirstOccurrenceOfThePhrase.java
<gh_stars>10-100 package com.aspose.pdf.examples.AsposePdfExamples.Text; import com.aspose.pdf.Color; import com.aspose.pdf.Document; import com.aspose.pdf.FontRepository; import com.aspose.pdf.TextFragment; import com.aspose.pdf.TextFragmentAbsorber; import com.aspose.pdf.TextFragmentCollection; public class ReplaceOnlyFirstOccurrenceOfThePhrase { public static void main(String[] args) { // open document Document pdfDocument = new Document("input.pdf"); // create TextAbsorber object to find all instances of the input search // phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("line"); // accept the absorber for first page of document pdfDocument.getPages().accept(textFragmentAbsorber); // get the extracted text fragments into collection TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments(); // get first occurrence of text and replace TextFragment textFragment = textFragmentCollection.get_Item(1); // update text and other properties textFragment.setText("New Pharase"); textFragment.getTextState().setFont(FontRepository.findFont("Verdana")); textFragment.getTextState().setFontSize(22); textFragment.getTextState().setForegroundColor(Color.getBlue()); textFragment.getTextState().setBackgroundColor(Color.getGray()); // save updated PDF file pdfDocument.save("Text_Updated.pdf"); } /* // Info // accept the absorber for first page of document pdfDocument.getPages().get_Item(1).accept(textFragmentAbsorber); // Info * */ }
qbox/drone
yaml/transform/filter.go
<reponame>qbox/drone package transform import ( "github.com/drone/drone/model" "github.com/drone/drone/yaml" ) // ChangeFilter is a transform function that alters status constraints set to // change and replaces with the opposite of the prior status. func ChangeFilter(conf *yaml.Config, prev string) { for _, step := range conf.Pipeline { for i, status := range step.Constraints.Status.Include { if status != "change" && status != "changed" { continue } if prev == model.StatusFailure { step.Constraints.Status.Include[i] = model.StatusSuccess } else { step.Constraints.Status.Include[i] = model.StatusFailure } } } } // DefaultFilter is a transform function that applies default Filters to each // step in the Yaml specification file. func DefaultFilter(conf *yaml.Config) { for _, step := range conf.Pipeline { defaultStatus(step) defaultEvent(step) } } // defaultStatus sets default status conditions. func defaultStatus(c *yaml.Container) { if !isEmpty(c.Constraints.Status) { return } c.Constraints.Status.Include = []string{ model.StatusSuccess, } } // defaultEvent sets default event conditions. func defaultEvent(c *yaml.Container) { if !isEmpty(c.Constraints.Event) { return } if isPlugin(c) && !isClone(c) { c.Constraints.Event.Exclude = []string{ model.EventPull, } } } // helper function returns true if the step is a clone step. func isEmpty(c yaml.Constraint) bool { return len(c.Include) == 0 && len(c.Exclude) == 0 } // helper function returns true if the step is a plugin step. func isPlugin(c *yaml.Container) bool { return len(c.Commands) == 0 || len(c.Vargs) != 0 } // helper function returns true if the step is a command step. func isCommand(c *yaml.Container) bool { return len(c.Commands) != 0 } // helper function returns true if the step is a clone step. func isClone(c *yaml.Container) bool { return c.Name == "clone" }
ricardolopezb/tp-prog-gpo6-FINAL
test/de/fhpotsdam/utils/InteractiveCentroidTestApp.java
package de.fhpotsdam.utils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import processing.core.PApplet; import processing.core.PVector; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.GeoUtils; import de.fhpotsdam.unfolding.utils.MapUtils; import de.fhpotsdam.unfolding.utils.ScreenPosition; public class InteractiveCentroidTestApp extends PApplet { UnfoldingMap map; List<Location> locations = new ArrayList<Location>(); public void setup() { size(800, 600); smooth(); map = new UnfoldingMap(this); MapUtils.createDefaultEventDispatcher(this, map); } public void draw() { background(0); map.draw(); fill(0); List<PVector> vertices = new ArrayList<PVector>(); for (Location location : locations) { ScreenPosition pos = map.getScreenPosition(location); ellipse(pos.x, pos.y, 10, 10); vertices.add(pos); } fill(0, 100); beginShape(); for (PVector pos : vertices) { vertex(pos.x, pos.y); } endShape(); Location centroid = GeoUtils.getCentroid(locations); ScreenPosition centroidPos = map.getScreenPosition(centroid); fill(255, 0, 0); ellipse(centroidPos.x, centroidPos.y, 10, 10); PVector centroidPos1 = getCentroidOfPolygon(vertices); fill(0, 255, 0); ellipse(centroidPos1.x, centroidPos1.y, 10, 10); } public void mouseClicked() { Location location = map.getLocation(mouseX, mouseY); locations.add(location); } public void keyPressed() { println(locations); } public static PVector getCentroidOfPolygon(List<PVector> originalVertices) { List<PVector> vertices = getClosedPolygon(originalVertices); float cx = 0f, cy = 0f; for (int i = 0; i < vertices.size() - 1; i++) { PVector vi0 = vertices.get(i); PVector vi1 = vertices.get(i + 1); cx = cx + (vi0.x + vi1.x) * (vi0.x * vi1.y - vi0.y * vi1.x); cy = cy + (vi0.y + vi1.y) * (vi0.x * vi1.y - vi0.y * vi1.x); } float area = getArea(vertices); cx /= (6f * area); cy /= (6f * area); return new PVector(cx, cy); } public static List<PVector> getClosedPolygon(List<PVector> originalVertices) { if (originalVertices.size() < 1 || (originalVertices.get(0).equals(originalVertices.get(originalVertices.size() - 1)))) { // Return unchanged, if only one point, or already closed return originalVertices; } List<PVector> vertices = new ArrayList<PVector>(originalVertices.size() + 1); for (int i = 0; i < originalVertices.size(); i++) { vertices.add(new PVector()); } Collections.copy(vertices, originalVertices); if (vertices.size() > 1) { if (!vertices.get(0).equals(vertices.get(vertices.size() - 1))) { // Add first vertex on last position to close polygon vertices.add(vertices.get(0)); } } return vertices; } public static float getArea(List<PVector> vertices) { float sum = 0; for (int i = 0; i < vertices.size() - 1; i++) { PVector vi0 = vertices.get(i); PVector vi1 = vertices.get(i + 1); sum += (vi0.x * vi1.y - vi1.x * vi0.y); } return sum * 0.5f; } }
bear1704/DX11_Portfolio
include/maxsdk/Rendering/Renderer.h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include "../MaxHeap.h" #include "../Object.h" #pragma warning(push) #pragma warning(disable:4100) class RendParamDlg; class IRendParams; class ITargetedIO; class IInteractiveRender; /*! Describes a default light. An array of these default lights is passed into the method Renderer::Open(). \n\n Note: In 3ds Max 3.0 the production renderer has been modified so that if a DefaultLight is passed into Renderer::Open() with a transformation matrix that is all zeros, the renderer will interpret this to mean that on each frame it should create a light located at the view point, pointing in the view direction. This allows the implementation of the new viewport 1-light option so that it tracks the camera during an animated camera move. \see Class Renderer, Class Matrix3, Structure LightState. */ class DefaultLight : public MaxHeapOperators { public: LightState ls; //!< Describes the properties of the light. Matrix3 tm; //!< The transformation of the light that controls its position in the scene. }; //============================================================================== // class Renderer // //! \brief This is the base class for any renderer plugin. /*! The main entry points for this class are methods Open(), Render(), and Close(). Any render operation works as follows: 1. Open() is called exactly once. 2. Render() is called zero or more times. 3. Close() is called exactly once. */ /*! \sa Class ReferenceTarget, Class FrameRendParams, Class RendProgressCallback, Class IRendParams, Class INode, Class ViewParams, Class RendParamDlg, Class RendParams, Class DefaultLight.\n\n \par Description: This is the base class for the creation of plug-in renderers. There are five methods that need to be implemented: Open(), Render(), Close(), CreateParamDialog() and ResetParams(). */ class Renderer : public ReferenceTarget { public: //! \brief Returns the super class ID RENDERER_CLASS_ID. SClass_ID SuperClassID() {return RENDERER_CLASS_ID;} //! \brief Called once and only once per render operation; used to initialize the renderer //! before rendering a sequence of frames. /*! This gives a chance to the renderer to build any data structures which it will need in the rendering phase. If this call returns 0, then the caller is not required to call Close(), so Open() should do any necessary cleanup before returning 0. \param[in] scene - The root node of the scene to render. Note: If you are rendering in the Materials Editor, you'll instead get a pointer to the INode that is in the sample slot - not the root node of the scene. \param[in] vnode - The view node. This may be a camera, a light, or NULL. \param[in] viewPar - View parameters for rendering orthographic or user viewports. This is used if vnode is NULL. \param[in] rp - This class contains a set of common renderer parameters. \param[in] hwnd - The owner window for messages. \param[in] defaultLights - An array of default lights if there are no user created lights in the scene. \param[in] numDefLights - Number of lights in defaultLights array. \param[in] prog - A callback used to allow the renderer to update the progress dialog. \return Nonzero for success, zero for failure. */ virtual int Open( INode *scene, INode *vnode, ViewParams *viewPar, RendParams &rp, HWND hwnd, DefaultLight* defaultLights=NULL, int numDefLights=0, RendProgressCallback* prog = NULL ) = 0; //! \brief Called to render a single frame. /*! This may be called zero or more times, in between calls to Open() and Close(), to render a sequence of frames, at a series of time values which are not necessarily sequential. \param[in] t - The time at which this frame is to be rendered. \param[in] tobm - The bitmap to which the image is to be rendered. \param[in] frp - A set of frame dependent parameters. \param[in] hwnd - The owner window handle. \param[in] prog - A callback used to allow the renderer to update the progress dialog. \param[in] viewPar - This parameter allows one to specify a different view transformation on each render call. For example, one may render a given scene at a given time from many different viewpoints, without calling Render::Open() for each one. \return Nonzero for success, zero for failure. */ virtual int Render( TimeValue t, Bitmap *tobm, FrameRendParams &frp, HWND hwnd, RendProgressCallback *prog=NULL, ViewParams *viewPar=NULL )=0; //! \brief Called once and only once per render operation; used to free any resources //! allocated by Open() or Render(). /*! This method needs to be called whenever Open() was called and returned a non-zero value. The renderer should free any allocated resources, returning in a state identical to the one before Open() was called. \param[in] hwnd - The owner window handle. \param[in] prog - A callback used to allow the renderer to update the progress dialog. \return Nonzero for success, zero for failure. */ virtual void Close( HWND hwnd, RendProgressCallback* prog = NULL )=0; //! \brief This method is called to apply the render effects at the specified time value. /*! It should be called between the Open() and Close() methods.\n\n This can be used during a multi-pass rendering, in order to apply the render effects to the final, blended bitmap. \par Parameters: \param t - The time to apply the render effects. \param pBitmap - Points to the bitmap. \param updateDisplay - Passing true indicates that Bitmap's display should be refreshed by the renderer; false indicates it should not be. \return Returns true if the effects were successfully applied; otherwise false. */ virtual bool ApplyRenderEffects(TimeValue t, Bitmap* pBitmap, bool updateDisplay=true) { return false; } //! \brief This method is called to create and return a pointer to an instance of the //! RendParamDlg class. /*! The renderer can add rollup page(s) to the renderer configuration dialog using the IRendParams interface passed into this method. \param ir - An interface that provides methods for use in displaying parameters, for example this class has methods for adding rollup pages. \param prog - If TRUE then the rollup page should just display the parameters so the user has them for reference while rendering, they should not be editable. \return A pointer to an instance of the <b>RendParamDlg</b> class. This class will be deleted using RendParamDlg::DeleteThis(). */ virtual RendParamDlg *CreateParamDialog(IRendParams *ir,BOOL prog=FALSE)=0; //! This method simply sets all the parameters to their default values. virtual void ResetParams()=0; virtual int GetAAFilterSupport(){ return 0; } // point sample, no reconstruction filter //! \brief Renderers which support texture baking should override this method to return true. /*! It is checked when the Render to Texture dialog is opened; if the current renderer does not support texture baking, then a warning message is displayed and the user will not be able to press the Render button in the dialog. \return By default this will return false */ virtual bool SupportsTexureBaking() { return false; } //! \brief A renderer should override this method to return true if it supports any custom preset categories beyond the standard categories. /*! \return By default this will returns false */ virtual bool SupportsCustomRenderPresets() { return false; } //! \brief Return a number indicating the current version of the renderer's custom preset. /*! The number can be arbitrary \return By default this will return -1 */ virtual int RenderPresetsFileVersion() { return -1; } //! \brief Return true if the renderer can load presets of the indicated version. /*! \param version The version to test compatibility against \return By default this will return false. */ virtual BOOL RenderPresetsIsCompatible( int version ) { return false; } //! \brief Returns the UI name of a supported custom category /*! \param catIndex - The custom preset index to return the name of. catIndex will be a number between RENDER_PRESETS_CUSTOM_CATEGORY_INDEX_BEGIN and RENDER_PRESETS_CATEGORY_COUNT. \return If the ID is a supported custom category, return the name of the category to be displayed in the UI. Otherwise return NULL */ virtual const MCHAR* RenderPresetsMapIndexToCategory( int catIndex ) { return NULL; } //! \brief Returns the index of a supported custom category /*! \param category - The UI name of a custom category \return If the input is the name of a custom category supported by the renderer, return the ID number of the category. Otherwise returns 0 */ virtual int RenderPresetsMapCategoryToIndex( const MCHAR* category ) { return 0; } //! \brief called before a render preset is saved. /*! For each custom category supported use root->AddSaveTarget() passing the object with the parameters for that category if the corresponding bit is set in the saveCategories, The object will be saved along with the preset. \par Example Implementation: \code { // Iterate through all our possible custom preset indices for (int i = RENDER_PRESETS_CUSTOM_CATEGORY_INDEX_BEGIN; i < RENDER_PRESETS_CUSTOM_CATEGORY_INDEX_BEGIN + MY_CUSTOM_PRESET_COUNT; i++) { // Should the preset be saved? if (saveCategories[i]) { // p_myOptions is a class derived from ReferenceTarget that contains our options. root->AddSaveTarget(i, p_myOptions); } } } \endcode \param root An instance of an ITargetedIO class to be used to save any custom presets specified \param saveCategories Species the custom preset categories to be saved */ virtual int RenderPresetsPreSave( ITargetedIO * root, BitArray saveCategories ) { return -1; } //! \brief called after a preset is saved. /*! No specific action is required from the renderer at this time. \sa RenderPresetsPreSave */ virtual int RenderPresetsPostSave( ITargetedIO * /*root*/, BitArray /*loadCategories*/ ) { return -1; } //! \brief called before a preset is loaded. /*! For each custom category supported, if the corresponding bit is not set in the loadCategories, use root->Store() passing the object with the parameters for that category. The object will be preserved, so the renderer can refer to it after the preset is loaded. \sa RenderPresetsPreSave, RenderPresetsPostLoad \param root An instance of an ITargetedIO class to be used to store any custom presets specified \param saveCategories Lists the custom preset categories to be loaded. Any categories not being loaded should be stored on root. */ virtual int RenderPresetsPreLoad( ITargetedIO * root, BitArray saveCategories ) { return -1; } //! \brief called after a preset is loaded. /*! For each custom category supported...\n\n If the bit is set in the loadCategories: use root->GetSaveTarget() to retrieve the loaded object, and update the renderer's active parameters to match this object\n\n If the bit is not set in the loadCategories: use root->Retrieve() to retrieve the object that was stored during pre-load. Update the renderer's active parameters to match this object. This is important in case a certain category was held in the file and loaded, but the user did not choose to load that category. In this case the renderer must restore its parameters to their former value. \sa RenderPresetsPreLoad \param root An instance of an ITargetedIO class to be used to retrieve any custom presets stored pre-load. \param loadCategories Lists the custom preset categories that have been loaded. */ virtual int RenderPresetsPostLoad( ITargetedIO * root, BitArray loadCategories ) { return -1; } //! \name Stopping and Pausing a Render //! See \ref stopping_pausing_renderer /*! \page stopping_pausing_renderer Stopping and pausing a renderer <b>Stopping functionality</b> is meant for progressive renderers which may be stopped manually at any time. Renderers such as path tracers may be set to render indefinitely, in which case the only way to stop rendering is through this functionality. Stopping a renderer differs from canceling/aborting in that a stopped render is considered successful, finished, complete. Stopping a progressive renderer is equivalent to reaching a pre-set termination criterion, such as time or number of iterations. Following a stop, the rendered image will be saved, the render elements will be processed, and the next frame of the animation sequence will be rendered - all things that do not happen upon canceling a render. <b>Pausing functionality</b> enables a user to temporarily interrupt the rendering process, freeing computer resources to perform other tasks. 3ds Max has long supported the pausing of renderers through a wait loop in the call to RendProgressCallback:Progress(), however this functionality is not well suited for all renderers. These methods below supersede the legacy functionality; a renderer that supports pausing through this interface will not see the progress callback perform a wait loop when the renderer is paused. */ //@{ /*! Returns true if and only the renderer supports the stop functionality, in which case the Stop button will be displayed in the render progress dialog, and StopRendering() may be called. \remark This method may only be called from the main thread. \sa \ref stopping_pausing_renderer */ virtual bool IsStopSupported() const = 0; /*! Called to instruct the renderer to stop rendering. The renderer is expected to stop rendering at its earliest convenience. If, for example, the renderer is in the process of rendering an iteration, it may finish rendering this iteration (or not), as it wishes - so long as it outputs a valid rendered image representing the progress rendered so far. \remark \li This method may only be called from the main thread. \li The renderer should take special care of supporting a stop while the renderer is paused; the user should not need to manually resume for a stop to function properly. \li This method is asynchronously called, and should return immediately; it must not wait for the rendering process to actually be stopped. \sa \ref stopping_pausing_renderer */ virtual void StopRendering() = 0; /*! Returns whether pause is supported by this renderer. \remark \li This method may only be called from the main thread. \sa \ref stopping_pausing_renderer */ enum class PauseSupport { //! This renderer does not support pausing, in which case the Pause button will be disabled or hidden. None, //! Full support for pausing, in which case pressing the Pause button will result in PauseRendering() being called. Full, //! Legacy support for pausing, which involves the progress callback hanging to forcibly pause the renderer. This only //! works if the renderer uses the progess callback in a synchronous manner. PauseRendering() may still be called. Legacy }; virtual PauseSupport IsPauseSupported() const = 0; /*! Requests that the renderer pauses itself, at which point it should stop rendering and free CPU resources until a resume is requested. \remark \li This method may only be called from the main thread. \li Abort or Stop events may be received while the renderer is paused. Those should be processed correctly. \li It is possible for this method to be called while the renderer is already paused. The implementation should handle that correctly. \sa \ref stopping_pausing_renderer */ virtual void PauseRendering() = 0; /*! Requests that the renderer resumes rendering, following a call to PauseRendering(). \remark \li This method may only be called from the main thread. \li It is possible for this method to be called while the renderer is not currently paused. The implementation should handle that correctly. \sa \ref stopping_pausing_renderer */ virtual void ResumeRendering() = 0; //@} //! \name Renderer Requirements //! Renderer requirements are special flags which the application may query to determine whether a renderer supports certain features, //! or to modify the behaviour of the application depending no the renderer's needs. //@{ enum Requirement { // This flag is deprecated in 3ds Max 2017. It is replaced by Renderer::IsPauseSupported() //kRequirement_NoPauseSupport = 0, /** Indicates that the VFB shouldn't be popped-up after rendering, even if * "Show VFB" is ON in the common render parameters. This is useful for * renderers which generate something other than an image. * Note that this also affects render element VFBs.*/ kRequirement_NoVFB = 1, /** Indicates that the rendered image shouldn't be saved after rendering, even * if a file was specified in the common render parameters. This is useful for * renderers which generate something other than an image. * Note that this also affects render element outputs.*/ kRequirement_DontSaveRenderOutput = 2, /** Indicates the renderer wants a 32bit floating-point RGBA frame buffer to be * created for output. The render executer will query the renderer and will create a * 32bit floating-point frame buffer, instead of a 16bit integer buffer, if the * renderer returns true for this requirement. * Note that there is no guarantee about the frame buffer type: even if the renderer * returns true for this requirement, a 16bit integer buffer could still be created.*/ kRequirement_Wants32bitFPOutput = 3, /** Indicates the renderer wants an object selection for rendering. * The render executer will throw an error message when the renderer indicates * this requirement, and no objects are selected. */ kRequirement_WantsObjectSelection = 4, /** Flags the renderer as not supporting GBuffers when processing the exposure control preview. By default, the exposure control preview * uses GBuffers to re-compose the image whenever the exposure parameters change. This enables it to effectively re-compose the background * into the rendered image with good fidelity. But should this requirement be set, the exposure control preview will switch to an alternate * method which uses the alpha channel to extract the background from the rendered image. The results will not be as good but are generally * sufficient for the sake of previewing. */ kRequirement_NoGBufferForToneOpPreview = 5, /** Enables the concurrent/parallel rendering of ActiveShade and material editor previews for this renderer. */ kRequirement_SupportsConcurrentRendering = 6, }; //! Returns true if the renderer has the given requirement, or returns false otherwise. virtual bool HasRequirement(Requirement requirement) = 0; //@} //! \name Renderer Element Support //@{ //! Returns whether this renderer plugin is compatible with any render elements whatsoever. //! This affects whether the render elements tab is displayed at all. virtual bool CompatibleWithAnyRenderElement() const = 0; //! Returns whether this renderer plugin is compatible with the given render element. //! \param pIRenderElement The render element for which to verify compatibility. virtual bool CompatibleWithRenderElement(IRenderElement& pIRenderElement) const = 0; //@} //! \name Interactive Rendering (Active Shade) //@{ //! \brief Returns the interface used for interactive rendering. /*! This method returns a pointer to an IInteractiveRender, the interface used to perform interactive rendering (aka Active Shade). Ownership of the interface remains with the Renderer, i.e. the Renderer is responsible for freeing this interface, if necessary, in its destructor. Consequently, every call to this method should return the same pointer value - there is a one-to-one association between classes IInteractiveRenderer and Renderer. \remark Should return null if interactive rendering is not supported by the renderer. */ virtual IInteractiveRender* GetIInteractiveRender() = 0; //@} //! \name Renderer Information //@{ //! \brief Get renderer name, provider, version, etc. //! \remarks If the string is longer than 32-character, it will be trunked on Render Message Window //! \param info The returned string containing the vendor info. virtual void GetVendorInformation(MSTR& info) const = 0; //! \brief Platform information concerning the renderer. //! \remarks It could be information of OS, CPU, GPU, etc. //! If the string is longer than 32-character, it will be trunked on Render Message Window. //! \param info The returned string containing the platform info. virtual void GetPlatformInformation(MSTR& info) const = 0; //@} }; #pragma warning(pop)
UW-MAGIC-lab/hidden_village
src/components/Settings.js
<gh_stars>0 const Settings = () => { return <div>You made it to the setting page!</div>; }; export default Settings;
fabric8io/fabric8-declarative-pipeline-step-functions
src/main/java/io/fabric8/pipeline/steps/PromoteImages.java
/** * Copyright (C) Original Authors 2017 * * 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 io.fabric8.pipeline.steps; import com.google.common.base.Strings; import io.fabric8.Fabric8Commands; import io.fabric8.Fabric8FunctionSupport; import io.jenkins.functions.runtime.FunctionSupport; import io.fabric8.pipeline.steps.model.ServiceConstants; import io.jenkins.functions.Argument; import io.jenkins.functions.Step; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Function; import static com.google.common.base.Strings.isNullOrEmpty; /** * Promote images */ @Step(displayName = "Promotes docker images to a docker registry like hub.docker.com") public class PromoteImages extends Fabric8FunctionSupport implements Function<PromoteImages.Arguments, String> { public PromoteImages() { } public PromoteImages(FunctionSupport parentStep) { super(parentStep); } @Override @Step public String apply(Arguments config) { final List<String> images = config.getImages(); final String tag = config.getTag(); final String org = config.getOrg(); final String toRegistry = config.getToRegistry(); if (Strings.isNullOrEmpty(tag)) { error("No tag specified for tagImages step for images " + images); return null; } if (isNullOrEmpty(org)) { error("Docker Organisation config missing so cannot promote images " + images); return null; } if (isNullOrEmpty(toRegistry)) { error("Promote To Docker Registry config missing so cannot promote images " + images); return null; } return container("docker", () -> { Fabric8Commands flow = new Fabric8Commands(PromoteImages.this); for (final String image : images) { if (flow.isSingleNode()) { sh("docker tag " + org + "/" + image + ":" + tag + " " + toRegistry + "/" + org + "/" + image + ":" + tag); } else { String registryHost = ServiceConstants.getDockerRegistryHost(); String registryPort = ServiceConstants.getDockerRegistryPort(); sh("docker pull " + registryHost + ":" + registryPort + "/fabric8/" + image + ":" + tag); sh("docker tag " + registryHost + ":" + registryPort + "/" + org + "/" + image + ":" + tag + " " + toRegistry + "/" + org + "/" + image + ":" + tag); } retry(3, (Callable<String>) () -> { sh("docker push " + toRegistry + "/" + org + "/" + image + ":" + tag); return null; }); } return null; }); } public static class Arguments { @Argument private String tag = ""; @Argument private String org = ""; @Argument private String toRegistry = ""; @Argument private List<String> images = new ArrayList<>(); public Arguments() { } public Arguments(String tag, String org, String toRegistry, List<String> images) { this.tag = tag; this.org = org; this.toRegistry = toRegistry; this.images = images; } public List<String> getImages() { return images; } public void setImages(List<String> images) { this.images = images; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getOrg() { return org; } public void setOrg(String org) { this.org = org; } public String getToRegistry() { return toRegistry; } public void setToRegistry(String toRegistry) { this.toRegistry = toRegistry; } } }
Alexey-N-Chernyshov/cpp-libp2p
include/libp2p/peer/protocol_repository/inmem_protocol_repository.hpp
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef LIBP2P_INMEM_PROTOCOL_REPOSITORY_HPP #define LIBP2P_INMEM_PROTOCOL_REPOSITORY_HPP #include <set> #include <unordered_map> #include <libp2p/peer/protocol_repository.hpp> namespace libp2p::peer { /** * @brief In-memory implementation of Protocol repository. For each peer * stores ordered set of protocols. */ class InmemProtocolRepository : public ProtocolRepository { public: ~InmemProtocolRepository() override = default; outcome::result<void> addProtocols(const PeerId &p, gsl::span<const Protocol> ms) override; outcome::result<void> removeProtocols( const PeerId &p, gsl::span<const Protocol> ms) override; outcome::result<std::vector<Protocol>> getProtocols( const PeerId &p) const override; outcome::result<std::vector<Protocol>> supportsProtocols( const PeerId &p, const std::set<Protocol> &protocols) const override; void clear(const PeerId &p) override; void collectGarbage() override; std::unordered_set<PeerId> getPeers() const override; private: using set = std::set<Protocol>; using set_ptr = std::shared_ptr<set>; outcome::result<set_ptr> getProtocolSet(const PeerId &p) const; set_ptr getOrAllocateProtocolSet(const PeerId &p); std::unordered_map<PeerId, set_ptr> db_; }; } // namespace libp2p::peer #endif // LIBP2P_INMEM_PROTOCOL_REPOSITORY_HPP
iamzken/aliyun-openapi-cpp-sdk
dypnsapi/src/model/TwiceTelVerifyResult.cc
<gh_stars>10-100 /* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/dypnsapi/model/TwiceTelVerifyResult.h> #include <json/json.h> using namespace AlibabaCloud::Dypnsapi; using namespace AlibabaCloud::Dypnsapi::Model; TwiceTelVerifyResult::TwiceTelVerifyResult() : ServiceResult() {} TwiceTelVerifyResult::TwiceTelVerifyResult(const std::string &payload) : ServiceResult() { parse(payload); } TwiceTelVerifyResult::~TwiceTelVerifyResult() {} void TwiceTelVerifyResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto twiceTelVerifyResultNode = value["TwiceTelVerifyResult"]; if(!twiceTelVerifyResultNode["Carrier"].isNull()) result_.carrier = twiceTelVerifyResultNode["Carrier"].asString(); if(!twiceTelVerifyResultNode["VerifyResult"].isNull()) result_.verifyResult = std::stoi(twiceTelVerifyResultNode["VerifyResult"].asString()); if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string TwiceTelVerifyResult::getMessage()const { return message_; } TwiceTelVerifyResult::Result TwiceTelVerifyResult::getTwiceTelVerifyResult()const { return twiceTelVerifyResult_; } std::string TwiceTelVerifyResult::getCode()const { return code_; }
riteshiosdev/iOS-UIKit
Chat/ChatSecure-iOS-master/ChatSecure/Strings/Strings.h
#import "OTRLanguageManager.h" // DO NOT EDIT THIS FILE. EDIT strings.json then run python StringsConverter.py #define errSSLCryptoString [OTRLanguageManager translatedString: @"Underlying cryptographic error"] #define OFFLINE_STRING [OTRLanguageManager translatedString: @"Offline"] #define ERROR_STRING [OTRLanguageManager translatedString: @"Error!"] #define LOGOUT_STRING [OTRLanguageManager translatedString: @"Log Out"] #define DELETE_CONVERSATIONS_ON_DISCONNECT_TITLE_STRING [OTRLanguageManager translatedString: @"Auto-delete"] #define DONE_STRING [OTRLanguageManager translatedString: @"Done"] #define noErrString [OTRLanguageManager translatedString: @"No Error"] #define CHATSECURE_PUSH_STRING [OTRLanguageManager translatedString: @"ChatSecure Push"] #define CONVERSATION_NO_LONGER_SECURE_STRING [OTRLanguageManager translatedString: @"The conversation with %@ is no longer secure."] #define USER_PASS_BLANK_STRING [OTRLanguageManager translatedString: @"You must enter a username and a password to login."] #define THEIR_FINGERPRINT_STRING [OTRLanguageManager translatedString: @"Purported fingerprint for"] #define errSSLPeerAuthCompletedString [OTRLanguageManager translatedString: @"Peer cert is valid, or was ignored if verification disabled"] #define PASSWORD_STRING [OTRLanguageManager translatedString: @"Password"] #define ADVANCED_STRING [OTRLanguageManager translatedString: @"Advanced"] #define OTRL_MSGEVENT_ENCRYPTION_REQUIRED_STRING [OTRLanguageManager translatedString: @"Our policy requires encryption but we are trying to send an unencrypted message out."] #define VERSION_STRING [OTRLanguageManager translatedString: @"Version"] #define ACCOUNT_DISCONNECTED_STRING [OTRLanguageManager translatedString: @"Account Disconnected"] #define INITIATE_ENCRYPTED_CHAT_STRING [OTRLanguageManager translatedString: @"Initiate Encrypted Chat"] #define INVALID_EMAIL_TITLE_STRING [OTRLanguageManager translatedString: @"Invalid Email"] #define OTRL_MSGEVENT_CONNECTION_ENDED_STRING [OTRLanguageManager translatedString: @"Message has not been sent because our buddy has ended the private conversation. We should either close the connection, or refresh it."] #define ACCOUNT_DISCONNECTED_DESCRIPTION_STRING [OTRLanguageManager translatedString: @"Please log into this account before managing requests."] #define ADD_STRING [OTRLanguageManager translatedString: @"Add"] #define OTRL_MSGEVENT_RCVDMSG_FOR_OTHER_INSTANCE_STRING [OTRLanguageManager translatedString: @"Received and discarded a message intended for another instance."] #define OPEN_IN_TWITTER_STRING [OTRLanguageManager translatedString: @"Open in Twitter"] #define TWITTER_STRING [OTRLanguageManager translatedString: @"Twitter"] #define CONNECTED_STRING [OTRLanguageManager translatedString: @"Connected"] #define TOR_WARNING_MESSAGE_STRING [OTRLanguageManager translatedString: @"Tor is an experimental feature, please use with caution."] #define EXTENDED_AWAY_STRING [OTRLanguageManager translatedString: @"Extended Away"] #define OTRL_MSGEVENT_MSG_REFLECTED_STRING [OTRLanguageManager translatedString: @"Received our own OTR messages."] #define errSSLClosedNoNotifyString [OTRLanguageManager translatedString: @"Server closed session with no notification"] #define PUBLIC_KEY_ERROR_STRING [OTRLanguageManager translatedString: @"Could not retrieve public key from certificate"] #define OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE_STRING [OTRLanguageManager translatedString: @"Received an encrypted message but cannot read it because no private connection is established yet."] #define NEW_CERTIFICATE_STRING [OTRLanguageManager translatedString: @"New SSL Certificate"] #define LOGIN_STRING [OTRLanguageManager translatedString: @"Log In"] #define CANCEL_STRING [OTRLanguageManager translatedString: @"Cancel"] #define LOGIN_AUTOMATICALLY_STRING [OTRLanguageManager translatedString: @"Login Automatically"] #define errSSLPeerDecodeErrorString [OTRLanguageManager translatedString: @"Decoding error"] #define iOS_SSL_ERROR_PART1_STRING [OTRLanguageManager translatedString: @"Your current iOS system version (%@) contains a serious security vulnerability. Please update to the latest version as soon as possible."] #define errSSLRecordOverflowString [OTRLanguageManager translatedString: @"Record overflow"] #define errSSLDecryptionFailString [OTRLanguageManager translatedString: @"Decryption failure"] #define CONNECT_EXISTING_STRING [OTRLanguageManager translatedString: @"Connect to Existing Account"] #define GITHUB_STRING [OTRLanguageManager translatedString: @"GitHub"] #define OPEN_IN_FACEBOOK_STRING [OTRLanguageManager translatedString: @"Open in Facebook"] #define errSSLHostNameMismatchString [OTRLanguageManager translatedString: @"Peer host name mismatch"] #define CONVERSATION_SECURE_WARNING_STRING [OTRLanguageManager translatedString: @"This chat is secured"] #define PINNED_CERTIFICATES_STRING [OTRLanguageManager translatedString: @"Pinned Certificates"] #define DELETE_ACCOUNT_MESSAGE_STRING [OTRLanguageManager translatedString: @"Permanently delete"] #define OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR_STRING [OTRLanguageManager translatedString: @"Received a general OTR error."] #define CREATED_BY_STRING [OTRLanguageManager translatedString: @"Created by"] #define UNLOCKED_ALERT_STRING [OTRLanguageManager translatedString: @"The conversation is not secure"] #define SAVE_STRING [OTRLanguageManager translatedString: @"Save"] #define errSSLNoRootCertString [OTRLanguageManager translatedString: @"Cert chain not verified by root"] #define ACCOUNTS_STRING [OTRLanguageManager translatedString: @"Accounts"] #define PENDING_APPROVAL_STRING [OTRLanguageManager translatedString: @"Pending Approval"] #define errSSLPeerDecryptionFailString [OTRLanguageManager translatedString: @"Decryption failed"] #define JABBER_STRING [OTRLanguageManager translatedString: @"Jabber (XMPP)"] #define VERIFY_STRING [OTRLanguageManager translatedString: @"Verify"] #define errSSLCertExpiredString [OTRLanguageManager translatedString: @"Chain had an expired cert"] #define errSSLBadConfigurationString [OTRLanguageManager translatedString: @"Configuration error"] #define ADD_BUDDY_STRING [OTRLanguageManager translatedString: @"Add Buddy"] #define errSSLClientCertRequestedString [OTRLanguageManager translatedString: @"Server has requested a client cert"] #define XMPP_TOR_STRING [OTRLanguageManager translatedString: @"XMPP + Tor"] #define REGISTER_ERROR_STRING [OTRLanguageManager translatedString: @"Error Registering Username"] #define OTRL_MSGEVENT_RCVDMSG_UNREADABLE_STRING [OTRLanguageManager translatedString: @"Cannot read the received message."] #define errSSLPeerProtocolVersionString [OTRLanguageManager translatedString: @"Bad protocol version"] #define TOR_DOMAIN_WARNING_MESSAGE_STRING [OTRLanguageManager translatedString: @"Only one Tor account per domain is supported at this time."] #define CHANGE_PASSPHRASE_STRING [OTRLanguageManager translatedString: @"Change Passphrase"] #define RECENT_STRING [OTRLanguageManager translatedString: @"Recent"] #define errSSLBufferOverflowString [OTRLanguageManager translatedString: @"Insufficient buffer provided"] #define COPY_STRING [OTRLanguageManager translatedString: @"Copy"] #define CONNECTING_STRING [OTRLanguageManager translatedString: @"Connecting"] #define LOCKED_WARN_STRING [OTRLanguageManager translatedString: @"The fingerprint has not been verified"] #define UNLOCK_STRING [OTRLanguageManager translatedString: @"Unlock"] #define DONATE_MESSAGE_STRING [OTRLanguageManager translatedString: @"Your donation will help fund the continued development of ChatSecure."] #define DONATE_STRING [OTRLanguageManager translatedString: @"Donate"] #define REJECT_STRING [OTRLanguageManager translatedString: @"Reject"] #define errSSLIllegalParamString [OTRLanguageManager translatedString: @"Illegal parameter"] #define CREATE_STRING [OTRLanguageManager translatedString: @"Create"] #define RESOURCE_STRING [OTRLanguageManager translatedString: @"Resource"] #define errSSLPeerAccessDeniedString [OTRLanguageManager translatedString: @"Access denied"] #define errSSLPeerInternalErrorString [OTRLanguageManager translatedString: @"Internal error"] #define OTRL_MSGEVENT_ENCRYPTION_ERROR_STRING [OTRLanguageManager translatedString: @"An error occured while encrypting a message and the message was not sent."] #define VERIFY_FINGERPRINT_STRING [OTRLanguageManager translatedString: @"Verify Fingerprint"] #define SAVED_CERTIFICATES_STRING [OTRLanguageManager translatedString: @"Saved Certificates"] #define NEW_ACCOUNT_STRING [OTRLanguageManager translatedString: @"New Account"] #define DOMAIN_BLANK_ERROR_STRING [OTRLanguageManager translatedString: @"Domain needs to be set"] #define LOCKED_SECURE_STRING [OTRLanguageManager translatedString: @"The conversation is secure and the fingerprint is verfied"] #define QR_CODE_STRING [OTRLanguageManager translatedString: @"QR code"] #define AWAY_MESSAGE_STRING [OTRLanguageManager translatedString: @"is now away"] #define AWAY_STRING [OTRLanguageManager translatedString: @"Away"] #define HOSTNAME_STRING [OTRLanguageManager translatedString: @"Hostname"] #define errSSLPeerInsufficientSecurityString [OTRLanguageManager translatedString: @"Insufficient security"] #define iOS_SSL_ERROR_TITLE_STRING [OTRLanguageManager translatedString: @"iOS Vulnerability"] #define SKIP_STRING [OTRLanguageManager translatedString: @"Skip"] #define SEARCH_STRING [OTRLanguageManager translatedString: @"Search"] #define AIM_STRING [OTRLanguageManager translatedString: @"OSCAR Instant Messenger"] #define DISCONNECTION_WARNING_DESC_STRING [OTRLanguageManager translatedString: @"1 Minute Alert Before Disconnection"] #define OTRL_MSGEVENT_MSG_RESENT_STRING [OTRLanguageManager translatedString: @"The previous message was resent."] #define PAYMENTS_SETUP_ERROR_STRING [OTRLanguageManager translatedString: @"This device doesn't seem to be configured to make payments."] #define errSSLPeerRecordOverflowString [OTRLanguageManager translatedString: @"Record overflow"] #define SECURITY_STRING [OTRLanguageManager translatedString: @"Security"] #define errSSLPeerCertUnknownString [OTRLanguageManager translatedString: @"Unknown certificate"] #define ERROR_CREATING_ACCOUNT_STRING [OTRLanguageManager translatedString: @"Error Creating Account"] #define OTR_FINGERPRINTS_STRING [OTRLanguageManager translatedString: @"OTR Fingerprints"] #define errSSLPeerCertExpiredString [OTRLanguageManager translatedString: @"Certificate expired"] #define OTRL_MSGEVENT_SETUP_ERROR_STRING [OTRLanguageManager translatedString: @"A private conversation could not be set up."] #define errSSLNegotiationString [OTRLanguageManager translatedString: @"Cipher Suite negotiation failure"] #define errSSLPeerExportRestrictionString [OTRLanguageManager translatedString: @"Export restriction"] #define errSSLPeerHandshakeFailString [OTRLanguageManager translatedString: @"Handshake failure"] #define GOOGLE_TALK_STRING [OTRLanguageManager translatedString: @"Google Talk"] #define OTR_FINGERPRINTS_SUBTITLE_STRING [OTRLanguageManager translatedString: @"Manage OTR fingerprints"] #define errSSLFatalAlertString [OTRLanguageManager translatedString: @"Fatal alert"] #define iOS_SSL_ERROR_PART2_STRING [OTRLanguageManager translatedString: @"Settings -> General -> Software Update"] #define USERNAME_STRING [OTRLanguageManager translatedString: @"Username"] #define errSSLModuleAttachString [OTRLanguageManager translatedString: @"Module attach failure"] #define REMEMBER_PASSPHRASE_INFO_STRING [OTRLanguageManager translatedString: @"Your password will be stored in the iOS Keychain of this device only, and is only as safe as your device passphrase or pin. However, it will not persist during a device backup/restore via iTunes, so please don't forget it, or you may lose your conversation history."] #define SHARE_STRING [OTRLanguageManager translatedString: @"Share"] #define OPPORTUNISTIC_OTR_SETTING_TITLE [OTRLanguageManager translatedString: @"Auto-start Encryption"] #define SEND_FEEDBACK_STRING [OTRLanguageManager translatedString: @"Send Feedback"] #define NAME_STRING [OTRLanguageManager translatedString: @"Name"] #define BLOCK_STRING [OTRLanguageManager translatedString: @"Block"] #define ACCOUNT_FINGERPRINTS_STRING [OTRLanguageManager translatedString: @"Account Fingerprints"] #define OK_STRING [OTRLanguageManager translatedString: @"OK"] #define OPPORTUNISTIC_OTR_SETTING_DESCRIPTION [OTRLanguageManager translatedString: @"Enables opportunistic OTR"] #define errSSLUnexpectedRecordString [OTRLanguageManager translatedString: @"Unexpected (skipped) record in DTLS"] #define PORT_STRING [OTRLanguageManager translatedString: @"Port"] #define errSSLClosedAbortString [OTRLanguageManager translatedString: @"Connection closed via error"] #define SUBSCRIPTION_REQUEST_TITLE [OTRLanguageManager translatedString: @"Subscription Requests"] #define DELETE_ACCOUNT_TITLE_STRING [OTRLanguageManager translatedString: @"Delete Account?"] #define errSSLPeerDecompressFailString [OTRLanguageManager translatedString: @"Decompression failure"] #define errSSLPeerUnsupportedCertString [OTRLanguageManager translatedString: @"Bad unsupported cert format"] #define OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED_STRING [OTRLanguageManager translatedString: @"Received an unencrypted message."] #define errSSLPeerUnknownCAString [OTRLanguageManager translatedString: @"Unknown Cert Authority"] #define errSSLBadCipherSuiteString [OTRLanguageManager translatedString: @"Bad SSLCipherSuite"] #define OFFLINE_MESSAGE_STRING [OTRLanguageManager translatedString: @"is now offline"] #define errSSLBadRecordMacString [OTRLanguageManager translatedString: @"Bad MAC"] #define CONNECT_FACEBOOK_STRING [OTRLanguageManager translatedString: @"Connect Facebook"] #define errSSLPeerNoRenegotiationString [OTRLanguageManager translatedString: @"No renegotiation allowed"] #define EXPIRATION_STRING [OTRLanguageManager translatedString: @"Background session will expire in one minute."] #define DISCONNECT_FACEBOOK_STRING [OTRLanguageManager translatedString: @"Disconnect Facebook"] #define FACEBOOK_STRING [OTRLanguageManager translatedString: @"Facebook"] #define PUSH_TITLE_STRING [OTRLanguageManager translatedString: @"Push"] #define DUPLICATE_ACCOUNT_MESSAGE_STRING [OTRLanguageManager translatedString: @"There already exists an account with this username."] #define errSSLWouldBlockString [OTRLanguageManager translatedString: @"I/O would block (not fatal)"] #define errSSLInternalString [OTRLanguageManager translatedString: @"Internal error"] #define CONNECTING_TO_TOR_STRING [OTRLanguageManager translatedString: @"Connecting to Tor"] #define CHAT_STRING [OTRLanguageManager translatedString: @"Chat"] #define OTRL_MSGEVENT_LOG_HEARTBEAT_RCVD_STRING [OTRLanguageManager translatedString: @"Received a heartbeat."] #define DO_NOT_DISTURB_STRING [OTRLanguageManager translatedString: @"Do Not Disturb"] #define errSSLProtocolString [OTRLanguageManager translatedString: @"SSL protocol error"] #define SHARE_MESSAGE_STRING [OTRLanguageManager translatedString: @"Chat with me securely"] #define XMPP_FAIL_STRING [OTRLanguageManager translatedString: @"Failed to connect to XMPP server. Please check your login credentials and internet connection and try again."] #define OTRL_MSGEVENT_LOG_HEARTBEAT_SENT_STRING [OTRLanguageManager translatedString: @"Sent a heartbeat."] #define errSSLClosedGracefulString [OTRLanguageManager translatedString: @"Connection closed gracefully"] #define VALID_CERTIFICATE_STRING [OTRLanguageManager translatedString: @"Valid certificate"] #define NEW_STRING [OTRLanguageManager translatedString: @"New"] #define errSSLPeerUnexpectedMsgString [OTRLanguageManager translatedString: @"Unexpected message received"] #define DELETE_CONVERSATIONS_ON_DISCONNECT_DESCRIPTION_STRING [OTRLanguageManager translatedString: @"Delete chats on disconnect"] #define CHATS_STRING [OTRLanguageManager translatedString: @"Chats"] #define HELP_TRANSLATE_STRING [OTRLanguageManager translatedString: @"Help Translate"] #define NOT_VERIFIED_STRING [OTRLanguageManager translatedString: @"Not Verified"] #define errSSLPeerDecryptErrorString [OTRLanguageManager translatedString: @"Decryption error"] #define errSSLBadCertString [OTRLanguageManager translatedString: @"Bad certificate format"] #define errSSLConnectionRefusedString [OTRLanguageManager translatedString: @"Peer dropped connection before responding"] #define SECURITY_WARNING_STRING [OTRLanguageManager translatedString: @"Security Warning"] #define VERIFIED_STRING [OTRLanguageManager translatedString: @"Verified"] #define BUDDY_INFO_STRING [OTRLanguageManager translatedString: @"Buddy Info"] #define NEW_PASSPHRASE_STRING [OTRLanguageManager translatedString: @"New Passphrase"] #define ACCOUNT_STRING [OTRLanguageManager translatedString: @"Account"] #define QR_CODE_INSTRUCTIONS_STRING [OTRLanguageManager translatedString: @"This QR Code contains a link to http://omniqrcode.com/q/chatsecure and will redirect to the App Store."] #define REMEMBER_PASSWORD_STRING [OTRLanguageManager translatedString: @"Remember password"] #define CONVERSATION_NOT_SECURE_WARNING_STRING [OTRLanguageManager translatedString: @"Warning: This chat is not encrypted"] #define CANCEL_ENCRYPTED_CHAT_STRING [OTRLanguageManager translatedString: @"Cancel Encrypted Chat"] #define SETTINGS_STRING [OTRLanguageManager translatedString: @"Settings"] #define ENCRYPTION_ERROR_STRING [OTRLanguageManager translatedString: @"Encryption Error"] #define LOCKED_ERROR_STRING [OTRLanguageManager translatedString: @"The fingerprint has changed and needs to be verified"] #define SIGN_UP_STRING [OTRLanguageManager translatedString: @"Sign Up"] #define REMEMBER_PASSPHRASE_STRING [OTRLanguageManager translatedString: @"Remember Passphrase"] #define MANAGE_CHATSECURE_PUSH_ACCOUNT_STRING [OTRLanguageManager translatedString: @"Manage ChatSecure Push account"] #define errSSLPeerBadCertString [OTRLanguageManager translatedString: @"Miscellaneous bad certificate"] #define OLD_STRING [OTRLanguageManager translatedString: @"Old"] #define FORGOT_PASSPHRASE_INFO_STRING [OTRLanguageManager translatedString: @"Because the database contents is encrypted with your passphrase, you've lost access to your data and will need to delete and reinstall ChatSecure to continue. Password managers like 1Password or MiniKeePass can be helpful for generating and storing strong passwords."] #define SOURCE_STRING [OTRLanguageManager translatedString: @"Check out the source here on Github"] #define DATABASE_PASSPHRASE_CHANGE_SUCCESS_STRING [OTRLanguageManager translatedString: @"The database passphrase change was successful."] #define errSSLSessionNotFoundString [OTRLanguageManager translatedString: @"Attempt to restore an unknown session"] #define INFO_STRING [OTRLanguageManager translatedString: @"Info"] #define OTHER_STRING [OTRLanguageManager translatedString: @"Other"] #define REPLY_STRING [OTRLanguageManager translatedString: @"Reply"] #define IN_BAND_ERROR_STRING [OTRLanguageManager translatedString: @"The XMPP server does not support in-band registration"] #define AVAILABLE_STRING [OTRLanguageManager translatedString: @"Available"] #define CREATE_NEW_ACCOUNT_STRING [OTRLanguageManager translatedString: @"Create New Account"] #define errSSLPeerBadRecordMacString [OTRLanguageManager translatedString: @"Bad MAC"] #define OPTIONAL_STRING [OTRLanguageManager translatedString: @"Optional"] #define errSSLCertNotYetValidString [OTRLanguageManager translatedString: @"Chain had a cert not yet valid"] #define errSSLPeerUserCancelledString [OTRLanguageManager translatedString: @"User canceled"] #define DELIVERED_STRING [OTRLanguageManager translatedString: @"Delivered"] #define ABOUT_STRING [OTRLanguageManager translatedString: @"About"] #define REQUIRED_STRING [OTRLanguageManager translatedString: @"Required"] #define INVALID_EMAIL_DETAIL_STRING [OTRLanguageManager translatedString: @"Please choose a valid email address"] #define YOUR_FINGERPRINT_STRING [OTRLanguageManager translatedString: @"Fingerprint for you"] #define COMPOSE_STRING [OTRLanguageManager translatedString: @"Compose"] #define FORGOT_PASSPHRASE_STRING [OTRLanguageManager translatedString: @"Forgot Passphrase?"] #define NEXT_STRING [OTRLanguageManager translatedString: @"Next"] #define DUPLICATE_ACCOUNT_STRING [OTRLanguageManager translatedString: @"Duplicate account"] #define BASIC_STRING [OTRLanguageManager translatedString: @"Basic"] #define LANGUAGE_STRING [OTRLanguageManager translatedString: @"Language"] #define errSSLUnknownRootCertString [OTRLanguageManager translatedString: @"Valid cert chain, untrusted root"] #define SET_NEW_DATABASE_PASSPHRASE_STRING [OTRLanguageManager translatedString: @"Set new database passphrase"] #define AVAILABLE_MESSAGE_STRING [OTRLanguageManager translatedString: @"is now available"] #define OTRL_MSGEVENT_RCVDMSG_MALFORMED_STRING [OTRLanguageManager translatedString: @"The message received contains malformed data."] #define DATABASE_PASSPHRASE_CHANGE_ERROR_STRING [OTRLanguageManager translatedString: @"An error occurred while changing the database passphrase."] #define BLOCK_AND_REMOVE_STRING [OTRLanguageManager translatedString: @"Block & Remove"] #define CREATING_ACCOUNT_STRING [OTRLanguageManager translatedString: @"Creating Account"] #define DATABASE_SETUP_ERROR_STRING [OTRLanguageManager translatedString: @"An error occurred while setting up the database."] #define XMPP_PORT_FAIL_STRING [OTRLanguageManager translatedString: @"Domain needs to be set manually when specifying a custom port"] #define DISCONNECTION_WARNING_TITLE_STRING [OTRLanguageManager translatedString: @"Sign out Warning"] #define BUDDY_LIST_STRING [OTRLanguageManager translatedString: @"Buddy List"] #define errSSLPeerCertRevokedString [OTRLanguageManager translatedString: @"Certificate revoked"] #define VERIFY_LATER_STRING [OTRLanguageManager translatedString: @"Verify Later"] #define LOGGING_IN_STRING [OTRLanguageManager translatedString: @"Logging in..."] #define OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED_STRING [OTRLanguageManager translatedString: @"Cannot recognize the type of OTR message received."] #define SSL_MISMATCH_STRING [OTRLanguageManager translatedString: @"SSL Hostname Mismatch"] #define errSSLXCertChainInvalidString [OTRLanguageManager translatedString: @"Invalid certificate chain"] #define EMAIL_STRING [OTRLanguageManager translatedString: @"Email"] #define XMPP_USERNAME_EXAMPLE_STRING [OTRLanguageManager translatedString: @"<EMAIL>"] #define OPEN_IN_CHROME [OTRLanguageManager translatedString: @"Open in Chrome"] #define SECURE_CONVERSATION_STRING [OTRLanguageManager translatedString: @"You must be in a secure conversation first."] #define SHOW_USERVOICE_STRING [OTRLanguageManager translatedString: @"Would you like to connect to UserVoice to send feedback?"] #define CURRENT_PASSPHRASE_STRING [OTRLanguageManager translatedString: @"Current Passphrase"] #define SELF_SIGNED_SSL_STRING [OTRLanguageManager translatedString: @"Self Signed SSL"] #define ABOUT_VERSION_STRING [OTRLanguageManager translatedString: @"About This Version"] #define BUDDY_FINGERPRINTS_STRING [OTRLanguageManager translatedString: @"Buddy Fingerprints"] #define PINNED_CERTIFICATES_DESCRIPTION_STRING [OTRLanguageManager translatedString: @"Manage saved SSL certificates"] #define REMOVE_STRING [OTRLanguageManager translatedString: @"Remove"] #define DEFAULT_LANGUAGE_STRING NSLocalizedString(@"Default", @"default string to revert to normal language behaviour")
psiha/nt2
modules/boost/simd/base/unit/arithmetic/simd/fast_rsqrt.cpp
<gh_stars>10-100 //============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/arithmetic/include/functions/simd/fast_rsqrt.hpp> #include <boost/simd/include/functions/splat.hpp> #include <boost/dispatch/functor/meta/call.hpp> #include <boost/simd/sdk/simd/io.hpp> #include <boost/simd/sdk/simd/native.hpp> #include <boost/simd/include/constants/one.hpp> #include <boost/simd/include/constants/mone.hpp> #include <boost/simd/include/constants/nan.hpp> #include <boost/simd/include/constants/four.hpp> #include <boost/simd/include/constants/half.hpp> #include <boost/simd/include/constants/sqrt_2.hpp> #include <nt2/sdk/unit/tests/ulp.hpp> #include <nt2/sdk/unit/tests/type_expr.hpp> #include <nt2/sdk/unit/module.hpp> NT2_TEST_CASE_TPL( fast_rsqrt, BOOST_SIMD_SIMD_REAL_TYPES ) { using boost::simd::fast_rsqrt; using boost::simd::tag::fast_rsqrt_; using boost::simd::native; using boost::simd::splat; typedef BOOST_SIMD_DEFAULT_EXTENSION ext_t; typedef native<T,ext_t> vT; // return type conformity test NT2_TEST_TYPE_IS( typename boost::dispatch::meta::call<fast_rsqrt_(vT)>::type , vT ); // specific values tests NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::Mone<vT>()), boost::simd::Nan<vT>(), 75); NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::Nan<vT>()), boost::simd::Nan<vT>(), 75); NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::One<vT>()), boost::simd::One<vT>(), 75); NT2_TEST_ULP_EQUAL(fast_rsqrt(boost::simd::Four<vT>()), boost::simd::Half<vT>(), 75); NT2_TEST_ULP_EQUAL(fast_rsqrt(splat<vT>(0.5)), boost::simd::Sqrt_2<vT>(), 75); NT2_TEST_ULP_EQUAL(fast_rsqrt(splat<vT>(0.01)), splat<vT>(10), 75); NT2_TEST_ULP_EQUAL(fast_rsqrt(splat<vT>(0.0001)), splat<vT>(100), 75); }
hraada/kartchamp
src/main/webapp/js/lib/angular-1.0.3/angular-resource.min.js
<reponame>hraada/kartchamp /* AngularJS v1.0.3 (c) 2010-2012 Google, Inc. http://angularjs.org License: MIT */ (function (A, e, w) { 'use strict'; e.module("ngResource", ["ng"]).factory("$resource", ["$http", "$parse", function (x, y) { function k(a, f) { return encodeURIComponent(a).replace(/%40/gi, "@").replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(f ? null : /%20/g, "+") } function t(a, f) { this.template = a += "#"; this.defaults = f || {}; var b = this.urlParams = {}; l(a.split(/\W/), function (d) { d && a.match(RegExp("[^\\\\]:" + d + "\\W")) && (b[d] = !0) }); this.template = a.replace(/\\:/g, ":") } function u(a, f, b) { function d(b, c) { var a = {}, c = i({}, f, c); l(c, function (o, c) { var d; o.charAt && o.charAt(0) == "@" ? (d = o.substr(1), d = y(d)(b)) : d = o; a[c] = d }); return a } function h(a) { v(a || {}, this) } var e = new t(a), b = i({}, z, b); l(b, function (g, c) { var k = g.method == "POST" || g.method == "PUT" || g.method == "PATCH"; h[c] = function (a, b, c, f) { var s = {}, j, m = p, q = null; switch (arguments.length) { case 4: q = f, m = c; case 3: case 2: if (r(b)) { if (r(a)) { m = a; q = b; break } m = b; q = c } else { s = a; j = b; m = c; break } case 1: r(a) ? m = a : k ? j = a : s = a; break; case 0: break; default: throw"Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var n = this instanceof h ? this : g.isArray ? [] : new h(j); x({method: g.method, url: e.url(i({}, d(j, g.params || {}), s)), data: j}).then(function (a) { var b = a.data; if (b)g.isArray ? (n.length = 0, l(b, function (a) { n.push(new h(a)) })) : v(b, n); (m || p)(n, a.headers) }, q); return n }; h.bind = function (c) { return u(a, i({}, f, c), b) }; h.prototype["$" + c] = function (a, b, f) { var g = d(this), e = p, j; switch (arguments.length) { case 3: g = a; e = b; j = f; break; case 2: case 1: r(a) ? (e = a, j = b) : (g = a, e = b || p); case 0: break; default: throw"Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } h[c].call(this, g, k ? this : w, e, j) } }); return h } var z = {get: {method: "GET"}, save: {method: "POST"}, query: {method: "GET", isArray: !0}, remove: {method: "DELETE"}, "delete": {method: "DELETE"}}, p = e.noop, l = e.forEach, i = e.extend, v = e.copy, r = e.isFunction; t.prototype = {url: function (a) { var f = this, b = this.template, d, h, a = a || {}; l(this.urlParams, function (g, c) { d = a.hasOwnProperty(c) ? a[c] : f.defaults[c]; e.isDefined(d) && d !== null ? (h = k(d, !0).replace(/%26/gi, "&").replace(/%3D/gi, "=").replace(/%2B/gi, "+"), b = b.replace(RegExp(":" + c + "(\\W)", "g"), h + "$1")) : b = b.replace(RegExp("/?:" + c + "(\\W)", "g"), "$1") }); var b = b.replace(/\/?#$/, ""), i = []; l(a, function (a, b) { f.urlParams[b] || i.push(k(b) + "=" + k(a)) }); i.sort(); b = b.replace(/\/*$/, ""); return b + (i.length ? "?" + i.join("&") : "") }}; return u }]) })(window, window.angular);
Robotia/ExtraUtilities
ExtraUtilitiesBuilder/src/main/java/invtweaks/api/IItemTree.java
// // ExtraUtilities decompiled and fixed by Robotia https://github.com/Robotia // package invtweaks.api; import java.util.Random; import java.util.Collection; import java.util.List; public interface IItemTree { void registerOre(final String p0, final String p1, final String p2, final int p3); boolean matches(final List<IItemTreeItem> p0, final String p1); boolean isKeywordValid(final String p0); Collection<IItemTreeCategory> getAllCategories(); IItemTreeCategory getRootCategory(); IItemTreeCategory getCategory(final String p0); boolean isItemUnknown(final String p0, final int p1); List<IItemTreeItem> getItems(final String p0, final int p1); List<IItemTreeItem> getItems(final String p0); IItemTreeItem getRandomItem(final Random p0); boolean containsItem(final String p0); boolean containsCategory(final String p0); void setRootCategory(final IItemTreeCategory p0); IItemTreeCategory addCategory(final String p0, final String p1) throws NullPointerException; void addCategory(final String p0, final IItemTreeCategory p1) throws NullPointerException; IItemTreeItem addItem(final String p0, final String p1, final String p2, final int p3, final int p4) throws NullPointerException; void addItem(final String p0, final IItemTreeItem p1) throws NullPointerException; int getKeywordDepth(final String p0); int getKeywordOrder(final String p0); }
kldavis4/xstream
xstream/src/test/com/thoughtworks/acceptance/LambdaTest.java
<filename>xstream/src/test/com/thoughtworks/acceptance/LambdaTest.java<gh_stars>10-100 /* * Copyright (C) 2014, 2015 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 31. December 2014 by <NAME> */ package com.thoughtworks.acceptance; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.util.concurrent.Callable; /** * @author J&ouml;<NAME> */ public class LambdaTest extends AbstractAcceptanceTest { public static class LambdaKeeper { private Callable<String> callable; @SuppressWarnings("unused") private Object referenced; void keep(final Callable<String> c) { callable = c; } void reference() { referenced = callable; } } public void testLambdaExpression() { final LambdaKeeper keeper = new LambdaKeeper(); keeper.keep((Callable<String>)() -> "result"); final String expected = "" + "<keeper>\n" + " <callable class=\"null\"/>\n" + "</keeper>"; xstream.alias("keeper", LambdaKeeper.class); xstream.allowTypes(SerializedLambda.class); assertEquals(expected, xstream.toXML(keeper)); assertBothWays(xstream.fromXML(expected), "<keeper/>"); } public void testSerializableLambdaExpression() { final LambdaKeeper keeper = new LambdaKeeper(); keeper.keep((Callable<String> & Serializable)() -> "result"); final String expected = "" + "<keeper>\n" + " <callable resolves-to=\"serialized-lambda\">\n" + " <capturingClass>com.thoughtworks.acceptance.LambdaTest</capturingClass>\n" + " <functionalInterfaceClass>java/util/concurrent/Callable</functionalInterfaceClass>\n" + " <functionalInterfaceMethodName>call</functionalInterfaceMethodName>\n" + " <functionalInterfaceMethodSignature>()Ljava/lang/Object;</functionalInterfaceMethodSignature>\n" + " <implClass>com/thoughtworks/acceptance/LambdaTest</implClass>\n" + " <implMethodName>lambda$0</implMethodName>\n" + " <implMethodSignature>()Ljava/lang/String;</implMethodSignature>\n" + " <implMethodKind>6</implMethodKind>\n" + " <instantiatedMethodType>()Ljava/lang/String;</instantiatedMethodType>\n" + " <capturedArgs/>\n" + " </callable>\n" + "</keeper>"; xstream.alias("keeper", LambdaKeeper.class); xstream.allowTypes(SerializedLambda.class); assertBothWaysNormalized(keeper, expected); // ... deserialization fails if code was compiled with compiler of different vendor // Object resultRoot = xstream.fromXML(expected); // assertNotNull(resultRoot); } public void testReferencedLambdaExpression() { final LambdaKeeper keeper = new LambdaKeeper(); keeper.keep((Callable<String> & Serializable)() -> "result"); keeper.reference(); final String expected = "" + "<keeper>\n" + " <callable resolves-to=\"serialized-lambda\">\n" + " <capturingClass>com.thoughtworks.acceptance.LambdaTest</capturingClass>\n" + " <functionalInterfaceClass>java/util/concurrent/Callable</functionalInterfaceClass>\n" + " <functionalInterfaceMethodName>call</functionalInterfaceMethodName>\n" + " <functionalInterfaceMethodSignature>()Ljava/lang/Object;</functionalInterfaceMethodSignature>\n" + " <implClass>com/thoughtworks/acceptance/LambdaTest</implClass>\n" + " <implMethodName>lambda$0</implMethodName>\n" + " <implMethodSignature>()Ljava/lang/String;</implMethodSignature>\n" + " <implMethodKind>6</implMethodKind>\n" + " <instantiatedMethodType>()Ljava/lang/String;</instantiatedMethodType>\n" + " <capturedArgs/>\n" + " </callable>\n" + " <referenced class=\"java.util.concurrent.Callable\" reference=\"../callable\"/>\n" + "</keeper>"; xstream.alias("keeper", LambdaKeeper.class); xstream.allowTypes(SerializedLambda.class); assertBothWaysNormalized(keeper, expected); } public interface X { static int getTwo() { return 2; } default int getOne() { return 1; } } public interface SerializableCallable<T> extends X, Serializable, Callable<T> {} public void testLambdaArray() { Object[] lambdas = { (Callable<String> & Serializable)() -> "result", (SerializableCallable<String>)() -> "result", (Runnable & Serializable)() -> run(), (X & Serializable & Callable<String>)() -> "result", (Runnable)() -> run(), null}; lambdas[lambdas.length - 1] = lambdas[0]; final String expected = "" + "<object-array>\n" + " <callable resolves-to=\"serialized-lambda\">\n" + " <capturingClass>com.thoughtworks.acceptance.LambdaTest</capturingClass>\n" + " <functionalInterfaceClass>java/util/concurrent/Callable</functionalInterfaceClass>\n" + " <functionalInterfaceMethodName>call</functionalInterfaceMethodName>\n" + " <functionalInterfaceMethodSignature>()Ljava/lang/Object;</functionalInterfaceMethodSignature>\n" + " <implClass>com/thoughtworks/acceptance/LambdaTest</implClass>\n" + " <implMethodName>lambda$0</implMethodName>\n" + " <implMethodSignature>()Ljava/lang/String;</implMethodSignature>\n" + " <implMethodKind>6</implMethodKind>\n" + " <instantiatedMethodType>()Ljava/lang/String;</instantiatedMethodType>\n" + " <capturedArgs/>\n" + " </callable>\n" + " <serializable-callable resolves-to=\"serialized-lambda\">\n" + " <capturingClass>com.thoughtworks.acceptance.LambdaTest</capturingClass>\n" + " <functionalInterfaceClass>com/thoughtworks/acceptance/LambdaTest$SerializableCallable</functionalInterfaceClass>\n" + " <functionalInterfaceMethodName>call</functionalInterfaceMethodName>\n" + " <functionalInterfaceMethodSignature>()Ljava/lang/Object;</functionalInterfaceMethodSignature>\n" + " <implClass>com/thoughtworks/acceptance/LambdaTest</implClass>\n" + " <implMethodName>lambda$0</implMethodName>\n" + " <implMethodSignature>()Ljava/lang/String;</implMethodSignature>\n" + " <implMethodKind>6</implMethodKind>\n" + " <instantiatedMethodType>()Ljava/lang/String;</instantiatedMethodType>\n" + " <capturedArgs/>\n" + " </serializable-callable>\n" + " <runnable resolves-to=\"serialized-lambda\">\n" + " <capturingClass>com.thoughtworks.acceptance.LambdaTest</capturingClass>\n" + " <functionalInterfaceClass>java/lang/Runnable</functionalInterfaceClass>\n" + " <functionalInterfaceMethodName>run</functionalInterfaceMethodName>\n" + " <functionalInterfaceMethodSignature>()V</functionalInterfaceMethodSignature>\n" + " <implClass>com/thoughtworks/acceptance/LambdaTest</implClass>\n" + " <implMethodName>lambda$0</implMethodName>\n" + " <implMethodSignature>()V</implMethodSignature>\n" + " <implMethodKind>7</implMethodKind>\n" + " <instantiatedMethodType>()V</instantiatedMethodType>\n" + " <capturedArgs>\n" + " <com.thoughtworks.acceptance.LambdaTest>\n" + " <fName>testLambdaArray</fName>\n" + " </com.thoughtworks.acceptance.LambdaTest>\n" + " </capturedArgs>\n" + " </runnable>\n" + " <callable resolves-to=\"serialized-lambda\">\n" + " <capturingClass>com.thoughtworks.acceptance.LambdaTest</capturingClass>\n" + " <functionalInterfaceClass>java/util/concurrent/Callable</functionalInterfaceClass>\n" + " <functionalInterfaceMethodName>call</functionalInterfaceMethodName>\n" + " <functionalInterfaceMethodSignature>()Ljava/lang/Object;</functionalInterfaceMethodSignature>\n" + " <implClass>com/thoughtworks/acceptance/LambdaTest</implClass>\n" + " <implMethodName>lambda$0</implMethodName>\n" + " <implMethodSignature>()Ljava/lang/String;</implMethodSignature>\n" + " <implMethodKind>6</implMethodKind>\n" + " <instantiatedMethodType>()Ljava/lang/String;</instantiatedMethodType>\n" + " <capturedArgs/>\n" + " </callable>\n" + " <null/>\n" + " <callable reference=\"../callable\"/>\n" + "</object-array>"; xstream.alias("callable", Callable.class); xstream.alias("runnable", Runnable.class); xstream.alias("serializable-callable", SerializableCallable.class); xstream.allowTypes(SerializedLambda.class, LambdaTest.class); assertBothWaysNormalized(lambdas, expected); } private void assertBothWaysNormalized(final Object original, final String expected) { String resultXml = toXML(original); assertEquals(normalizeLambda(expected), normalizeLambda(resultXml)); final Object resultRoot = xstream.fromXML(resultXml); resultXml = toXML(resultRoot); assertEquals(normalizeLambda(expected), normalizeLambda(resultXml)); } private String normalizeLambda(final String xml) { // unify compiler specific name for implMethodName, Eclipse uses always "lambda$0" return xml.replaceAll(">lambda\\$[^<]+<", ">lambda\\$0<"); } }
ruslanvolov6667/ID
vkapi/api.py
import requests import enum import json import os from .exceptions import * import logging class Mode(enum.Enum): POST = "POST" GET = "GET" class VkApi(object): Mode: Mode mode: Mode access_token: str version: str lang: str raise_excepts: bool api_url = "https://api.vk.com/method/" def __init__(self, access_token: str, version: str = "5.103", mode: Mode = Mode.POST, lang: str = "ru", raise_excepts: bool = False): self.logger = logging.getLogger('vkapi') self.Mode = Mode self.access_token = access_token self.version = version self.mode = self.Mode(mode) self.lang = lang self.raise_excepts = raise_excepts def method(self, method, **kwargs): def load_methods(): with open(os.path.join(os.path.dirname(__file__), "schemes", "methods.json")) as file: return json.loads(file.read()) mode = self.Mode(kwargs.get('mode', self.mode)) version = kwargs.get('version', self.version) access_token = kwargs.get('access_token', self.access_token) lang = kwargs.get('lang', self.lang) raise_excepts = kwargs.get('raise_excepts', self.raise_excepts) methods = [method__['name'].lower() for method__ in load_methods()['methods']] if method.lower() not in methods: if raise_excepts: raise InvalidMethodException(method) else: return [err for err in load_methods() if err['name'] == "API_ERROR_METHOD"][0] data = {} for key in kwargs.keys(): if key.lower() not in ["mode", "version", "access_token", "lang", "raise_excepts"]: data[key] = kwargs[key] request = None if mode == self.Mode.GET: url_ = self.api_url + method + "?" data_list = [f"{key_}={data[key_]}" for key_ in data.keys()] data_list.append(f"v={version}") data_list.append(f"access_token={access_token}") data_list.append(f"lang={lang}") url_ += "&".join(data_list) request = requests.get(url_) else: url_ = self.api_url + method + f"?v={version}&access_token={access_token}&lang={lang}" request = requests.post(url_, data=data) if 'response' in request.json().keys(): self.logger.info(f"Запрос {method} выполнен") return request.json()["response"] elif 'error' in request.json().keys(): self.logger.info(f"Запрос {method} не выполнен: {request.json()['error']}") if raise_excepts: raise VkApiResponseException(**request.json()["error"]) else: return request.json() else: raise Exception() def __call__(self, method, **kwargs): return self.method(method, **kwargs)
MasterOogwayis/spring
base/base-logging/src/main/java/com/zsw/log/catchlog/CatchLogAspect.java
<reponame>MasterOogwayis/spring package com.zsw.log.catchlog; import com.zsw.utils.JacksonUtils; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; /** * @author ZhangShaowei on 2021/6/30 16:39 */ @Slf4j @Aspect public class CatchLogAspect { @Pointcut("@within(CatchAndLog) && execution(public * *(..))") public void pointcut() { // Do nothing } @Around(value = "pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); logRequest(joinPoint); Object response = joinPoint.proceed(); logResponse(startTime, response); return response; } private void logResponse(long startTime, Object response) { try { long endTime = System.currentTimeMillis(); log.debug("response : {}", JacksonUtils.toJson(response)); log.debug("cost : {}ms", (endTime - startTime)); } catch (Exception e) { //swallow it log.error("logResponse error", e); } } private void logRequest(ProceedingJoinPoint joinPoint) { try { log.debug("start processing: {}", joinPoint.getSignature().toShortString()); Object[] args = joinPoint.getArgs(); for (Object arg : args) { log.debug("request : " + JacksonUtils.toJson(arg)); } } catch (Exception e) { log.error("logRequest error", e); } } }
nvpnathan/pulumi-nsxt
sdk/go/nsxt/policyVlanSegment.go
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package nsxt import ( "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v2/go/pulumi" ) type PolicyVlanSegment struct { pulumi.CustomResourceState // Advanced segment configuration AdvancedConfig PolicyVlanSegmentAdvancedConfigPtrOutput `pulumi:"advancedConfig"` // Description for this resource Description pulumi.StringPtrOutput `pulumi:"description"` // Policy path to DHCP server or relay configuration to use for subnets configured on this segment DhcpConfigPath pulumi.StringPtrOutput `pulumi:"dhcpConfigPath"` // IP and MAC discovery profiles for this segment DiscoveryProfile PolicyVlanSegmentDiscoveryProfilePtrOutput `pulumi:"discoveryProfile"` // Display name for this resource DisplayName pulumi.StringOutput `pulumi:"displayName"` // DNS domain names DomainName pulumi.StringPtrOutput `pulumi:"domainName"` // Configuration for extending Segment through L2 VPN L2Extension PolicyVlanSegmentL2ExtensionPtrOutput `pulumi:"l2Extension"` // NSX ID for this resource NsxId pulumi.StringOutput `pulumi:"nsxId"` // Policy path for this resource Path pulumi.StringOutput `pulumi:"path"` // QoS profiles for this segment QosProfile PolicyVlanSegmentQosProfilePtrOutput `pulumi:"qosProfile"` // The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's // changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET // operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected Revision pulumi.IntOutput `pulumi:"revision"` // Security profiles for this segment SecurityProfile PolicyVlanSegmentSecurityProfilePtrOutput `pulumi:"securityProfile"` // Subnet configuration with at most 1 IPv4 CIDR and multiple IPv6 CIDRs Subnets PolicyVlanSegmentSubnetArrayOutput `pulumi:"subnets"` // Set of opaque identifiers meaningful to the user Tags PolicyVlanSegmentTagArrayOutput `pulumi:"tags"` // Policy path to the transport zone TransportZonePath pulumi.StringOutput `pulumi:"transportZonePath"` // VLAN IDs for VLAN backed Segment VlanIds pulumi.StringArrayOutput `pulumi:"vlanIds"` } // NewPolicyVlanSegment registers a new resource with the given unique name, arguments, and options. func NewPolicyVlanSegment(ctx *pulumi.Context, name string, args *PolicyVlanSegmentArgs, opts ...pulumi.ResourceOption) (*PolicyVlanSegment, error) { if args == nil || args.DisplayName == nil { return nil, errors.New("missing required argument 'DisplayName'") } if args == nil || args.TransportZonePath == nil { return nil, errors.New("missing required argument 'TransportZonePath'") } if args == nil || args.VlanIds == nil { return nil, errors.New("missing required argument 'VlanIds'") } if args == nil { args = &PolicyVlanSegmentArgs{} } var resource PolicyVlanSegment err := ctx.RegisterResource("nsxt:index/policyVlanSegment:PolicyVlanSegment", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetPolicyVlanSegment gets an existing PolicyVlanSegment resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetPolicyVlanSegment(ctx *pulumi.Context, name string, id pulumi.IDInput, state *PolicyVlanSegmentState, opts ...pulumi.ResourceOption) (*PolicyVlanSegment, error) { var resource PolicyVlanSegment err := ctx.ReadResource("nsxt:index/policyVlanSegment:PolicyVlanSegment", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering PolicyVlanSegment resources. type policyVlanSegmentState struct { // Advanced segment configuration AdvancedConfig *PolicyVlanSegmentAdvancedConfig `pulumi:"advancedConfig"` // Description for this resource Description *string `pulumi:"description"` // Policy path to DHCP server or relay configuration to use for subnets configured on this segment DhcpConfigPath *string `pulumi:"dhcpConfigPath"` // IP and MAC discovery profiles for this segment DiscoveryProfile *PolicyVlanSegmentDiscoveryProfile `pulumi:"discoveryProfile"` // Display name for this resource DisplayName *string `pulumi:"displayName"` // DNS domain names DomainName *string `pulumi:"domainName"` // Configuration for extending Segment through L2 VPN L2Extension *PolicyVlanSegmentL2Extension `pulumi:"l2Extension"` // NSX ID for this resource NsxId *string `pulumi:"nsxId"` // Policy path for this resource Path *string `pulumi:"path"` // QoS profiles for this segment QosProfile *PolicyVlanSegmentQosProfile `pulumi:"qosProfile"` // The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's // changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET // operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected Revision *int `pulumi:"revision"` // Security profiles for this segment SecurityProfile *PolicyVlanSegmentSecurityProfile `pulumi:"securityProfile"` // Subnet configuration with at most 1 IPv4 CIDR and multiple IPv6 CIDRs Subnets []PolicyVlanSegmentSubnet `pulumi:"subnets"` // Set of opaque identifiers meaningful to the user Tags []PolicyVlanSegmentTag `pulumi:"tags"` // Policy path to the transport zone TransportZonePath *string `pulumi:"transportZonePath"` // VLAN IDs for VLAN backed Segment VlanIds []string `pulumi:"vlanIds"` } type PolicyVlanSegmentState struct { // Advanced segment configuration AdvancedConfig PolicyVlanSegmentAdvancedConfigPtrInput // Description for this resource Description pulumi.StringPtrInput // Policy path to DHCP server or relay configuration to use for subnets configured on this segment DhcpConfigPath pulumi.StringPtrInput // IP and MAC discovery profiles for this segment DiscoveryProfile PolicyVlanSegmentDiscoveryProfilePtrInput // Display name for this resource DisplayName pulumi.StringPtrInput // DNS domain names DomainName pulumi.StringPtrInput // Configuration for extending Segment through L2 VPN L2Extension PolicyVlanSegmentL2ExtensionPtrInput // NSX ID for this resource NsxId pulumi.StringPtrInput // Policy path for this resource Path pulumi.StringPtrInput // QoS profiles for this segment QosProfile PolicyVlanSegmentQosProfilePtrInput // The _revision property describes the current revision of the resource. To prevent clients from overwriting each other's // changes, PUT operations must include the current _revision of the resource, which clients should obtain by issuing a GET // operation. If the _revision provided in a PUT request is missing or stale, the operation will be rejected Revision pulumi.IntPtrInput // Security profiles for this segment SecurityProfile PolicyVlanSegmentSecurityProfilePtrInput // Subnet configuration with at most 1 IPv4 CIDR and multiple IPv6 CIDRs Subnets PolicyVlanSegmentSubnetArrayInput // Set of opaque identifiers meaningful to the user Tags PolicyVlanSegmentTagArrayInput // Policy path to the transport zone TransportZonePath pulumi.StringPtrInput // VLAN IDs for VLAN backed Segment VlanIds pulumi.StringArrayInput } func (PolicyVlanSegmentState) ElementType() reflect.Type { return reflect.TypeOf((*policyVlanSegmentState)(nil)).Elem() } type policyVlanSegmentArgs struct { // Advanced segment configuration AdvancedConfig *PolicyVlanSegmentAdvancedConfig `pulumi:"advancedConfig"` // Description for this resource Description *string `pulumi:"description"` // Policy path to DHCP server or relay configuration to use for subnets configured on this segment DhcpConfigPath *string `pulumi:"dhcpConfigPath"` // IP and MAC discovery profiles for this segment DiscoveryProfile *PolicyVlanSegmentDiscoveryProfile `pulumi:"discoveryProfile"` // Display name for this resource DisplayName string `pulumi:"displayName"` // DNS domain names DomainName *string `pulumi:"domainName"` // Configuration for extending Segment through L2 VPN L2Extension *PolicyVlanSegmentL2Extension `pulumi:"l2Extension"` // NSX ID for this resource NsxId *string `pulumi:"nsxId"` // QoS profiles for this segment QosProfile *PolicyVlanSegmentQosProfile `pulumi:"qosProfile"` // Security profiles for this segment SecurityProfile *PolicyVlanSegmentSecurityProfile `pulumi:"securityProfile"` // Subnet configuration with at most 1 IPv4 CIDR and multiple IPv6 CIDRs Subnets []PolicyVlanSegmentSubnet `pulumi:"subnets"` // Set of opaque identifiers meaningful to the user Tags []PolicyVlanSegmentTag `pulumi:"tags"` // Policy path to the transport zone TransportZonePath string `pulumi:"transportZonePath"` // VLAN IDs for VLAN backed Segment VlanIds []string `pulumi:"vlanIds"` } // The set of arguments for constructing a PolicyVlanSegment resource. type PolicyVlanSegmentArgs struct { // Advanced segment configuration AdvancedConfig PolicyVlanSegmentAdvancedConfigPtrInput // Description for this resource Description pulumi.StringPtrInput // Policy path to DHCP server or relay configuration to use for subnets configured on this segment DhcpConfigPath pulumi.StringPtrInput // IP and MAC discovery profiles for this segment DiscoveryProfile PolicyVlanSegmentDiscoveryProfilePtrInput // Display name for this resource DisplayName pulumi.StringInput // DNS domain names DomainName pulumi.StringPtrInput // Configuration for extending Segment through L2 VPN L2Extension PolicyVlanSegmentL2ExtensionPtrInput // NSX ID for this resource NsxId pulumi.StringPtrInput // QoS profiles for this segment QosProfile PolicyVlanSegmentQosProfilePtrInput // Security profiles for this segment SecurityProfile PolicyVlanSegmentSecurityProfilePtrInput // Subnet configuration with at most 1 IPv4 CIDR and multiple IPv6 CIDRs Subnets PolicyVlanSegmentSubnetArrayInput // Set of opaque identifiers meaningful to the user Tags PolicyVlanSegmentTagArrayInput // Policy path to the transport zone TransportZonePath pulumi.StringInput // VLAN IDs for VLAN backed Segment VlanIds pulumi.StringArrayInput } func (PolicyVlanSegmentArgs) ElementType() reflect.Type { return reflect.TypeOf((*policyVlanSegmentArgs)(nil)).Elem() }
geometryzen/davinci-eight
build/module/lib/visual/ArrowFH.js
import { Color } from '../core/Color'; import { Geometric3 } from '../math/Geometric3'; import { normVectorE3 } from '../math/normVectorE3'; import { ArrowHead } from './ArrowHead'; import { ArrowTail } from './ArrowTail'; /** * An arrow with a fixed head and variable length. */ var ArrowFH = /** @class */ (function () { /** * @param contextManager This will usually be provided by the `Engine`. * @param options */ function ArrowFH(contextManager, options) { if (options === void 0) { options = {}; } this.$vector = Geometric3.zero(false); this.$position = Geometric3.zero(false); this.$attitude = Geometric3.zero(false); this.$color = Color.fromRGB(1, 1, 1); this.$isHeadVisible = true; this.head = new ArrowHead(contextManager, options); this.tail = new ArrowTail(contextManager, options); this.$vector.copyVector(this.head.vector).addVector(this.tail.vector); this.$vectorLock = this.$vector.lock(); this.$position.copyVector(this.tail.position); this.$positionLock = this.$position.lock(); this.$attitude.copySpinor(this.tail.attitude); this.$attitudeLock = this.$attitude.lock(); this.$color.copy(this.tail.color); this.$colorLock = this.$color.lock(); this.updateHeadAttitude(); this.updateHeadPosition(); } ArrowFH.prototype.render = function (ambients) { if (this.$isHeadVisible) { this.head.render(ambients); } this.tail.render(ambients); }; /** * @hidden */ ArrowFH.prototype.contextFree = function () { this.head.contextFree(); this.tail.contextFree(); }; /** * @hidden */ ArrowFH.prototype.contextGain = function () { this.head.contextGain(); this.tail.contextGain(); }; /** * @hidden */ ArrowFH.prototype.contextLost = function () { this.head.contextLost(); this.tail.contextLost(); }; ArrowFH.prototype.addRef = function () { this.head.addRef(); return this.tail.addRef(); }; ArrowFH.prototype.release = function () { this.head.release(); return this.tail.release(); }; Object.defineProperty(ArrowFH.prototype, "vector", { /** * The vector from the tail of the arrow to the head of the arrow. */ get: function () { return this.$vector; }, set: function (vector) { this.$vector.unlock(this.$vectorLock); this.$vector.copyVector(vector); this.$vectorLock = this.$vector.lock(); var magnitude = normVectorE3(vector); var heightShaft = magnitude - this.head.heightCone; if (heightShaft >= 0) { this.$isHeadVisible = true; this.tail.heightShaft = heightShaft; this.updateHeadPosition(); } else { this.$isHeadVisible = false; this.tail.heightShaft = magnitude; } // Don't try to set the direction for the zero vector. if (magnitude > 0) { this.head.axis = vector; this.tail.axis = vector; } this.updateHeadPosition(); }, enumerable: false, configurable: true }); /** * @hidden */ ArrowFH.prototype.isZombie = function () { if (this.head.isZombie()) { if (this.tail.isZombie()) { return true; } else { throw new Error(); } } else { if (this.tail.isZombie()) { throw new Error(); } else { return false; } } }; Object.defineProperty(ArrowFH.prototype, "X", { /** * Alias for `position`. */ get: function () { return this.$position; }, set: function (X) { this.setPosition(X); }, enumerable: false, configurable: true }); Object.defineProperty(ArrowFH.prototype, "position", { /** * The position (vector). */ get: function () { return this.$position; }, set: function (position) { this.setPosition(position); }, enumerable: false, configurable: true }); Object.defineProperty(ArrowFH.prototype, "R", { /** * Alias for `attitude`. */ get: function () { return this.$attitude; }, set: function (R) { this.setAttitude(R); }, enumerable: false, configurable: true }); Object.defineProperty(ArrowFH.prototype, "attitude", { /** * The attitude (spinor). */ get: function () { return this.$attitude; }, set: function (attitude) { this.setAttitude(attitude); }, enumerable: false, configurable: true }); Object.defineProperty(ArrowFH.prototype, "color", { get: function () { return this.$color; }, set: function (color) { this.$color.unlock(this.$colorLock); this.$color.copy(color); this.$colorLock = this.$color.lock(); this.head.color = color; this.tail.color = color; }, enumerable: false, configurable: true }); ArrowFH.prototype.setPosition = function (position) { this.$position.unlock(this.$positionLock); this.$position.copyVector(position); this.$positionLock = this.$position.lock(); this.tail.position = position; this.updateHeadPosition(); }; ArrowFH.prototype.setAttitude = function (attitude) { this.$attitude.unlock(this.$attitudeLock); this.$attitude.copySpinor(attitude); this.$attitudeLock = this.$attitude.lock(); this.tail.attitude = attitude; this.updateHeadPosition(); this.updateHeadAttitude(); }; ArrowFH.prototype.updateHeadPosition = function () { this.head.position.copyVector(this.tail.position).addVector(this.tail.vector); }; ArrowFH.prototype.updateHeadAttitude = function () { this.head.attitude = this.tail.attitude; }; return ArrowFH; }()); export { ArrowFH };
DanIverson/OpenVnmrJ
src/ib/i_mod.c
<filename>src/ib/i_mod.c /* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ #include "f2c.h" #ifdef KR_headers integer i_mod(a,b) integer *a, *b; #else integer i_mod(integer *a, integer *b) #endif { return( *a % *b); }
cosailer/mass_storage_device
LUFA/Documentation/html/struct_r_n_d_i_s___message___header__t.js
<reponame>cosailer/mass_storage_device<gh_stars>0 var struct_r_n_d_i_s___message___header__t = [ [ "MessageLength", "struct_r_n_d_i_s___message___header__t.html#a71397e19c56f9744cba3b25e3221c5e8", null ], [ "MessageType", "struct_r_n_d_i_s___message___header__t.html#a284087f944d8d23ffbcf34b530e32752", null ] ];
liorisraeli87/fbthrift
thrift/compiler/test/fixtures/types/gen-cpp2/module_fatal.h
/** * Autogenerated by Thrift for src/module.thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #pragma once #include <thrift/lib/cpp2/reflection/reflection.h> #include <fatal/type/list.h> #include <fatal/type/pair.h> #include <fatal/type/sequence.h> #include "thrift/compiler/test/fixtures/types/gen-cpp2/module_types.h" namespace apache { namespace thrift { namespace fixtures { namespace types { namespace __fbthrift_refl { struct __fbthrift_strings_module { using AllocatorAware = ::fatal::sequence<char, 'A', 'l', 'l', 'o', 'c', 'a', 't', 'o', 'r', 'A', 'w', 'a', 'r', 'e'>; using AllocatorAware2 = ::fatal::sequence<char, 'A', 'l', 'l', 'o', 'c', 'a', 't', 'o', 'r', 'A', 'w', 'a', 'r', 'e', '2'>; using AnnotatedTypes = ::fatal::sequence<char, 'A', 'n', 'n', 'o', 't', 'a', 't', 'e', 'd', 'T', 'y', 'p', 'e', 's'>; using ComplexNestedWithDefault = ::fatal::sequence<char, 'C', 'o', 'm', 'p', 'l', 'e', 'x', 'N', 'e', 's', 't', 'e', 'd', 'W', 'i', 't', 'h', 'D', 'e', 'f', 'a', 'u', 'l', 't'>; using ComplexString = ::fatal::sequence<char, 'C', 'o', 'm', 'p', 'l', 'e', 'x', 'S', 't', 'r', 'i', 'n', 'g'>; using ContainerStruct = ::fatal::sequence<char, 'C', 'o', 'n', 't', 'a', 'i', 'n', 'e', 'r', 'S', 't', 'r', 'u', 'c', 't'>; using CppTypeStruct = ::fatal::sequence<char, 'C', 'p', 'p', 'T', 'y', 'p', 'e', 'S', 't', 'r', 'u', 'c', 't'>; using ForwardUsageByRef = ::fatal::sequence<char, 'F', 'o', 'r', 'w', 'a', 'r', 'd', 'U', 's', 'a', 'g', 'e', 'B', 'y', 'R', 'e', 'f'>; using ForwardUsageRoot = ::fatal::sequence<char, 'F', 'o', 'r', 'w', 'a', 'r', 'd', 'U', 's', 'a', 'g', 'e', 'R', 'o', 'o', 't'>; using ForwardUsageStruct = ::fatal::sequence<char, 'F', 'o', 'r', 'w', 'a', 'r', 'd', 'U', 's', 'a', 'g', 'e', 'S', 't', 'r', 'u', 'c', 't'>; using MinPadding = ::fatal::sequence<char, 'M', 'i', 'n', 'P', 'a', 'd', 'd', 'i', 'n', 'g'>; using MyBinaryField = ::fatal::sequence<char, 'M', 'y', 'B', 'i', 'n', 'a', 'r', 'y', 'F', 'i', 'e', 'l', 'd'>; using MyBinaryField2 = ::fatal::sequence<char, 'M', 'y', 'B', 'i', 'n', 'a', 'r', 'y', 'F', 'i', 'e', 'l', 'd', '2'>; using MyBinaryField3 = ::fatal::sequence<char, 'M', 'y', 'B', 'i', 'n', 'a', 'r', 'y', 'F', 'i', 'e', 'l', 'd', '3'>; using MyBinaryListField4 = ::fatal::sequence<char, 'M', 'y', 'B', 'i', 'n', 'a', 'r', 'y', 'L', 'i', 's', 't', 'F', 'i', 'e', 'l', 'd', '4'>; using MyBoolField = ::fatal::sequence<char, 'M', 'y', 'B', 'o', 'o', 'l', 'F', 'i', 'e', 'l', 'd'>; using MyDataItem = ::fatal::sequence<char, 'M', 'y', 'D', 'a', 't', 'a', 'I', 't', 'e', 'm'>; using MyEnumA = ::fatal::sequence<char, 'M', 'y', 'E', 'n', 'u', 'm', 'A'>; using MyForwardRefEnum = ::fatal::sequence<char, 'M', 'y', 'F', 'o', 'r', 'w', 'a', 'r', 'd', 'R', 'e', 'f', 'E', 'n', 'u', 'm'>; using MyIntField = ::fatal::sequence<char, 'M', 'y', 'I', 'n', 't', 'F', 'i', 'e', 'l', 'd'>; using MyMapEnumAndInt = ::fatal::sequence<char, 'M', 'y', 'M', 'a', 'p', 'E', 'n', 'u', 'm', 'A', 'n', 'd', 'I', 'n', 't'>; using MyStringField = ::fatal::sequence<char, 'M', 'y', 'S', 't', 'r', 'i', 'n', 'g', 'F', 'i', 'e', 'l', 'd'>; using MyStringField2 = ::fatal::sequence<char, 'M', 'y', 'S', 't', 'r', 'i', 'n', 'g', 'F', 'i', 'e', 'l', 'd', '2'>; using MyStruct = ::fatal::sequence<char, 'M', 'y', 'S', 't', 'r', 'u', 'c', 't'>; using MyStructWithForwardRefEnum = ::fatal::sequence<char, 'M', 'y', 'S', 't', 'r', 'u', 'c', 't', 'W', 'i', 't', 'h', 'F', 'o', 'r', 'w', 'a', 'r', 'd', 'R', 'e', 'f', 'E', 'n', 'u', 'm'>; using NONZERO = ::fatal::sequence<char, 'N', 'O', 'N', 'Z', 'E', 'R', 'O'>; using NoExceptMoveUnion = ::fatal::sequence<char, 'N', 'o', 'E', 'x', 'c', 'e', 'p', 't', 'M', 'o', 'v', 'e', 'U', 'n', 'i', 'o', 'n'>; using NoexceptMoveComplexStruct = ::fatal::sequence<char, 'N', 'o', 'e', 'x', 'c', 'e', 'p', 't', 'M', 'o', 'v', 'e', 'C', 'o', 'm', 'p', 'l', 'e', 'x', 'S', 't', 'r', 'u', 'c', 't'>; using NoexceptMoveEmpty = ::fatal::sequence<char, 'N', 'o', 'e', 'x', 'c', 'e', 'p', 't', 'M', 'o', 'v', 'e', 'E', 'm', 'p', 't', 'y'>; using NoexceptMoveSimpleStruct = ::fatal::sequence<char, 'N', 'o', 'e', 'x', 'c', 'e', 'p', 't', 'M', 'o', 'v', 'e', 'S', 'i', 'm', 'p', 'l', 'e', 'S', 't', 'r', 'u', 'c', 't'>; using Renaming = ::fatal::sequence<char, 'R', 'e', 'n', 'a', 'm', 'i', 'n', 'g'>; using SomeService = ::fatal::sequence<char, 'S', 'o', 'm', 'e', 'S', 'e', 'r', 'v', 'i', 'c', 'e'>; using TrivialNestedWithDefault = ::fatal::sequence<char, 'T', 'r', 'i', 'v', 'i', 'a', 'l', 'N', 'e', 's', 't', 'e', 'd', 'W', 'i', 't', 'h', 'D', 'e', 'f', 'a', 'u', 'l', 't'>; using TrivialNumeric = ::fatal::sequence<char, 'T', 'r', 'i', 'v', 'i', 'a', 'l', 'N', 'u', 'm', 'e', 'r', 'i', 'c'>; using Type = ::fatal::sequence<char, 'T', 'y', 'p', 'e'>; using VirtualStruct = ::fatal::sequence<char, 'V', 'i', 'r', 't', 'u', 'a', 'l', 'S', 't', 'r', 'u', 'c', 't'>; using ZERO = ::fatal::sequence<char, 'Z', 'E', 'R', 'O'>; using a = ::fatal::sequence<char, 'a'>; using aa_list = ::fatal::sequence<char, 'a', 'a', '_', 'l', 'i', 's', 't'>; using aa_map = ::fatal::sequence<char, 'a', 'a', '_', 'm', 'a', 'p'>; using aa_set = ::fatal::sequence<char, 'a', 'a', '_', 's', 'e', 't'>; using aa_string = ::fatal::sequence<char, 'a', 'a', '_', 's', 't', 'r', 'i', 'n', 'g'>; using apache__thrift__fixtures__types = ::fatal::sequence<char, 'a', 'p', 'a', 'c', 'h', 'e', ':', ':', 't', 'h', 'r', 'i', 'f', 't', ':', ':', 'f', 'i', 'x', 't', 'u', 'r', 'e', 's', ':', ':', 't', 'y', 'p', 'e', 's'>; using b = ::fatal::sequence<char, 'b'>; using bar = ::fatal::sequence<char, 'b', 'a', 'r'>; using big = ::fatal::sequence<char, 'b', 'i', 'g'>; using biggish = ::fatal::sequence<char, 'b', 'i', 'g', 'g', 'i', 's', 'h'>; using binary_field = ::fatal::sequence<char, 'b', 'i', 'n', 'a', 'r', 'y', '_', 'f', 'i', 'e', 'l', 'd'>; using binary_keyed_map = ::fatal::sequence<char, 'b', 'i', 'n', 'a', 'r', 'y', '_', 'k', 'e', 'y', 'e', 'd', '_', 'm', 'a', 'p'>; using boolField = ::fatal::sequence<char, 'b', 'o', 'o', 'l', 'F', 'i', 'e', 'l', 'd'>; using bounce_map = ::fatal::sequence<char, 'b', 'o', 'u', 'n', 'c', 'e', '_', 'm', 'a', 'p'>; using cpp = ::fatal::sequence<char, 'c', 'p', 'p'>; using cpp2 = ::fatal::sequence<char, 'c', 'p', 'p', '2'>; using cpp2_noncomparable = ::fatal::sequence<char, 'c', 'p', 'p', '2', '.', 'n', 'o', 'n', 'c', 'o', 'm', 'p', 'a', 'r', 'a', 'b', 'l', 'e'>; using cpp_allocator = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'a', 'l', 'l', 'o', 'c', 'a', 't', 'o', 'r'>; using cpp_declare_bitwise_ops = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'd', 'e', 'c', 'l', 'a', 'r', 'e', '_', 'b', 'i', 't', 'w', 'i', 's', 'e', '_', 'o', 'p', 's'>; using cpp_declare_equal_to = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'd', 'e', 'c', 'l', 'a', 'r', 'e', '_', 'e', 'q', 'u', 'a', 'l', '_', 't', 'o'>; using cpp_declare_hash = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'd', 'e', 'c', 'l', 'a', 'r', 'e', '_', 'h', 'a', 's', 'h'>; using cpp_deprecated_enum_unscoped = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'd', 'e', 'p', 'r', 'e', 'c', 'a', 't', 'e', 'd', '_', 'e', 'n', 'u', 'm', '_', 'u', 'n', 's', 'c', 'o', 'p', 'e', 'd'>; using cpp_minimize_padding = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'm', 'i', 'n', 'i', 'm', 'i', 'z', 'e', '_', 'p', 'a', 'd', 'd', 'i', 'n', 'g'>; using cpp_noexcept_move = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'n', 'o', 'e', 'x', 'c', 'e', 'p', 't', '_', 'm', 'o', 'v', 'e'>; using cpp_virtual = ::fatal::sequence<char, 'c', 'p', 'p', '.', 'v', 'i', 'r', 't', 'u', 'a', 'l'>; using data = ::fatal::sequence<char, 'd', 'a', 't', 'a'>; using decorated_struct = ::fatal::sequence<char, 'd', 'e', 'c', 'o', 'r', 'a', 't', 'e', 'd', '_', 's', 't', 'r', 'u', 'c', 't'>; using field = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd'>; using fieldA = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'A'>; using fieldB = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'B'>; using fieldC = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'C'>; using fieldD = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'D'>; using fieldE = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'E'>; using fieldF = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'F'>; using fieldG = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'G'>; using fieldH = ::fatal::sequence<char, 'f', 'i', 'e', 'l', 'd', 'H'>; using foo = ::fatal::sequence<char, 'f', 'o', 'o'>; using has_bitwise_ops = ::fatal::sequence<char, 'h', 'a', 's', '_', 'b', 'i', 't', 'w', 'i', 's', 'e', '_', 'o', 'p', 's'>; using hello = ::fatal::sequence<char, 'h', 'e', 'l', 'l', 'o'>; using i32_field = ::fatal::sequence<char, 'i', '3', '2', '_', 'f', 'i', 'e', 'l', 'd'>; using is_unscoped = ::fatal::sequence<char, 'i', 's', '_', 'u', 'n', 's', 'c', 'o', 'p', 'e', 'd'>; using list_field = ::fatal::sequence<char, 'l', 'i', 's', 't', '_', 'f', 'i', 'e', 'l', 'd'>; using m = ::fatal::sequence<char, 'm'>; using majorVer = ::fatal::sequence<char, 'm', 'a', 'j', 'o', 'r', 'V', 'e', 'r'>; using medium = ::fatal::sequence<char, 'm', 'e', 'd', 'i', 'u', 'm'>; using module = ::fatal::sequence<char, 'm', 'o', 'd', 'u', 'l', 'e'>; using n = ::fatal::sequence<char, 'n'>; using none = ::fatal::sequence<char, 'n', 'o', 'n', 'e'>; using not_a_container = ::fatal::sequence<char, 'n', 'o', 't', '_', 'a', '_', 'c', 'o', 'n', 't', 'a', 'i', 'n', 'e', 'r'>; using one = ::fatal::sequence<char, 'o', 'n', 'e'>; using r = ::fatal::sequence<char, 'r'>; using small = ::fatal::sequence<char, 's', 'm', 'a', 'l', 'l'>; using string_field = ::fatal::sequence<char, 's', 't', 'r', 'i', 'n', 'g', '_', 'f', 'i', 'e', 'l', 'd'>; using three = ::fatal::sequence<char, 't', 'h', 'r', 'e', 'e'>; using tiny = ::fatal::sequence<char, 't', 'i', 'n', 'y'>; using two = ::fatal::sequence<char, 't', 'w', 'o'>; using world = ::fatal::sequence<char, 'w', 'o', 'r', 'l', 'd'>; using z = ::fatal::sequence<char, 'z'>; using zero = ::fatal::sequence<char, 'z', 'e', 'r', 'o'>; }; struct module_module_traits { using strings = __fbthrift_strings_module; using name = strings::module; using namespaces = ::fatal::list< ::fatal::pair<strings::cpp, strings::apache__thrift__fixtures__types>, ::fatal::pair<strings::cpp2, strings::apache__thrift__fixtures__types> >; using enums = ::fatal::list< ::fatal::pair<::apache::thrift::fixtures::types::has_bitwise_ops, strings::has_bitwise_ops>, ::fatal::pair<::apache::thrift::fixtures::types::is_unscoped, strings::is_unscoped>, ::fatal::pair<::apache::thrift::fixtures::types::MyForwardRefEnum, strings::MyForwardRefEnum>, ::fatal::pair<::apache::thrift::fixtures::types::MyEnumA, strings::MyEnumA> >; using unions = ::fatal::list< ::fatal::pair<::apache::thrift::fixtures::types::NoExceptMoveUnion, strings::NoExceptMoveUnion> >; using structs = ::fatal::list< ::fatal::pair<::apache::thrift::fixtures::types::decorated_struct, strings::decorated_struct>, ::fatal::pair<::apache::thrift::fixtures::types::ContainerStruct, strings::ContainerStruct>, ::fatal::pair<::apache::thrift::fixtures::types::CppTypeStruct, strings::CppTypeStruct>, ::fatal::pair<::apache::thrift::fixtures::types::VirtualStruct, strings::VirtualStruct>, ::fatal::pair<::apache::thrift::fixtures::types::MyStructWithForwardRefEnum, strings::MyStructWithForwardRefEnum>, ::fatal::pair<::apache::thrift::fixtures::types::TrivialNumeric, strings::TrivialNumeric>, ::fatal::pair<::apache::thrift::fixtures::types::TrivialNestedWithDefault, strings::TrivialNestedWithDefault>, ::fatal::pair<::apache::thrift::fixtures::types::ComplexString, strings::ComplexString>, ::fatal::pair<::apache::thrift::fixtures::types::ComplexNestedWithDefault, strings::ComplexNestedWithDefault>, ::fatal::pair<::apache::thrift::fixtures::types::MinPadding, strings::MinPadding>, ::fatal::pair<::apache::thrift::fixtures::types::MyStruct, strings::MyStruct>, ::fatal::pair<::apache::thrift::fixtures::types::MyDataItem, strings::MyDataItem>, ::fatal::pair<::apache::thrift::fixtures::types::Renaming, strings::Renaming>, ::fatal::pair<::apache::thrift::fixtures::types::AnnotatedTypes, strings::AnnotatedTypes>, ::fatal::pair<::apache::thrift::fixtures::types::ForwardUsageRoot, strings::ForwardUsageRoot>, ::fatal::pair<::apache::thrift::fixtures::types::ForwardUsageStruct, strings::ForwardUsageStruct>, ::fatal::pair<::apache::thrift::fixtures::types::ForwardUsageByRef, strings::ForwardUsageByRef>, ::fatal::pair<::apache::thrift::fixtures::types::NoexceptMoveEmpty, strings::NoexceptMoveEmpty>, ::fatal::pair<::apache::thrift::fixtures::types::NoexceptMoveSimpleStruct, strings::NoexceptMoveSimpleStruct>, ::fatal::pair<::apache::thrift::fixtures::types::NoexceptMoveComplexStruct, strings::NoexceptMoveComplexStruct>, ::fatal::pair<::apache::thrift::fixtures::types::AllocatorAware, strings::AllocatorAware>, ::fatal::pair<::apache::thrift::fixtures::types::AllocatorAware2, strings::AllocatorAware2> >; using constants = ::fatal::list< >; using services = ::fatal::list< strings::SomeService >; }; } // __fbthrift_refl class module_tags { using __fbthrift_strings = __fbthrift_refl::__fbthrift_strings_module; struct __fbthrift_languages { using cpp = __fbthrift_strings::cpp; using cpp2 = __fbthrift_strings::cpp2; }; struct __fbthrift_enums { using has_bitwise_ops = __fbthrift_strings::has_bitwise_ops; using is_unscoped = __fbthrift_strings::is_unscoped; using MyForwardRefEnum = __fbthrift_strings::MyForwardRefEnum; using MyEnumA = __fbthrift_strings::MyEnumA; }; struct __fbthrift_unions { using NoExceptMoveUnion = __fbthrift_strings::NoExceptMoveUnion; }; struct __fbthrift_structs { using decorated_struct = __fbthrift_strings::decorated_struct; using ContainerStruct = __fbthrift_strings::ContainerStruct; using CppTypeStruct = __fbthrift_strings::CppTypeStruct; using VirtualStruct = __fbthrift_strings::VirtualStruct; using MyStructWithForwardRefEnum = __fbthrift_strings::MyStructWithForwardRefEnum; using TrivialNumeric = __fbthrift_strings::TrivialNumeric; using TrivialNestedWithDefault = __fbthrift_strings::TrivialNestedWithDefault; using ComplexString = __fbthrift_strings::ComplexString; using ComplexNestedWithDefault = __fbthrift_strings::ComplexNestedWithDefault; using MinPadding = __fbthrift_strings::MinPadding; using MyStruct = __fbthrift_strings::MyStruct; using MyDataItem = __fbthrift_strings::MyDataItem; using Renaming = __fbthrift_strings::Renaming; using AnnotatedTypes = __fbthrift_strings::AnnotatedTypes; using ForwardUsageRoot = __fbthrift_strings::ForwardUsageRoot; using ForwardUsageStruct = __fbthrift_strings::ForwardUsageStruct; using ForwardUsageByRef = __fbthrift_strings::ForwardUsageByRef; using NoexceptMoveEmpty = __fbthrift_strings::NoexceptMoveEmpty; using NoexceptMoveSimpleStruct = __fbthrift_strings::NoexceptMoveSimpleStruct; using NoexceptMoveComplexStruct = __fbthrift_strings::NoexceptMoveComplexStruct; using AllocatorAware = __fbthrift_strings::AllocatorAware; using AllocatorAware2 = __fbthrift_strings::AllocatorAware2; }; struct __fbthrift_constants { }; struct __fbthrift_services { using SomeService = __fbthrift_strings::SomeService; }; public: struct module {}; using strings = __fbthrift_strings; using languages = __fbthrift_languages; using enums = __fbthrift_enums; using unions = __fbthrift_unions; using structs = __fbthrift_structs; using constants = __fbthrift_constants; using services = __fbthrift_services; }; THRIFT_REGISTER_REFLECTION_METADATA(module_tags::module, __fbthrift_refl::module_module_traits); }}}} // apache::thrift::fixtures::types #include "thrift/compiler/test/fixtures/types/gen-cpp2/module_fatal_types.h"
jainsakshi2395/linux
tools/testing/selftests/powerpc/mm/stack_expansion_ldst.c
// SPDX-License-Identifier: GPL-2.0 /* * Test that loads/stores expand the stack segment, or trigger a SEGV, in * various conditions. * * Based on test code by <NAME>. */ #undef NDEBUG #include <assert.h> #include <err.h> #include <errno.h> #include <stdio.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #define _KB (1024) #define _MB (1024 * 1024) volatile char *stack_top_ptr; volatile unsigned long stack_top_sp; volatile char c; enum access_type { LOAD, STORE, }; /* * Consume stack until the stack pointer is below @target_sp, then do an access * (load or store) at offset @delta from either the base of the stack or the * current stack pointer. */ __attribute__ ((noinline)) int consume_stack(unsigned long target_sp, unsigned long stack_high, int delta, enum access_type type) { unsigned long target; char stack_cur; if ((unsigned long)&stack_cur > target_sp) return consume_stack(target_sp, stack_high, delta, type); else { // We don't really need this, but without it GCC might not // generate a recursive call above. stack_top_ptr = &stack_cur; #ifdef __powerpc__ asm volatile ("mr %[sp], %%r1" : [sp] "=r" (stack_top_sp)); #else asm volatile ("mov %%rsp, %[sp]" : [sp] "=r" (stack_top_sp)); #endif target = stack_high - delta + 1; volatile char *p = (char *)target; if (type == STORE) *p = c; else c = *p; // Do something to prevent the stack frame being popped prior to // our access above. getpid(); } return 0; } static int search_proc_maps(char *needle, unsigned long *low, unsigned long *high) { unsigned long start, end; static char buf[4096]; char name[128]; FILE *f; int rc; f = fopen("/proc/self/maps", "r"); if (!f) { perror("fopen"); return -1; } while (fgets(buf, sizeof(buf), f)) { rc = sscanf(buf, "%lx-%lx %*c%*c%*c%*c %*x %*d:%*d %*d %127s\n", &start, &end, name); if (rc == 2) continue; if (rc != 3) { printf("sscanf errored\n"); rc = -1; break; } if (strstr(name, needle)) { *low = start; *high = end - 1; rc = 0; break; } } fclose(f); return rc; } int child(unsigned int stack_used, int delta, enum access_type type) { unsigned long low, stack_high; assert(search_proc_maps("[stack]", &low, &stack_high) == 0); assert(consume_stack(stack_high - stack_used, stack_high, delta, type) == 0); printf("Access OK: %s delta %-7d used size 0x%06x stack high 0x%lx top_ptr %p top sp 0x%lx actual used 0x%lx\n", type == LOAD ? "load" : "store", delta, stack_used, stack_high, stack_top_ptr, stack_top_sp, stack_high - stack_top_sp + 1); return 0; } static int test_one(unsigned int stack_used, int delta, enum access_type type) { pid_t pid; int rc; pid = fork(); if (pid == 0) exit(child(stack_used, delta, type)); assert(waitpid(pid, &rc, 0) != -1); if (WIFEXITED(rc) && WEXITSTATUS(rc) == 0) return 0; // We don't expect a non-zero exit that's not a signal assert(!WIFEXITED(rc)); printf("Faulted: %s delta %-7d used size 0x%06x signal %d\n", type == LOAD ? "load" : "store", delta, stack_used, WTERMSIG(rc)); return 1; } // This is fairly arbitrary but is well below any of the targets below, // so that the delta between the stack pointer and the target is large. #define DEFAULT_SIZE (32 * _KB) static void test_one_type(enum access_type type, unsigned long page_size, unsigned long rlim_cur) { unsigned long delta; // We should be able to access anywhere within the rlimit for (delta = page_size; delta <= rlim_cur; delta += page_size) assert(test_one(DEFAULT_SIZE, delta, type) == 0); assert(test_one(DEFAULT_SIZE, rlim_cur, type) == 0); // But if we go past the rlimit it should fail assert(test_one(DEFAULT_SIZE, rlim_cur + 1, type) != 0); } static int test(void) { unsigned long page_size; struct rlimit rlimit; page_size = getpagesize(); getrlimit(RLIMIT_STACK, &rlimit); printf("Stack rlimit is 0x%lx\n", rlimit.rlim_cur); printf("Testing loads ...\n"); test_one_type(LOAD, page_size, rlimit.rlim_cur); printf("Testing stores ...\n"); test_one_type(STORE, page_size, rlimit.rlim_cur); printf("All OK\n"); return 0; } #ifdef __powerpc__ #include "utils.h" int main(void) { return test_harness(test, "stack_expansion_ldst"); } #else int main(void) { return test(); } #endif
Nefla/the-pod
app/helpers/shuffle-date.js
<reponame>Nefla/the-pod<filename>app/helpers/shuffle-date.js<gh_stars>1-10 import DaySort from '../constants/DaySort' function shuffleDate(){ return randomDate(DaySort.OLDEST, DaySort.NEWEST) } // Taken from stackoverflow user tomasz: // http://stackoverflow.com/a/9035732/6598709 function randomDate(start, end) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())) } module.exports = shuffleDate
databeast/apicore
apiv2-streamsrv/rtmp/protocol/packet_on_status_call.go
package protocol // OnStatusCallPacket onStatus command, AMF0 Call // user must set the stream id type OnStatusCallPacket struct { // CommandName Name of command. Set to "onStatus" CommandName string // TransactionID set to 0 TransactionID float64 // Args Command information does not exist. Set to null type. Args Amf0Object // Data Name-value pairs that describe the response from the server. // ‘code’,‘level’, ‘description’ are names of few among such information. Data []Amf0Object } // Decode . func (pkt *OnStatusCallPacket) Decode(data []uint8) (err error) { //nothing return } // Encode . func (pkt *OnStatusCallPacket) Encode() (data []uint8) { data = append(data, amf0WriteString(pkt.CommandName)...) data = append(data, amf0WriteNumber(pkt.TransactionID)...) data = append(data, amf0WriteNull()...) data = append(data, amf0WriteObject(pkt.Data)...) return } // GetMessageType . func (pkt *OnStatusCallPacket) GetMessageType() uint8 { return RtmpMsgAmf0CommandMessage } // GetPreferCsID . func (pkt *OnStatusCallPacket) GetPreferCsID() uint32 { return RtmpCidOverStream } // AddObj add object to data func (pkt *OnStatusCallPacket) AddObj(obj *Amf0Object) { pkt.Data = append(pkt.Data, *obj) }
alexeev/jboss-fuse-mirror
sandbox/fabric-monitor/src/main/scala/org/fusesource/fabric/monitor/internal/PropertiesFilter.scala
/* * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.monitor.internal import javax.xml.bind.Unmarshaller import javax.xml.stream.XMLStreamReader import javax.xml.stream.util.StreamReaderDelegate import java.io.InputStream import java.util.Properties import java.net.URL import io.fabric8.monitor.api.XmlCodec object PropertiesFilter { import XmlCodec._ def decode[T](t : Class[T], url: URL, props: Properties): T = { return decode(t, url.openStream, props) } def decode[T](t: Class[T], is: InputStream, props: Properties): T = { if (is == null) { throw new IllegalArgumentException("input stream was null") } try { var reader: XMLStreamReader = factory.createXMLStreamReader(is) if (props != null) { reader = new PropertiesFilter(reader, props) } var unmarshaller: Unmarshaller = context.createUnmarshaller return t.cast(unmarshaller.unmarshal(reader)) } finally { is.close } } } /** * Changes ${property} with values from a properties object */ class PropertiesFilter(parent: XMLStreamReader, val props: Properties) extends StreamReaderDelegate(parent) { override def getAttributeValue(index: Int): String = { import FilterSupport._ return filter(super.getAttributeValue(index), props) } }
ChristopherDurand/Exercises
ruby/small-problems/easy3/e06.rb
def xor?(a, b) (a && !b) || (b && !a) end puts xor?(true, true) puts xor?(true, false) puts xor?(false, true) puts xor?(false, false)
fspace/go-playground
advexamples/iocookbook/internal/usingreader/directly-using-io-reader.go
<reponame>fspace/go-playground package usingreader import ( "fmt" "io" "log" "strings" ) func Main() { reader := strings.NewReader("this is the stuff I'm reading") var result []byte buf := make([]byte, 4) for { n, err := reader.Read(buf) result = append(result, buf[:n]...) if err != nil { if err == io.EOF { break } log.Fatal(err) } } fmt.Println(string(result)) }
otymko/phoenixbsl
src/main/java/com/github/otymko/phoenixbsl/logic/PhoenixContext.java
<reponame>otymko/phoenixbsl<filename>src/main/java/com/github/otymko/phoenixbsl/logic/PhoenixContext.java package com.github.otymko.phoenixbsl.logic; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.otymko.phoenixbsl.PhoenixCore; import com.github.otymko.phoenixbsl.model.Configuration; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.nio.file.Path; @Slf4j public class PhoenixContext { public static final String BSL_CONFIGURATION_NAME = ".bsl-language-server.json"; public static final String DEFAULT_PROJECT_NAME = "Базовый проект"; private final PhoenixCore core; @Getter private final Path basePathApp = Path.of(System.getProperty("user.home"), PhoenixCore.APPLICATION_NAME); @Getter private final Path pathToFolderLog = createPathToLog(); @Getter private final Path pathToConfiguration = createPathToConfiguration(); @Getter private final Path pathToBSLConfigurationDefault = Path.of(basePathApp.toString(), BSL_CONFIGURATION_NAME); public PhoenixContext(PhoenixCore core) { this.core = core; } public void initConfiguration() { // файл конфигурации должен лежать по пути: app/configuration.json var fileConfiguration = getPathToConfiguration().toFile(); Configuration configuration; if (!fileConfiguration.exists()) { // создать новый по умолчанию configuration = Configuration.create(); writeConfiguration(configuration, fileConfiguration); } else { // прочитать в текущие настройки configuration = Configuration.create(fileConfiguration); } core.setConfiguration(configuration); } public void writeConfiguration(Configuration configuration, File fileConfiguration) { // запишем ее в файл ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(fileConfiguration, configuration); } catch (IOException e) { LOGGER.error("Не удалось записать конфигурацию в файл.", e); } } public void writeConfiguration(Configuration configuration) { writeConfiguration(configuration, getPathToConfiguration().toFile()); } public String getProjectName() { var projectName = core.getConfiguration().getProject(); if (projectName.isEmpty()) { projectName = PhoenixContext.DEFAULT_PROJECT_NAME; } return projectName; } private Path createPathToLog() { var path = Path.of(basePathApp.toString(), "logs").toAbsolutePath(); path.toFile().mkdirs(); return path; } private static Path createPathToConfiguration() { var path = Path.of(System.getProperty("user.home"), PhoenixCore.APPLICATION_NAME, "Configuration.json") .toAbsolutePath(); path.getParent().toFile().mkdirs(); return path; } }
JLLeitschuh/book
src/main/java/com/tamingtext/classifier/maxent/CategoryDataStream.java
<reponame>JLLeitschuh/book /* * Copyright 2008-2011 <NAME>, <NAME> and <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. * ------------------- * To purchase or learn more about Taming Text, by <NAME>, <NAME> and <NAME>, visit * http://www.manning.com/ingersoll */ package com.tamingtext.classifier.maxent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import opennlp.tools.doccat.DocumentSample; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.util.ObjectStream; import org.slf4j.Logger; public class CategoryDataStream implements ObjectStream<DocumentSample> { public static final Logger log = org.slf4j.LoggerFactory.getLogger(CategoryDataStream.class); File[] inputFiles; int inputFilesIndex = 0; String encoding; BufferedReader reader; Tokenizer tokenizer; String line; File currentFile; public CategoryDataStream(File[] inputFiles, Tokenizer tokenizer) { this(inputFiles, "UTF-8", tokenizer); } public CategoryDataStream(File[] inputFiles, String encoding, Tokenizer tokenizer) { this.inputFiles = inputFiles; this.encoding = encoding; if (tokenizer == null) { this.tokenizer = SimpleTokenizer.INSTANCE; } else { this.tokenizer = tokenizer; } } public CategoryDataStream(String fileName, Tokenizer tokenizer) { this(fileName, "UTF-8", tokenizer); } public CategoryDataStream(String fileName, String encoding, Tokenizer tokenizer) { this((File[]) null, encoding, tokenizer); inputFiles = new File[1]; inputFiles[0] = new File(fileName); } public void reset() { close(); line = null; inputFilesIndex = 0; } public void close() { if (reader != null) { try { reader.close(); } catch (IOException ex) { log.warn("IOException on close", ex); } } } /** Set the current buffered line to null, and attempt to obtain the next * line of training data, if we run out of lines in one file, move on to * the next. If we are out of files, line will remain null when this * method returns. * * @throws RuntimeException if there's a problem reading any of the input * files. */ protected void getNextLine() { line = null; try { while (line == null) { if (reader == null) { // no more files to read; if (inputFilesIndex >= inputFiles.length) break; // open the next file. currentFile = inputFiles[inputFilesIndex]; reader = new BufferedReader( new InputStreamReader( new FileInputStream(currentFile), encoding)); } line = reader.readLine(); if (line == null) { // done with this reader, move to the next file. reader = null; inputFilesIndex++; } } } catch (IOException e) { throw new RuntimeException("Error reading input from: " + currentFile, e); } } public boolean hasNext() { getNextLine(); return line != null; } //<start id="maxent.examples.train.event"/> public DocumentSample read() { if (line == null && !hasNext()) { //<co id="mee.train.read"/> return null; } int split = line.indexOf('\t'); //<co id="mee.train.cat"/> if (split < 0) throw new RuntimeException("Invalid line in " + inputFiles[inputFilesIndex]); String category = line.substring(0,split); String document = line.substring(split+1); line = null; // mark line as consumed String[] tokens = tokenizer.tokenize(document); //<co id="mee.train.tok"/> return new DocumentSample(category, tokens); //<co id="mee.train.sample"/> } /*<calloutlist> <callout arearefs="mee.train.read">Read a line training data</callout> <callout arearefs="mee.train.cat">Extract category</callout> <callout arearefs="mee.train.tok">Tokenize content</callout> <callout arearefs="mee.train.tok">Create sample</callout> </calloutlist>*/ //<end id="maxent.examples.train.event"/> }
ismo-karkkainen/datalackey
src/RawData.cpp
// // RawData.cpp // datalackey // // Created by <NAME> on 24.7.17. // Copyright © 2017 <NAME>. All rights reserved. // // Licensed under Universal Permissive License. See License.txt. #include "RawData.hpp" void RawData::Clear(bool LikelyUnused) { if (LikelyUnused) { std::vector<char> empty; buffer.swap(empty); } else buffer.resize(0); } char* RawData::Get(size_t Required) { size_t sz = buffer.size(); buffer.resize(sz + Required); return &(buffer[sz]); } void RawData::Discard(size_t Unused) { if (Unused <= buffer.size()) buffer.resize(buffer.size() - Unused); else buffer.resize(0); } void RawData::Append(ConstIterator From, ConstIterator To) { buffer.insert(buffer.end(), From, To); } void RawData::Append(const char Item) { buffer.push_back(Item); } void RawData::Append(const char *const Item) { const char* c = const_cast<const char*>(Item); while (*c) buffer.push_back(*c++); } void RawData::Swap(RawData& RD) { buffer.swap(RD.buffer); }
dzeban/java-exercises
ToString.java
class ToString { public static final String a = new Integer(123).toString(); }
sdee3/laravel-react-blog-starter
resources/js/pages/home/index.js
<filename>resources/js/pages/home/index.js import React from 'react'; export default function Home() { return ( <section className="home-page container"> <h1>MySite</h1> <h2>Homepage</h2> <img className="cards" src="http://pngimg.com/uploads/cards/cards_PNG8490.png" /> </section> ); }
yu1hpa/ctf-writeups
2021/redpwn/ret2generic-flag-reader/solve.py
from pwn import * #io = process("./ret2generic-flag-reader") io = remote('mc.ax', 31077) payload = b"" payload += b"A"*32 + b"B"*8 payload += p64(0x00000000004011f6) io.sendlineafter("what do you think?", payload) io.interactive()
cloudwebrtc/sys
sys-account/service/go/delivery/account_delivery.go
package delivery import ( "context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "github.com/getcouragenow/sys-share/pkg" "github.com/getcouragenow/sys/sys-account/service/go/dao" "github.com/getcouragenow/sys/sys-account/service/go/pkg/auth" coredb "github.com/getcouragenow/sys/sys-core/service/go/pkg/db" ) /* */ func (ad *AuthDelivery) NewAccount(ctx context.Context, in *pkg.Account) (*pkg.Account, error) { now := timestampNow() roleId := coredb.UID() if err := ad.store.InsertRole(&dao.Permission{ ID: roleId, AccountId: in.Id, // TODO @gutterbacon check for uniqueness Role: int(in.Role.Role), ProjectId: in.Role.ProjectID, OrgId: in.Role.OrgID, CreatedAt: now, }); err != nil { return nil, err } if err := ad.store.InsertAccount(&dao.Account{ ID: in.Id, Email: in.Email, Password: <PASSWORD>, RoleId: roleId, UserDefinedFields: in.Fields.Fields, CreatedAt: in.CreatedAt, UpdatedAt: in.UpdatedAt, LastLogin: in.LastLogin, Disabled: in.Disabled, }); err != nil { return nil, err } acc, err := ad.store.GetAccount(&dao.QueryParams{Params: map[string]interface{}{"id": in.Id}}) if err != nil { return nil, err } role, err := ad.store.GetRole(&dao.QueryParams{Params: map[string]interface{}{"id": acc.RoleId}}) if err != nil { return nil, err } userRole, err := role.ToPkgRole() if err != nil { return nil, err } return acc.ToPkgAccount(userRole) } func (ad *AuthDelivery) GetAccount(ctx context.Context, in *pkg.GetAccountRequest) (*pkg.Account, error) { if in == nil { return &pkg.Account{}, status.Errorf(codes.InvalidArgument, "cannot get user account: %v", auth.AuthError{Reason: auth.ErrInvalidParameters}) } // TODO @gutterbacon: In the absence of actual enforcement policy function, this method is a stub. We allow everyone to query anything at this point. acc, err := ad.store.GetAccount(&dao.QueryParams{Params: map[string]interface{}{ "id": in.Id, }}) if err != nil { return nil, status.Errorf(codes.NotFound, "cannot find user account: %v", auth.AuthError{Reason: auth.ErrAccountNotFound}) } role, err := ad.store.GetRole(&dao.QueryParams{Params: map[string]interface{}{ "id": acc.RoleId, }}) if err != nil { return nil, status.Errorf(codes.NotFound, "cannot find user role: %v", auth.AuthError{Reason: auth.ErrAccountNotFound}) } userRole, err := role.ToPkgRole() if err != nil { return nil, status.Errorf(codes.NotFound, "cannot find user role: %v", auth.AuthError{Reason: auth.ErrAccountNotFound}) } return acc.ToPkgAccount(userRole) } // TODO @gutterbacon: In the absence of actual enforcement policy function, this method is a stub. We allow everyone to query anything at this point. func (ad *AuthDelivery) ListAccounts(ctx context.Context, in *pkg.ListAccountsRequest) (*pkg.ListAccountsResponse, error) { if in == nil { return &pkg.ListAccountsResponse{}, status.Errorf(codes.InvalidArgument, "cannot list user accounts: %v", auth.AuthError{Reason: auth.ErrInvalidParameters}) } return &pkg.ListAccountsResponse{}, nil } // TODO @gutterbacon: In the absence of actual enforcement policy function, this method is a stub. We allow everyone to query anything at this point. func (ad *AuthDelivery) SearchAccounts(ctx context.Context, in *pkg.SearchAccountsRequest) (*pkg.SearchAccountsResponse, error) { return &pkg.SearchAccountsResponse{}, nil } // TODO @gutterbacon: In the absence of actual enforcement policy function, this method is a stub. We allow everyone to query anything at this point. func (ad *AuthDelivery) AssignAccountToRole(context.Context, *pkg.AssignAccountToRoleRequest) (*pkg.Account, error) { return &pkg.Account{}, nil } // TODO @gutterbacon: In the absence of actual enforcement policy function, this method is a stub. We allow everyone to query anything at this point. func (ad *AuthDelivery) UpdateAccount(context.Context, *pkg.Account) (*pkg.Account, error) { return &pkg.Account{}, nil } // TODO @gutterbacon: In the absence of actual enforcement policy function, this method is a stub. We allow everyone to query anything at this point. func (ad *AuthDelivery) DisableAccount(context.Context, *pkg.DisableAccountRequest) (*pkg.Account, error) { return &pkg.Account{}, nil }
lechium/tvOS135Headers
System/Library/PrivateFrameworks/CoreRC.framework/CoreRCXPCServiceCEC.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:43:24 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/PrivateFrameworks/CoreRC.framework/CoreRC * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol CoreRCXPCServiceCEC @required -(void)performActiveSourceAsync:(id)arg1 withMenus:(BOOL)arg2 reply:(/*^block*/id)arg3; -(void)performDeckControlSetDeckStatusAsync:(unsigned long long)arg1 forDevice:(id)arg2 reply:(/*^block*/id)arg3; -(void)performDeckControlCommandAsync:(id)arg1 controlMode:(unsigned long long)arg2 targetDevice:(id)arg3 reply:(/*^block*/id)arg4; -(void)performDeckControlPlayAsync:(id)arg1 playMode:(unsigned long long)arg2 targetDevice:(id)arg3 reply:(/*^block*/id)arg4; -(void)performDeckControlRefreshStatusAsync:(id)arg1 targetDevice:(id)arg2 requestType:(unsigned long long)arg3 reply:(/*^block*/id)arg4; -(void)performInactiveSourceAsync:(id)arg1 reply:(/*^block*/id)arg2; -(void)performRefreshDevicesAsync:(id)arg1 reply:(/*^block*/id)arg2; -(void)performRefreshProperties:(id)arg1 ofDevice:(id)arg2 withDeviceAsync:(id)arg3 reply:(/*^block*/id)arg4; -(void)performRequestActiveSourceAsync:(id)arg1 reply:(/*^block*/id)arg2; -(void)performSetSystemAudioControlEnabled:(BOOL)arg1 withDeviceAsync:(id)arg2 reply:(/*^block*/id)arg3; -(void)performSystemAudioModeRequestAsync:(id)arg1 withDesiredState:(unsigned long long)arg2 reply:(/*^block*/id)arg3; -(void)performSetPowerStatus:(unsigned long long)arg1 withDeviceAsync:(id)arg2 reply:(/*^block*/id)arg3; -(void)performStandbyAsync:(id)arg1 targetDevice:(id)arg2 reply:(/*^block*/id)arg3; -(void)queryLocalInstanceAsync:(id)arg1 bus:(id)arg2 reply:(/*^block*/id)arg3; -(void)setOsdNameAsync:(id)arg1 forBus:(id)arg2 reply:(/*^block*/id)arg3; -(void)setTvLanguageCodeAsync:(id)arg1 forBus:(id)arg2 reply:(/*^block*/id)arg3; @end
hiiq/shared-react-components-example
packages/molecules/flow-typed/PackageTypes/UtilsTypes/models/NavGraph.js
// @flow declare type ModelizedGraphNavSerieType = [number, number]; // Bad naming convention due to legacy declare type ModelizedGraphNavType = { navData: ModelizedGraphNavSerieType[], currency: string, disclaimers: ModelizedNavGraphDisclaimersType, hideNavGraph: boolean, }; declare type NavGraphModelizerType = ( fundsheet: APIFundsheetResponseType, navs: APINavGraphResponseType[], currentCurrency?: string ) => ModelizedGraphNavType;
camment/sdk-ios
CammentSDK/Classes/Core/Models/CMUserRemovedMessageBuilder.h
#import <Foundation/Foundation.h> @class CMUserRemovedMessage; @class CMUser; @interface CMUserRemovedMessageBuilder : NSObject + (instancetype)userRemovedMessage; + (instancetype)userRemovedMessageFromExistingUserRemovedMessage:(CMUserRemovedMessage *)existingUserRemovedMessage; - (CMUserRemovedMessage *)build; - (instancetype)withUserGroupUuid:(NSString *)userGroupUuid; - (instancetype)withUser:(CMUser *)user; @end
dmenneck/campus-map
src/components/RoomLayerThree.js
<reponame>dmenneck/campus-map import React, { useContext, useEffect } from "react"; import { AppContext } from "./AppContext"; import roomsThree from "../data/geoData/roomsThree.geojson"; import GeoJSON from "ol/format/GeoJSON"; let dataThree = ""; async function fetchDataThree() { const response = await fetch(roomsThree); const json = await response.json(); dataThree = json; } fetchDataThree(); const RoomLayerThree = ({ map }) => { const { value6, value18 } = useContext(AppContext); const [clickedBuildingsInformation, setclickedBuildingsInformation] = value6; const dataThree_features = dataThree.features; const building_number = clickedBuildingsInformation.building_number; if (dataThree_features === undefined) { // nothing happens } else { let roomFeatureToAdd = dataThree_features.filter( (item) => item.properties.build_num === building_number ); // get source of entrance layer const room_layer_source = map.getLayers().getArray()[8].getSource(); // transform object to GeoJSON const format = new GeoJSON(); const olFeatures = roomFeatureToAdd.map((feature) => format.readFeature(feature) ); // clear source so that only the clicked building entrances appear room_layer_source.clear(); // add features to source room_layer_source.addFeatures(olFeatures); } return <div></div>; }; export default RoomLayerThree;
IIyass/Portfolio
src/pages/blog.js
import React from "react" import Layout from "../components/layout" import Blogs from "../components/Blog" const Blog = (props) => { return ( <Layout path={props.location.pathname}> <Blogs /> </Layout> ) } export default Blog
cloudera/altus-sdk-java
src/test/java/com/cloudera/altus/authentication/credentials/AltusProfileCredentialsProviderTest.java
<filename>src/test/java/com/cloudera/altus/authentication/credentials/AltusProfileCredentialsProviderTest.java /* * Copyright (c) 2018 Cloudera, Inc. All Rights Reserved. * * Portions Copyright (c) Copyright 2013-2018 Amazon.com, Inc. or its * affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.altus.authentication.credentials; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import com.cloudera.altus.AltusClientException; import com.cloudera.altus.util.AltusSDKTestUtils; import com.google.common.collect.Maps; import java.nio.file.Path; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; public class AltusProfileCredentialsProviderTest { private String originalUserHome = null; @BeforeEach public void setEnvVariables(@TempDir Path folder) { originalUserHome = System.getProperty("user.home"); System.setProperty("user.home", folder.toAbsolutePath().toString()); Map<String, String> newEnvironment = Maps.newHashMap(); AltusSDKTestUtils.setEnv(newEnvironment); } @AfterEach public void resetEnvVariables() { System.setProperty("user.home", originalUserHome); } @Test public void readFromDefaultLocationDefaultProfileName(@TempDir Path folder) { AltusSDKTestUtils.copyTestCredentialsFileToFolder(folder); AltusProfileCredentialsProvider credentialsProvider = new AltusProfileCredentialsProvider(); AltusCredentials credentials = credentialsProvider.getCredentials(); assertNotNull(credentials.getPrivateKey()); assertEquals(AltusSDKTestUtils.DEFAULT_CREDENTIALS_KEY_ID, credentials.getAccessKeyId()); } @Test public void readFromDefaultLocationSpecifiedProfileName(@TempDir Path folder) { AltusSDKTestUtils.copyTestCredentialsFileToFolder(folder); AltusProfileCredentialsProvider credentialsProvider = new AltusProfileCredentialsProvider("altus_test"); AltusCredentials credentials = credentialsProvider.getCredentials(); assertNotNull(credentials.getPrivateKey()); assertEquals(AltusSDKTestUtils.TEST_CREDENTIALS_KEY_ID, credentials.getAccessKeyId()); } @Test public void invalidProfile(@TempDir Path folder) { AltusSDKTestUtils.copyTestCredentialsFileToFolder(folder); AltusProfileCredentialsProvider credentialsProvider = new AltusProfileCredentialsProvider("nonExistingName"); Throwable e = assertThrows(AltusClientException.class, () -> { credentialsProvider.getCredentials(); }); assertEquals("Unable to find profile named nonExistingName", e.getMessage()); } @Test public void invalidEnvVarProfile(@TempDir Path folder) { AltusSDKTestUtils.copyTestCredentialsFileToFolder(folder); Map<String, String> newEnvironment = Maps.newHashMap(); newEnvironment.put(AltusProfileCredentialsProvider.ALTUS_DEFAULT_PROFILE, "newEnvironmentprofile"); AltusSDKTestUtils.setEnv(newEnvironment); AltusProfileCredentialsProvider credentialsProvider = new AltusProfileCredentialsProvider(); Throwable e = assertThrows(AltusClientException.class, () -> { credentialsProvider.getCredentials(); }); assertEquals("Unable to find profile named newEnvironmentprofile", e.getMessage()); } @Test public void readFromEnvVar(@TempDir Path folder) { Map<String, String> newEnvironment = Maps.newHashMap(); newEnvironment.put(AltusProfileCredentialsProvider.ALTUS_DEFAULT_PROFILE, "altus_test"); AltusSDKTestUtils.setEnv(newEnvironment); AltusSDKTestUtils.copyTestCredentialsFileToFolder(folder); AltusProfileCredentialsProvider credentialsProvider = new AltusProfileCredentialsProvider(); AltusCredentials credentials = credentialsProvider.getCredentials(); assertNotNull(credentials.getPrivateKey()); assertEquals(AltusSDKTestUtils.TEST_CREDENTIALS_KEY_ID, credentials.getAccessKeyId()); } @Test public void readFromSpecifiedPath(@TempDir Path folder) { Path credentialsPath = AltusSDKTestUtils.copyTestCredentialsFileToFolder(folder); AltusProfileCredentialsProvider credentialsProvider = new AltusProfileCredentialsProvider(credentialsPath.toString(), "default"); AltusCredentials credentials = credentialsProvider.getCredentials(); assertNotNull(AltusSDKTestUtils.DEFAULT_CREDENTIALS_PRIVATE_KEY); assertEquals(AltusSDKTestUtils.DEFAULT_CREDENTIALS_KEY_ID, credentials.getAccessKeyId()); } }
WojciechKusa/datasets
datasets/wmt20_mlqe_task2/wmt20_mlqe_task2.py
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. """WMT20 MLQE Shared task 2.""" import datasets _CITATION = """ Not available. """ _DESCRIPTION = """\ This shared task (part of WMT20) will build on its previous editions to further examine automatic methods for estimating the quality of neural machine translation output at run-time, without relying on reference translations. As in previous years, we cover estimation at various levels. Important elements introduced this year include: a new task where sentences are annotated with Direct Assessment (DA) scores instead of labels based on post-editing; a new multilingual sentence-level dataset mainly from Wikipedia articles, where the source articles can be retrieved for document-wide context; the availability of NMT models to explore system-internal information for the task. Task 2 evaluates the application of QE for post-editing purposes. It consists of predicting: - A/ Word-level tags. This is done both on source side (to detect which words caused errors) and target side (to detect mistranslated or missing words). - A1/ Each token is tagged as either `OK` or `BAD`. Additionally, each gap between two words is tagged as `BAD` if one or more missing words should have been there, and `OK` otherwise. Note that number of tags for each target sentence is 2*N+1, where N is the number of tokens in the sentence. - A2/ Tokens are tagged as `OK` if they were correctly translated, and `BAD` otherwise. Gaps are not tagged. - B/ Sentence-level HTER scores. HTER (Human Translation Error Rate) is the ratio between the number of edits (insertions/deletions/replacements) needed and the reference translation length. """ _HOMEPAGE = "http://www.statmt.org/wmt20/quality-estimation-task.html" _LICENSE = "Unknown" _LANGUAGE_PAIRS = [ ("en", "de"), ("en", "zh"), ] _MAIN_URL = "https://github.com/deep-spin/deep-spin.github.io/raw/master/docs/data/wmt2020_qe" def inject_to_link(src_lg, tgt_lg): links = { "train+dev": f"{_MAIN_URL}/qe-{src_lg}{tgt_lg}-traindev.tar.gz", "test": f"{_MAIN_URL}/qe-{src_lg}{tgt_lg}-blindtest.tar.gz", } return links _URLs = {f"{src_lg}-{tgt_lg}": inject_to_link(src_lg, tgt_lg) for (src_lg, tgt_lg) in _LANGUAGE_PAIRS} class WmtMlqeConfig(datasets.BuilderConfig): def __init__(self, src_lg, tgt_lg, **kwargs): super(WmtMlqeConfig, self).__init__(**kwargs) self.src_lg = src_lg self.tgt_lg = tgt_lg class Wmt20MlqeTask2(datasets.GeneratorBasedBuilder): """WMT MLQE Shared task 2.""" BUILDER_CONFIGS = [ WmtMlqeConfig( name=f"{src_lg}-{tgt_lg}", version=datasets.Version("1.1.0"), description=f"Task 2: {src_lg} - {tgt_lg}", src_lg=src_lg, tgt_lg=tgt_lg, ) for (src_lg, tgt_lg) in _LANGUAGE_PAIRS ] BUILDER_CONFIG_CLASS = WmtMlqeConfig def _info(self): features = datasets.Features( { "translation": datasets.Translation(languages=(self.config.src_lg, self.config.tgt_lg)), "src_tags": datasets.Sequence(datasets.ClassLabel(names=["BAD", "OK"])), "mt_tags": datasets.Sequence(datasets.ClassLabel(names=["BAD", "OK"])), "pe": datasets.Value("string"), "hter": datasets.Value("float32"), "alignments": datasets.Sequence(datasets.Sequence(datasets.Value("int32"))), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" my_urls = _URLs[self.config.name] downloaded_files = dl_manager.download(my_urls) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepath": f"{self.config.src_lg}-{self.config.tgt_lg}/train", "split": "train", "source_lg": self.config.src_lg, "target_lg": self.config.tgt_lg, "files": dl_manager.iter_archive(downloaded_files["train+dev"]), }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "filepath": f"{self.config.src_lg}-{self.config.tgt_lg}/test-blind", "split": "test", "source_lg": self.config.src_lg, "target_lg": self.config.tgt_lg, "files": dl_manager.iter_archive(downloaded_files["test"]), }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "filepath": f"{self.config.src_lg}-{self.config.tgt_lg}/dev", "split": "dev", "source_lg": self.config.src_lg, "target_lg": self.config.tgt_lg, "files": dl_manager.iter_archive(downloaded_files["train+dev"]), }, ), ] def _generate_examples(self, filepath, split, source_lg, target_lg, files): """Yields examples.""" srcs_path = "/".join([filepath, f"{split}.src"]) mts_path = "/".join([filepath, f"{split}.mt"]) alignments_path = "/".join([filepath, f"{split}.src-mt.alignments"]) if split != "test": src_tags_path = "/".join([filepath, f"{split}.source_tags"]) mt_tags_path = "/".join([filepath, f"{split}.tags"]) pes_path = "/".join([filepath, f"{split}.pe"]) hters_path = "/".join([filepath, f"{split}.hter"]) srcs, mts, alignments, src_tags, mt_tags, pes, hters = [None] * 7 for path, f in files: if path == srcs_path: srcs = f.read().decode("utf-8").splitlines() elif path == mts_path: mts = f.read().decode("utf-8").splitlines() elif path == alignments_path: alignments = [ [idx_.split("-") for idx_ in t.split(" ")] for t in f.read().decode("utf-8").splitlines() ] if split != "test": if path == src_tags_path: src_tags = [t.split(" ") for t in f.read().decode("utf-8").splitlines()] elif path == mt_tags_path: mt_tags = [t.split(" ") for t in f.read().decode("utf-8").splitlines()] elif path == pes_path: pes = f.read().decode("utf-8").splitlines() elif path == hters_path: hters = f.read().decode("utf-8").splitlines() elif srcs is not None and src_tags is None: src_tags = [[]] * len(srcs) mt_tags = [[]] * len(srcs) pes = [""] * len(srcs) hters = [-10_000] * len(srcs) if all(x is not None for x in [srcs, mts, alignments, src_tags, mt_tags, pes, hters]): for id_, (src_, src_tags_, mt_, mt_tags_, pe_, hter_, alignments_) in enumerate( zip(srcs, src_tags, mts, mt_tags, pes, hters, alignments) ): yield id_, { "translation": {source_lg: src_, target_lg: mt_}, "src_tags": src_tags_, "mt_tags": mt_tags_, "pe": pe_, "hter": hter_, "alignments": alignments_, } break
felipelcaetano/tem-wifi-backend
src/main/java/br/com/temwifi/domains/infra/controller/AwsApiRestHandler.java
<reponame>felipelcaetano/tem-wifi-backend package br.com.temwifi.domains.infra.controller; import br.com.temwifi.domains.infra.model.request.AwsHttpContext; import br.com.temwifi.domains.infra.utils.exception.HttpException; public interface AwsApiRestHandler<I, O> { /** * Main method of each Aws Controller Class * * @param body * @param httpContext * @return * @throws HttpException */ O handleRequest(I body, AwsHttpContext httpContext) throws HttpException; }
matoruru/purescript-react-material-ui-svgicon
src/MaterialUI/SVGIcon/Icon/DoneOutlineRounded.js
exports.doneOutlineRoundedImpl = require('@material-ui/icons/DoneOutlineRounded').default;
Code4HR/okcandidate-platform
config/dev-fixtures/survey-result-fixtures.js
'use strict'; const surveyResults = [ { id: 1, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 1, CandidateId: 1 }, { id: 2, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 2, CandidateId: 1 }, { id: 3, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 3, CandidateId: 1 }, { id: 4, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 1, CandidateId: 2 }, { id: 5, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 2, CandidateId: 2 }, { id: 6, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 3, CandidateId: 2 }, { id: 7, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 1, CandidateId: 3 }, { id: 8, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 2, CandidateId: 3 }, { id: 9, publicPassPhrase: '<PASSWORD>', privatePassPhrase: '<PASSWORD>', SurveyId: 3, CandidateId: 3 } ]; module.exports = { load: (app) => { return app.orm.SurveyResult.count({}) .then(count => { if (count > 0) { return []; } const maxId = Math.max.apply(Math,surveyResults.map(o => o.id)); app.orm.SurveyResult.sequelize.query(`select setval('surveyresult_id_seq', ${maxId})`); // Create survey results return Promise.all( surveyResults.map(surveyResult => { return app.orm.SurveyResult.create(surveyResult); }) ) .then(newSurveyResults => { app.log.info('Survey results created.'); return newSurveyResults; }); }); } };
st-user/zerodep-web-push-java
src/main/java/com/zerodeplibs/webpush/key/ECPublicKeyUtil.java
<reponame>st-user/zerodep-web-push-java package com.zerodeplibs.webpush.key; import java.math.BigInteger; import java.security.interfaces.ECPublicKey; import java.security.spec.ECField; import java.security.spec.ECFieldFp; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.util.Base64; /** * The internal utility class for handling ECDSA public keys(mainly secp256r1). * * @author <NAME> */ class ECPublicKeyUtil { private ECPublicKeyUtil() { } private static final byte[] P256_HEAD = Base64.getDecoder().decode("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgA"); static byte[] uncompressedBytesToX509Bytes(byte[] uncompressedBytes) { byte[] encoded = new byte[P256_HEAD.length + uncompressedBytes.length]; System.arraycopy(P256_HEAD, 0, encoded, 0, P256_HEAD.length); System.arraycopy(uncompressedBytes, 0, encoded, P256_HEAD.length, uncompressedBytes.length); return encoded; } static byte[] encodedBytesToUncompressedBytes(byte[] encoded) { byte[] ret = new byte[65]; int elemCount = encoded.length - P256_HEAD.length; System.arraycopy(encoded, P256_HEAD.length, ret, 0, elemCount); return ret; } static void validateECPublicKey(ECPublicKey publicKey) { ECPoint w = publicKey.getW(); ECParameterSpec params = publicKey.getParams(); if (params.getCofactor() != 1) { throw new InvalidECPublicKeyException( "This method can't provide sufficient validation if h != 1."); } if (ECPoint.POINT_INFINITY.equals(w)) { throw new InvalidECPublicKeyException("Point at infinity."); } BigInteger x = publicKey.getW().getAffineX(); BigInteger y = publicKey.getW().getAffineY(); ECField field = publicKey.getParams().getCurve().getField(); BigInteger p = ((ECFieldFp) field).getP(); if (x.compareTo(BigInteger.ZERO) < 0 || x.compareTo(p) >= 0 || y.compareTo(BigInteger.ZERO) < 0 || y.compareTo(p) >= 0) { throw new InvalidECPublicKeyException("Both x and y are not in range [0, p-1]."); } BigInteger a = params.getCurve().getA(); BigInteger b = params.getCurve().getB(); BigInteger l = y.modPow(BigInteger.valueOf(2), p); BigInteger r = x.pow(3) .add(a.multiply(x)) .add(b) .mod(p); if (!l.equals(r)) { throw new InvalidECPublicKeyException("y^2 != x^3 + ax + b (mod p)"); } } }
tmikov/c99
tests/parser/crash1.c
int x;;
sbooeshaghi/bcl2fastq
src/cxx/lib/common/CsvGrammar.cpp
/** * BCL to FASTQ file converter * Copyright (c) 2007-2017 Illumina, Inc. * * This software is covered by the accompanying EULA * and certain third party copyright/licenses, and any user of this * source file is bound by the terms therein. * * \file CsvGrammar.cpp * * \brief Basic CSV grammar. * * \author <NAME> */ #include <algorithm> #include <iterator> #include <boost/format.hpp> #include <boost/bind.hpp> #include <boost/filesystem/fstream.hpp> #include "common/CsvGrammar.hh" #include "common/Exceptions.hh" namespace bcl2fastq { namespace common { CsvGrammarAttribute parseCsvFile(const boost::filesystem::path& csvFile) { int errnum; boost::filesystem::ifstream csvStream(csvFile); errnum = errno; if (!csvStream) { BOOST_THROW_EXCEPTION(common::IoError(errnum, (boost::format("Unable to open '%s' file for reading") % csvFile.string()).str())); } csvStream.unsetf(std::ios::skipws); typedef std::vector<char> CsvBuffer; CsvBuffer csvBuffer; errnum = 0; std::copy( std::istream_iterator<CsvBuffer::value_type>(csvStream), std::istream_iterator<CsvBuffer::value_type>(), std::back_inserter(csvBuffer) ); errnum = errno; if (!csvStream.eof()) { BOOST_THROW_EXCEPTION(common::IoError(errnum, "Failed to read " + csvFile.string() + " to the end")); } return parseCsvData(csvBuffer.begin(), csvBuffer.end()); } CsvGrammarAttribute::value_type::size_type correctCsvColumnsCount(CsvGrammarAttribute &csvData, const std::string &defaultValue) { if (csvData.empty()) { return 0; } const common::CsvGrammarAttribute::value_type::size_type maxCols = std::max_element( csvData.begin(), csvData.end(), boost::bind(&common::CsvGrammarAttribute::value_type::size, _1) < boost::bind(&common::CsvGrammarAttribute::value_type::size, _2) )->size(); std::for_each( csvData.begin(), csvData.end(), boost::bind(&common::CsvGrammarAttribute::value_type::resize, _1, maxCols, defaultValue) ); return maxCols; } } // namespace common } // namespace bcl2fastq
sakusimu/mh-skillsimu
benchmarks/util/timer.js
<gh_stars>1-10 'use strict'; class Timer { constructor(simu) { if (simu == null) throw new Error('simu is required'); this.simu = simu; this.records = {}; [ [ 'normalizer', 'normalize' ], [ 'combinator', 'combine' ], [ 'assembler', 'assemble' ] ].forEach(pair => this._spy(pair[0], pair[1])); } _spy(prop, method) { let obj = this.simu[prop]; let fn = obj[method]; obj[method] = (arg1, arg2, arg3) => { let p0 = Date.now(); let ret = fn.call(obj, arg1, arg2, arg3); let p1 = Date.now(); let time = p1 - p0; this._record(prop, time, ret); return ret; }; } _record(prop, time, ret) { this.records[prop] = { time: time, ret: ret }; } } module.exports = Timer;
gtaifu/CACTUS
src/1_digital/classical/classical_mem.cpp
<filename>src/1_digital/classical/classical_mem.cpp #include "classical_mem.h" #include "num_util.h" namespace cactus { void Classical_mem::config() { auto logger = get_logger_or_exit("console"); Global_config& global_config = Global_config::get_instance(); m_output_dir = global_config.output_dir; m_data_mem = global_config.data_memory; m_data_mem_size = m_data_mem->get_mem_size(); is_telf_on = true; telf_fn = sep_telf_fn(global_config.output_dir, this->name(), "classical_mem"); }; Classical_mem::Classical_mem(const sc_core::sc_module_name& n) : Telf_module(n) { auto logger = get_logger_or_exit("console"); logger->trace("Start initializing {}...", this->name()); config(); open_telf_file(); flags_cmp.init(16); flags_cmp_dly.init(16); // mem stage SC_CTHREAD(ex2mem_ff, clock.pos()); // read from memory SC_CTHREAD(read_mem, clock.pos()); // write to memory SC_CTHREAD(write_mem, clock.pos()); // sign extend SC_THREAD(sign_extend); sensitive << mem_sext << mem_addr_sel << mem_out_data; SC_CTHREAD(clock_counter, clock.pos()); logger->trace("Finished initializing {}...", this->name()); } Classical_mem::~Classical_mem() { close_telf_file(); } void Classical_mem::ex2mem_ff() { while (true) { wait(); mem_insn.write(ex_insn.read()); mem_ex_rd_value.write(ex_rd_value.read()); mem_wr_rd_en.write(ex_wr_rd_en.read()); mem_rd_addr.write(ex_rd_addr.read()); mem_run.write(ex_run.read()); mem_ex2reg.write(ex_ex2reg.read()); mem_addr_sel.write(ex_mem_addr_sel.read()); mem_sext.write(ex_mem_sext.read()); // cond_result.write(ex_cond_result.read()); for (size_t i = 0; i < 16; ++i) { flags_cmp_dly[i].write(flags_cmp[i].read()); } } } void Classical_mem::read_mem() { auto logger = get_logger_or_exit("console"); unsigned int read_data; bool need_data_next = false; unsigned int read_data_next; unsigned int read_addr; unsigned int byte_sel; std::string addr_sel_for_log; while (true) { wait(); if (ex_run.read() && ex_mem_strobe.read() && ex_mem_rw.read()) { read_addr = ex_rd_value.read().to_uint(); if (read_addr >= m_data_mem_size) { logger->error( "{}: Memory read address '0x{:08x}' is out of data memory size '0x{:08x}'. " "Simulation aborts!", this->name(), read_addr, m_data_mem_size); exit(EXIT_FAILURE); } read_data = m_data_mem->read_mem(read_addr >> 2); byte_sel = read_addr & 0x3; need_data_next = false; // check whether read address is out of memory when read a word if (ex_mem_addr_sel.read() == ADDR_WORD) { if (read_addr > m_data_mem_size - 4) { logger->error( "{}: Memory read address '0x{:08x}' is out of data memory size '0x{:08x}'. " "Simulation aborts!", this->name(), read_addr, m_data_mem_size); exit(EXIT_FAILURE); } if (byte_sel != 0) { need_data_next = true; } } // check whether read address is out of memory when read a half word if (ex_mem_addr_sel.read() == ADDR_HALF_WORD) { if (read_addr > m_data_mem_size - 2) { logger->error( "{}: Memory read address '0x{:08x}' is out of data_memory size '0x{:08x}'. " "Simulation aborts!", this->name(), read_addr, m_data_mem_size); exit(EXIT_FAILURE); } if (byte_sel == 3) { need_data_next = true; } } if (need_data_next) { read_data_next = m_data_mem->read_mem((read_addr >> 2) + 1); } switch (ex_mem_addr_sel.read()) { case ADDR_BYTE: // byte access switch (byte_sel) { case 0: read_data = read_data & 0x000000ff; break; case 1: read_data = (read_data & 0x0000ff00) >> 8; break; case 2: read_data = (read_data & 0x00ff0000) >> 16; break; case 3: read_data = (read_data & 0xff000000) >> 24; break; default: break; } addr_sel_for_log = "byte"; break; case ADDR_HALF_WORD: // half word access, not necessary aligned to 2 switch (byte_sel) { case 0: read_data = read_data & 0x0000ffff; break; case 1: read_data = (read_data & 0x00ffff00) >> 8; break; case 2: read_data = (read_data & 0xffff0000) >> 16; break; case 3: read_data = ((read_data_next & 0x000000ff) << 8) | ((read_data & 0xff000000) >> 24); break; default: break; } addr_sel_for_log = "half"; break; case ADDR_WORD: // word access, not necessary aligned to 4 switch (byte_sel) { case 0: // data has been read before switch statement break; case 1: read_data = (read_data >> 8) | ((read_data_next & 0x000000ff) << 24); break; case 2: read_data = (read_data >> 16) | ((read_data_next & 0x0000ffff) << 16); break; case 3: read_data = (read_data >> 24) | ((read_data_next & 0x00ffffff) << 8); break; default: break; } addr_sel_for_log = "word"; break; /* aligned to 2 case ADDR_HALF_WORD: // half word access if ((ex_rd_value.read() & 0x1) != 0) { // not 2 aligned logger->error( "{}: memory read address (0x{:8x}) is not aligned to 2 when write half " "word. Simulation aborts!", this->name(), ex_rd_value.read()); exit(EXIT_FAILURE); } // upper 16 bit if ((ex_rd_value.read() & 0x2) != 0) { read_data = (read_data & 0xffff0000) >> 16; } else { // lower 16 bit read_data = read_data & 0x0000ffff; } addr_sel_for_log = "half"; break; */ /* aligned to 4 case ADDR_WORD: // word access if ((ex_rd_value.read() & 0x3) != 0) { // not 4 aligned logger->error( "{}: memory write address (0x{:8x}) is not aligned to 4 when write a " "word. Simulation aborts!", this->name(), ex_rd_value.read()); exit(EXIT_FAILURE); } addr_sel_for_log = "word"; // data has been read before switch statement break; */ default: logger->error( "{}: Unrecognized memory access type. Support types: Byte, half word, word. " "Simulation aborts!", this->name()); exit(EXIT_FAILURE); break; } mem_out_data.write(read_data); // for logging if (is_telf_on) { telf_os << std::setfill(' ') << std::setw(15) << sc_core::sc_time_stamp().to_string(); telf_os << " " << std::setfill(' ') << std::setw(11) << std::dec << m_num_cycles; telf_os << " " << std::setfill(' ') << std::setw(3) << "r"; telf_os << " " << std::setfill(' ') << std::setw(10) << addr_sel_for_log; telf_os << " " << std::setfill('0') << std::setw(8) << std::hex << read_addr; telf_os << " " << std::setfill('0') << std::setw(8) << std::hex << read_data; telf_os << std::endl; } } } } void Classical_mem::write_mem() { auto logger = get_logger_or_exit("console"); unsigned int m_data; bool need_data_next = false; unsigned int m_data_next; unsigned int write_addr; std::string addr_sel_for_log; // for logging unsigned int data_for_log; // for logging while (true) { wait(); // store instr if (ex_run.read() && ex_mem_strobe.read() && !ex_mem_rw.read()) { write_addr = ex_rd_value.read().to_uint(); if (write_addr >= m_data_mem_size) { logger->error( "{}: Memory write address '0x{:08x}' is out of data memory size '0x{:08x}'. " "Simulation aborts!", this->name(), write_addr, m_data_mem_size); exit(EXIT_FAILURE); } m_data = m_data_mem->read_mem(write_addr >> 2); unsigned int byte_sel = ex_rd_value.read() & 0x3; need_data_next = false; // check whether read address is out of memory when read a word if (ex_mem_addr_sel.read() == ADDR_WORD) { if (write_addr > m_data_mem_size - 4) { logger->error( "{}: Memory write address '0x{:08x}' is out of data_memory size '0x{:08x}'. " "Simulation aborts!", this->name(), write_addr, m_data_mem_size); exit(EXIT_FAILURE); } if (byte_sel != 0) { need_data_next = true; } } // check whether read address is out of memory when read a half word if (ex_mem_addr_sel.read() == ADDR_HALF_WORD) { if (write_addr > m_data_mem_size - 2) { logger->error( "{}: Memory write address '0x{:08x}' is out of data memory size '0x{:08x}'. " "Simulation aborts!", this->name(), write_addr, m_data_mem_size); exit(EXIT_FAILURE); } if (byte_sel == 3) { need_data_next = true; } } if (need_data_next) { m_data_next = m_data_mem->read_mem((write_addr >> 2) + 1); } switch (ex_mem_addr_sel.read()) { case ADDR_BYTE: // byte access switch (byte_sel) { case 0: m_data = (m_data & 0xffffff00) | ex_mem_data.read().range(7, 0).to_uint(); break; case 1: m_data = (m_data & 0xffff00ff) | (ex_mem_data.read().range(7, 0).to_uint() << 8); break; case 2: m_data = (m_data & 0xff00ffff) | (ex_mem_data.read().range(7, 0).to_uint() << 16); break; case 3: m_data = (m_data & 0x00ffffff) | (ex_mem_data.read().range(7, 0).to_uint() << 24); break; default: break; } data_for_log = ex_mem_data.read().range(7, 0).to_uint(); addr_sel_for_log = "byte"; break; case ADDR_HALF_WORD: // half word access,not necessary aligned to 2 switch (byte_sel) { case 0: m_data = (m_data & 0xffff0000) | ex_mem_data.read().range(15, 0).to_uint(); break; case 1: m_data = (m_data & 0xff0000ff) | (ex_mem_data.read().range(15, 0).to_uint() << 8); break; case 2: m_data = (m_data & 0x0000ffff) | (ex_mem_data.read().range(15, 0).to_uint() << 16); break; case 3: m_data = (m_data & 0x00ffffff) | (ex_mem_data.read().range(7, 0).to_uint() << 24); m_data_next = (m_data_next & 0xffffff00) | ex_mem_data.read().range(15, 8).to_uint(); break; default: break; } data_for_log = ex_mem_data.read().range(15, 0).to_uint(); addr_sel_for_log = "half"; break; case ADDR_WORD: // word access, not necessary aligned to 4 switch (byte_sel) { case 0: m_data = ex_mem_data.read().to_uint(); break; case 1: m_data = (m_data & 0x000000ff) | (ex_mem_data.read().range(23, 0).to_uint() << 8); m_data_next = (m_data_next & 0xffffff00) | ex_mem_data.read().range(31, 24).to_uint(); break; case 2: m_data = (m_data & 0x0000ffff) | (ex_mem_data.read().range(15, 0).to_uint() << 16); m_data_next = (m_data_next & 0xffff0000) | ex_mem_data.read().range(31, 16).to_uint(); break; case 3: m_data = (m_data & 0x00ffffff) | (ex_mem_data.read().range(7, 0).to_uint() << 24); m_data_next = (m_data_next & 0xff000000) | ex_mem_data.read().range(31, 8).to_uint(); break; default: break; } data_for_log = ex_mem_data.read().to_uint(); addr_sel_for_log = "word"; break; /* case ADDR_HALF_WORD: // half word access,need addr aligned to 2 if ((ex_rd_value.read() & 0x1) != 0) { // not 2 aligned logger->error( "{}: memory write address (0x{:8x}) is not aligned to 2 when write " "half " "word. Simulation aborts!", this->name(), ex_rd_value.read()); exit(EXIT_FAILURE); } // upper 16 bit if ((ex_rd_value.read() & 0x2) != 0) { m_data = (m_data & 0x0000ffff) | (ex_mem_data.read().range(15, 0).to_uint() << 16); } else { // lower 16 bit m_data = (m_data & 0xffff0000) | ex_mem_data.read().range(15, 0).to_uint(); } data_for_log = ex_mem_data.read().range(15, 0).to_uint(); addr_sel_for_log = "half"; break; case ADDR_WORD: // word access, need aligned to 4 if ((ex_rd_value.read() & 0x3) != 0) { // not 4 aligned logger->error( "{}: memory write address (0x{:8x}) is not aligned to 4 when write a " "word. Simulation aborts!", this->name(), ex_rd_value.read()); exit(EXIT_FAILURE); } m_data = ex_mem_data.read().to_uint(); data_for_log = ex_mem_data.read().to_uint(); addr_sel_for_log = "word"; break; */ default: logger->error( "{}: Unrecognized memory access type. Support types: byte, half word, word. " "Simulation aborts!", this->name()); exit(EXIT_FAILURE); break; } // write to mem m_data_mem->write_mem(write_addr >> 2, m_data); if (need_data_next) { m_data_mem->write_mem((write_addr >> 2) + 1, m_data_next); } // logging if (is_telf_on) { telf_os << std::setfill(' ') << std::setw(15) << sc_core::sc_time_stamp().to_string(); telf_os << " " << std::setfill(' ') << std::setw(11) << std::dec << m_num_cycles; telf_os << " " << std::setfill(' ') << std::setw(3) << "w"; telf_os << " " << std::setfill(' ') << std::setw(10) << addr_sel_for_log; telf_os << " " << std::setfill('0') << std::setw(8) << std::hex << write_addr; telf_os << " " << std::setfill('0') << std::setw(8) << std::hex << data_for_log; telf_os << std::endl; } } } } void Classical_mem::sign_extend() { auto logger = get_logger_or_exit("console"); sc_int<32> data; while (true) { wait(); /* sign extend : The value of the left-most bit of the data (bit 15 or bit 7) is copied * to all bits to the left (into the high-order bits) */ /* non sign extend: 0 is copied to all bits to the left (into the high-order bits)*/ switch (mem_addr_sel.read()) { case ADDR_BYTE: // byte access if (mem_sext.read() && (mem_out_data.read() & 0x80)) { // sign value and copy 1 to the left bits mem_rd_value.write(mem_out_data.read() | 0xffffff00); } else { mem_rd_value.write(mem_out_data.read().to_uint()); } break; case ADDR_HALF_WORD: // half word access if (mem_sext.read() && (mem_out_data.read() & 0x8000)) { // sign value and copy 1 to the left bits mem_rd_value.write(mem_out_data.read() | 0xffff0000); } else { mem_rd_value.write(mem_out_data.read().to_uint()); } break; case ADDR_WORD: // word access mem_rd_value.write(mem_out_data.read().to_uint()); break; default: logger->error( "{}: Unrecognized memory access type. Support types: byte, half word, word. " "Simulation aborts!", this->name()); exit(EXIT_FAILURE); break; } } } void Classical_mem::clock_counter() { while (true) { wait(); m_num_cycles++; } } void Classical_mem::add_telf_header() { // Specify the signal type telf_os << "#memory access" << std::endl; telf_os << std::setfill(' ') << std::setw(15) << "sim_time"; telf_os << " " << std::setfill(' ') << std::setw(11) << "cycle"; telf_os << " " << std::setfill(' ') << std::setw(3) << "r/w"; telf_os << " " << std::setfill(' ') << std::setw(10) << "addr_sel"; telf_os << " " << std::setfill(' ') << std::setw(8) << "address"; telf_os << " " << std::setfill(' ') << std::setw(8) << "value"; telf_os << std::endl; } } // namespace cactus
leonardoanalista/java2word
java2word/src/test/java/word/w2004/HeadingStyleTest.java
package word.w2004; import junit.framework.Assert; import org.junit.Test; import word.w2004.style.HeadingStyle; public class HeadingStyleTest extends Assert{ @Test public void sanityTest(){ HeadingStyle style = new HeadingStyle(); assertNotNull(style); } }
katucker/midas
api/controllers/SearchController.js
<filename>api/controllers/SearchController.js /** * SearchController * * @module :: Controller * @description :: Performs search functions for the front end */ var _ = require('underscore'); var async = require('async'); var projUtil = require('../services/utils/project'); var taskUtil = require('../services/utils/task'); var tagUtil = require('../services/utils/tag'); function search (target, req, res) { // Store the userid for use later var userId = null; if (req.user) { userId = req.user[0].id; } // make the query well formed var q = req.body; q.items = q.items || []; q.tags = q.tags || []; // store the result data var items = []; var itemIds = q.items; var itemIdsAuthorized = []; // For each tag, find items associated with it var processTag = function (tagId, cb) { var where = {}; var t = target.substr(0, target.length - 1); where[t + 'Id'] = { not: null }; Tag.find() .where({ tagId: tagId }) .where(where) .exec(function (err, tags) { for (var i in tags) { if (_.indexOf(itemIds, tags[i][t + 'Id']) == -1) { itemIds.push(tags[i][t + 'Id']); } } cb(err); }); }; var checkFn = projUtil.authorized; if (target == 'tasks') { checkFn = taskUtil.authorized; } // Get the item by checking if we're authorized to view it var check = function (id, cb) { checkFn(id, userId, function (err, item) { if (!err && item) { items.push(item); itemIdsAuthorized.push(item.id); } cb(err); }); }; // Get each of the items with given tags async.each(q.tags, processTag, function (err) { if (err) { return res.send(400, { message: 'Error performing query.'}); } // Get the details of each item async.each(itemIds, check, function (err) { if (err) { return res.send(400, { message: 'Error performing query.'}); } // if there's no matching items (task or project), return an empty array if (itemIdsAuthorized.length === 0) { return res.send([]); } // Perform item specific processing // Get task metadata if (target == 'tasks') { // Look up task metadata taskUtil.findTasks({ id: itemIdsAuthorized }, function (err, items) { if (err) { return res.send(400, { message: 'Error performing query.', error: err }); } return res.send(items); }); return; } // Get project metadata async.each(items, projUtil.addCounts, function (err) { if (err) { return res.send(400, { message: 'Error performing query.'}); } res.send(items); }); }); }); }; module.exports = { index: function (req, res) { if (!req.body) { return res.send(400, { message: 'Need data to query' }); } if ((req.body.target == 'projects') || (req.body.target == 'tasks')) { return search(req.body.target, req, res); } return res.send([]); }, };
anderjason/util
dist/NumberUtil/_internal/numberWithRangeMap.js
<reponame>anderjason/util "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.numberWithRangeMap = void 0; const numberWithHardLimit_1 = require("./numberWithHardLimit"); function numberWithRangeMap(input, inputLow, inputHigh, outputLow, outputHigh) { const result = ((input - inputLow) * (outputHigh - outputLow)) / (inputHigh - inputLow) + outputLow; return numberWithHardLimit_1.numberWithHardLimit(result, Math.min(outputLow, outputHigh), Math.max(outputLow, outputHigh)); } exports.numberWithRangeMap = numberWithRangeMap; //# sourceMappingURL=numberWithRangeMap.js.map
anniyanvr/nesta
nesta/core/batchables/nih/nih_dedupe/run.py
""" run.py (nih_dedupe) ------------------- Deduplicate NiH articles based on similarity scores using Elasticsearch's document similarity API. Similarity is calculated based on the description of the project, the project abstract and the title of the project. Funding information is aggregated (summed) across all deduplicated articles, for the total and annuals funds. """ import logging from nesta.core.luigihacks.elasticsearchplus import ElasticsearchPlus from nesta.core.orms.orm_utils import load_json_from_pathstub from collections import Counter import json import boto3 import os import numpy as np import time def get_value(obj, key): """Retrieve a value by key if exists, else return None.""" try: return obj[key] except KeyError: return def extract_yearly_funds(src): """Extract yearly funds""" year = get_value(src, 'year_fiscal_funding') cost_ref = get_value(src, 'cost_total_project') start_date = get_value(src, 'date_start_project') end_date = get_value(src, 'date_end_project') yearly_funds = [] if year is not None: yearly_funds = [{'year':year, 'cost_ref': cost_ref, 'start_date': start_date, 'end_date': end_date}] return yearly_funds def run(): # Fetch the input parameters s3_bucket = os.environ["BATCHPAR_bucket"] batch_file = os.environ["BATCHPAR_batch_file"] es_host = os.environ['BATCHPAR_outinfo'] es_port = int(os.environ['BATCHPAR_out_port']) es_new_index = os.environ['BATCHPAR_out_index'] es_old_index = os.environ['BATCHPAR_in_index'] es_type = os.environ['BATCHPAR_out_type'] entity_type = os.environ["BATCHPAR_entity_type"] aws_auth_region = os.environ["BATCHPAR_aws_auth_region"] # Extract the article ids in this chunk s3 = boto3.resource('s3') ids_obj = s3.Object(s3_bucket, batch_file) art_ids = json.loads(ids_obj.get()['Body']._raw_stream.read()) logging.info(f'Processing {len(art_ids)} article ids') field_null_mapping = load_json_from_pathstub("health-scanner", "nulls.json") es = ElasticsearchPlus(hosts=es_host, port=es_port, aws_auth_region=aws_auth_region, no_commit=("AWSBATCHTEST" in os.environ), entity_type=entity_type, field_null_mapping=field_null_mapping, send_get_body_as='POST') # Iterate over article IDs processed_ids = set() for _id in art_ids: if _id in processed_ids: # To avoid duplicated effort continue # Collect all duplicated data together dupe_ids = {} # For identifying the most recent dupe yearly_funds = [] # The new deduped collection of annual funds hits = {} for hit in es.near_duplicates(index=es_old_index, doc_id=_id, doc_type=es_type, fields=["textBody_descriptive_project", "title_of_project", "textBody_abstract_project"]): # Extract key values src = hit['_source'] hit_id = hit['_id'] # Record this hit processed_ids.add(hit_id) hits[hit_id] = src # Extract year and funding info yearly_funds += extract_yearly_funds(src) year = get_value(src, 'year_fiscal_funding') if year is not None: dupe_ids[hit_id] = year # Get the most recent instance of the duplicates final_id = sorted(hits.keys())[-1] # default if years are all null if len(dupe_ids) > 0: # implies years are not all null final_id, year = Counter(dupe_ids).most_common()[0] body = hits[final_id] processed_ids = processed_ids.union(set(dupe_ids)) # Sort and sum the funding yearly_funds = sorted(yearly_funds, key=lambda row: row['year']) sum_funding = sum(row['cost_ref'] for row in yearly_funds if row['cost_ref'] is not None) # Add funding info and commit to the new index body['json_funding_project'] = yearly_funds body['cost_total_project'] = sum_funding body['date_start_project'] = yearly_funds[0]['start_date'] # just in case es.index(index=es_new_index, doc_type=es_type, id=final_id, body=body) logging.info(f'Processed {len(processed_ids)} ids') logging.info("Batch job complete.") # For local debugging if __name__ == "__main__": log_level = logging.INFO if 'BATCHPAR_outinfo' not in os.environ: logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('s3transfer').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) log_level = logging.INFO pars = {'batch_file': ('2019-05-23-True-' '1564652840333777.json'), 'config': 'mysqldb.config', 'bucket': 'nesta-production-intermediate', 'done': 'False', 'outinfo': ('https://search-health-scanner-' '5cs7g52446h7qscocqmiky5dn4.' 'eu-west-2.es.amazonaws.com'), 'out_port': '443', 'out_index': 'nih_v5', 'in_index': 'nih_v4', 'out_type': '_doc', 'aws_auth_region': 'eu-west-2', 'entity_type': 'paper', 'test': 'False', 'routine_id': '2019-05-23-True'} for k, v in pars.items(): os.environ[f'BATCHPAR_{k}'] = v log_stream_handler = logging.StreamHandler() logging.basicConfig(handlers=[log_stream_handler, ], level=log_level, format="%(asctime)s:%(levelname)s:%(message)s") run()
gtfierro/hod
db/transaction.go
package db import ( "container/list" "fmt" sparql "github.com/gtfierro/hod/lang/ast" "github.com/gtfierro/hod/turtle" "github.com/pkg/errors" logrus "github.com/sirupsen/logrus" "github.com/syndtr/goleveldb/leveldb" "time" ) const ( RDF_NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns" OWL_NAMESPACE = "http://www.w3.org/2002/07/owl" ) var ( INVERSEOF = turtle.URI{ Namespace: OWL_NAMESPACE, Value: "inverseOf", } ) // wrapper around the internal k/v store transaction type transaction struct { entity *leveldb.Transaction pk *leveldb.Transaction graph *leveldb.Transaction ext *leveldb.Transaction pred *leveldb.Transaction predbatch map[Key]*PredicateEntity triplesAdded int hashes map[turtle.URI]Key inverseRelationships map[Key]Key t *traversal cache *dbcache } func (db *DB) openTransaction() (tx *transaction, err error) { tx = &transaction{ hashes: make(map[turtle.URI]Key), inverseRelationships: make(map[Key]Key), predbatch: make(map[Key]*PredicateEntity), cache: db.cache, } t := &traversal{under: tx} tx.t = t getTransaction := func(db *leveldb.DB) (*leveldb.Transaction, error) { if ltx, err := db.OpenTransaction(); err != nil { if tx.entity != nil { tx.entity.Discard() } if tx.pk != nil { tx.pk.Discard() } if tx.graph != nil { tx.graph.Discard() } if tx.ext != nil { tx.ext.Discard() } if tx.pred != nil { tx.pred.Discard() } return nil, err } else { return ltx, err } } if tx.entity, err = getTransaction(db.entityDB); err != nil { return } if tx.pk, err = getTransaction(db.pkDB); err != nil { return } if tx.graph, err = getTransaction(db.graphDB); err != nil { return } if tx.ext, err = getTransaction(db.extendedDB); err != nil { return } if tx.pred, err = getTransaction(db.predDB); err != nil { return } return } func (tx *transaction) discard() { tx.entity.Discard() tx.pk.Discard() tx.graph.Discard() tx.ext.Discard() tx.pred.Discard() } func (tx *transaction) commit() error { if err := tx.entity.Commit(); err != nil { tx.discard() return err } if err := tx.pk.Commit(); err != nil { tx.discard() return err } if err := tx.graph.Commit(); err != nil { tx.discard() return err } if err := tx.ext.Commit(); err != nil { tx.discard() return err } if err := tx.pred.Commit(); err != nil { tx.discard() return err } return nil } func (tx *transaction) done() error { var b = new(leveldb.Batch) for key, predent := range tx.predbatch { bytes, err := predent.MarshalMsg(nil) if err != nil { return err } b.Put(key[:], bytes) } if err := tx.pred.Write(b, nil); err != nil { return err } return tx.commit() } func (tx *transaction) getHash(uri turtle.URI) (Key, error) { var ret Key val, err := tx.entity.Get(uri.Bytes(), nil) if err != nil { return ret, fmt.Errorf("Got non-existent hash but it should exist for %s", uri) } copy(ret[:], val) return ret, nil } func (tx *transaction) getURI(hash Key) (turtle.URI, error) { if hash == emptyKey { return turtle.URI{}, nil } val, err := tx.pk.Get(hash[:], nil) if err != nil { return turtle.URI{}, errors.Wrapf(err, "Could not get URI for %v", hash) } uri := turtle.ParseURI(string(val)) if err != nil { return turtle.URI{}, errors.Wrapf(err, "Could not get URI for %v", hash) } return uri, nil } func (tx *transaction) putEntity(ent *Entity) error { bytes, err := ent.MarshalMsg(nil) if err != nil { return err } return tx.graph.Put(ent.PK[:], bytes, nil) } func (tx *transaction) getEntityByURI(uri turtle.URI) (*Entity, error) { hash, err := tx.getHash(uri) if err != nil { return nil, err } return tx.getEntityByHash(hash) } func (tx *transaction) getEntityByHash(hash Key) (*Entity, error) { var entity = NewEntity() bytes, err := tx.graph.Get(hash[:], nil) if err != nil && err != leveldb.ErrNotFound { return nil, errors.Wrap(err, "Error getting entity from transaction") } _, err = entity.UnmarshalMsg(bytes) if err != nil { return nil, errors.Wrap(err, "Error deserializing entity from transaction") } return entity, nil } func (tx *transaction) getExtendedIndexByHash(hash Key) (*EntityExtendedIndex, error) { bytes, err := tx.ext.Get(hash[:], nil) if err != nil { return nil, err } ent := NewEntityExtendedIndex() _, err = ent.UnmarshalMsg(bytes) return ent, err } func (tx *transaction) getExtendedIndexByURI(uri turtle.URI) (*EntityExtendedIndex, error) { hash, err := tx.getHash(uri) if err != nil { return nil, err } return tx.getExtendedIndexByHash(hash) } func (tx *transaction) saveExtendedIndex(index *EntityExtendedIndex) error { if bytes, err := index.MarshalMsg(nil); err != nil { return errors.Wrap(err, "Error serializing extended index from transaction") } else if err := tx.ext.Put(index.PK[:], bytes, nil); err != nil { return errors.Wrap(err, "Error inserting extended index in transaction") } return nil } func (tx *transaction) getPredicateByURI(uri turtle.URI) (*PredicateEntity, error) { hash, err := tx.getHash(uri) if err != nil { return nil, err } return tx.getPredicateByHash(hash) } func (tx *transaction) getPredicateByHash(hash Key) (*PredicateEntity, error) { if pred, found := tx.predbatch[hash]; found { return pred, nil } var pred = NewPredicateEntity() bytes, err := tx.pred.Get(hash[:], nil) if err != nil && err != leveldb.ErrNotFound { return nil, errors.Wrap(err, "Error getting predicate from transaction") } else if err == leveldb.ErrNotFound { // add predicate entity to predhash db pred.PK = hash tx.predbatch[pred.PK] = pred return pred, nil } else if _, err = pred.UnmarshalMsg(bytes); err == nil { tx.predbatch[pred.PK] = pred return pred, nil } else { return pred, err } } func (tx *transaction) addTriples(dataset turtle.DataSet) error { var newPredicates = make(map[Key]struct{}) addStart := time.Now() // add all URIs to the database for _, triple := range dataset.Triples { if err := tx.addTriple(triple); err != nil { return errors.Wrapf(err, "Could not load triple (%s)", triple) } newPredicates[tx.hashes[triple.Predicate]] = struct{}{} // mark new predicate // if triple defines an inverseOf relationship, then track the subject/object of that // triple so we can populate the graph later if triple.Predicate.Namespace == OWL_NAMESPACE && triple.Predicate.Value == "inverseOf" { subjectHash := tx.hashes[triple.Subject] objectHash := tx.hashes[triple.Object] tx.inverseRelationships[subjectHash] = objectHash tx.inverseRelationships[objectHash] = subjectHash tx.getPredicateByURI(triple.Subject) tx.getPredicateByURI(triple.Object) } tx.triplesAdded += 1 } addEnd := time.Now() // pull out all of the inverse edges from the database and add to inverseRelationships reverseEdgeFindStart := time.Now() var predicatesAdded int pred, err := tx.getPredicateByURI(INVERSEOF) if err != nil && err != leveldb.ErrNotFound { logrus.WithError(err).Error("Could not load INVERSEOF pred") } else if err == nil { for subject, objectMap := range pred.Subjects { for object := range objectMap { var sh, oh Key sh.FromSlice([]byte(subject)) oh.FromSlice([]byte(object)) tx.inverseRelationships[sh] = oh tx.inverseRelationships[oh] = sh predicatesAdded += 1 } } } reverseEdgeFindEnd := time.Now() // add the inverse edges to the graph index reverseEdgeBuildStart := time.Now() var subject, object Key for predicate, reversePredicate := range tx.inverseRelationships { pred, err := tx.getPredicateByHash(predicate) _uri, _ := tx.getURI(predicate) if err != nil { return errors.Wrapf(err, "Could not load predicate %s", _uri) } revPred, err := tx.getPredicateByHash(reversePredicate) _uri, _ = tx.getURI(reversePredicate) if err != nil { return errors.Wrapf(err, "Could not load reverse predicate %s", _uri) } for subjectStr, objectMap := range pred.Subjects { subject.FromSlice([]byte(subjectStr)) for objectStr := range objectMap { object.FromSlice([]byte(objectStr)) subjectEnt, err := tx.getEntityByHash(subject) if err != nil { return errors.Wrap(err, "Could not load subject") } objectEnt, err := tx.getEntityByHash(object) if err != nil { return errors.Wrap(err, "Could not load object") } subjectEnt.AddInEdge(reversePredicate, object) subjectEnt.AddOutEdge(predicate, object) objectEnt.AddOutEdge(reversePredicate, subject) objectEnt.AddInEdge(predicate, subject) if err = tx.putEntity(subjectEnt); err != nil { return err } if err = tx.putEntity(objectEnt); err != nil { return err } revPred.AddSubjectObject(object, subject) } } tx.predbatch[reversePredicate] = revPred } reverseEdgeBuildEnd := time.Now() extendedBuildStart := time.Now() // for all *new* predicates, roll the edges forward for all entities in the transaction. for predicateHash := range newPredicates { tx.rollupPredicate(predicateHash) if reversePredicate, found := tx.inverseRelationships[predicateHash]; found { //fmt.Println(reversePredicate) // for all entities // add the roll-forward index tx.rollupPredicate(reversePredicate) } } extendedBuildEnd := time.Now() // TODO: for all *new* entities, roll the edges forward for all predicates //for _, turtle := range dataset.Triples { //} logrus.WithFields(logrus.Fields{ "EdgeBuild": reverseEdgeBuildEnd.Sub(reverseEdgeBuildStart), "AddTriples": addEnd.Sub(addStart), "EdgeFind": reverseEdgeFindEnd.Sub(reverseEdgeFindStart), "ExtendedIndexBuild": extendedBuildEnd.Sub(extendedBuildStart), "Triples": tx.triplesAdded, "Predicates": predicatesAdded, }).Info("Insert") return nil } // things to do: // - check for inverseOf relationships (do as a second pass?) and mark these for reverse edges // - track the namespaces we find // - add the class name to the text index // - add reverse edges to the graph // - populate predicate index // // for each part of the triple (subject, predicate, object), we check if its already in the entity database. // If it is, we can skip it. If not, we generate a murmur3 hash for the entity, and then // 0. check if we've already inserted the entity (skip if we already have) // 1. check if the hash is unique (check membership in pk db) - if it isn't then we add a salt and check again // 2. insert hash => []byte(entity) into pk db // 3. insert []byte(entity) => hash into entity db func (tx *transaction) addTriple(triple turtle.Triple) error { // insert subject, predicate and object tx.addURI(triple.Subject) tx.addURI(triple.Predicate) tx.addURI(triple.Object) // add the "1 or more" edge for the extended index rev := triple.Predicate rev.Value += "+" tx.addURI(rev) // populate subject, predicate and object in graph index with forward/inverse edges var ( subjectHash = tx.hashes[triple.Subject] predicateHash = tx.hashes[triple.Predicate] objectHash = tx.hashes[triple.Object] ) pred, err := tx.getPredicateByURI(triple.Predicate) if err != nil { return err } if pred.AddSubjectObject(subjectHash, objectHash) { tx.predbatch[pred.PK] = pred } subject, err := tx.getEntityByURI(triple.Subject) if err != nil { return err } object, err := tx.getEntityByURI(triple.Object) if err != nil { return err } if subject.AddOutEdge(predicateHash, object.PK) { if err = tx.putEntity(subject); err != nil { return err } } if object.AddInEdge(predicateHash, subject.PK) { if err = tx.putEntity(object); err != nil { return err } } tx.cache.evict(subjectHash) tx.cache.evict(objectHash) tx.cache.evict(predicateHash) return nil } // add the URI to the transaction. This involves: // - compute the hash of the entity // - add the entity and its hash to the entity/pk dbs // - initialize the entity's "neighbor table" in the graph db if it doesn't exist yet func (tx *transaction) addURI(uri turtle.URI) error { var hashdest Key var found bool if hashdest, found = tx.hashes[uri]; !found { if _hashdest, err := tx.entity.Get(uri.Bytes(), nil); err != nil && err != leveldb.ErrNotFound { return errors.Wrap(err, "Could not check key existence") } else if err == nil { copy(hashdest[:], _hashdest) } else if err == leveldb.ErrNotFound { // else if not found, then generate it var salt = uint64(0) hashURI(uri, hashdest[:], salt) for { if exists, err := tx.pk.Has(hashdest[:], nil); err == nil && exists { log.Warning("hash exists", uri) salt += 1 hashURI(uri, hashdest[:], salt) } else if err != nil { return errors.Wrapf(err, "Error checking db membership for %v", hashdest) } else { break } } // insert the hash into the entity and prefix dbs if err := tx.entity.Put(uri.Bytes(), hashdest[:], nil); err != nil { return errors.Wrapf(err, "Error inserting uri %s", uri.String()) } if err := tx.pk.Put(hashdest[:], uri.Bytes(), nil); err != nil { return errors.Wrapf(err, "Error inserting pk %s", hashdest) } } tx.hashes[uri] = hashdest } // insert the hash into the graph index if it doesn't exist already if exists, err := tx.graph.Has(hashdest[:], nil); err == nil && !exists { ent := NewEntity() ent.PK = hashdest if bytes, err := ent.MarshalMsg(nil); err != nil { return err } else if err := tx.graph.Put(hashdest[:], bytes, nil); err != nil { return err } } else if err != nil { return err } return nil } // follows all paths func (tx *transaction) rollupPredicate(predicateHash Key) error { var err error forwardPath := sparql.PathPattern{Pattern: sparql.PATTERN_ONE_PLUS} results := newKeymap() forwardPath.Predicate, err = tx.getURI(predicateHash) if err != nil { return err } predicate, err := tx.getPredicateByHash(predicateHash) if err != nil { return err } for subjectStringHash := range predicate.Subjects { var subjectHash Key subjectHash.FromSlice([]byte(subjectStringHash)) if exists, err := tx.ext.Has(subjectHash[:], nil); err == nil && !exists { subjectIndex := NewEntityExtendedIndex() subjectIndex.PK = subjectHash bytes, err := subjectIndex.MarshalMsg(nil) if err != nil { return err } if err := tx.ext.Put(subjectHash[:], bytes, nil); err != nil { return err } } else if err != nil { return err } subjectIndex, err := tx.getExtendedIndexByHash(subjectHash) if err != nil { return err } subject, err := tx.getEntityByHash(subjectHash) if err != nil { return err } stack := list.New() tx.t.followPathFromSubject(subject, results, stack, forwardPath) for results.Len() > 0 { objectIndex, err := tx.getExtendedIndexByHash(results.Max()) if err != nil { return err } subjectIndex.AddOutPlusEdge(predicateHash, results.DeleteMax()) objectIndex.AddInPlusEdge(predicateHash, subjectHash) if err := tx.saveExtendedIndex(objectIndex); err != nil { return err } } if err := tx.saveExtendedIndex(subjectIndex); err != nil { return err } } for objectStringHash := range predicate.Objects { var objectHash Key objectHash.FromSlice([]byte(objectStringHash)) if exists, err := tx.ext.Has(objectHash[:], nil); err == nil && !exists { objectIndex := NewEntityExtendedIndex() objectIndex.PK = objectHash if err := tx.saveExtendedIndex(objectIndex); err != nil { return err } } else if err != nil { return err } objectIndex, err := tx.getExtendedIndexByHash(objectHash) if err != nil { return err } object, err := tx.getEntityByHash(objectHash) if err != nil { return err } stack := list.New() tx.t.followPathFromObject(object, results, stack, forwardPath) for results.Len() > 0 { subjectIndex, err := tx.getExtendedIndexByHash(results.Max()) if err != nil { return err } objectIndex.AddInPlusEdge(predicateHash, results.DeleteMax()) subjectIndex.AddOutPlusEdge(predicateHash, objectHash) if err := tx.saveExtendedIndex(subjectIndex); err != nil { return err } } if err := tx.saveExtendedIndex(objectIndex); err != nil { return err } } return nil } func (tx *transaction) getReverseRelationship(forward turtle.URI) (reverse turtle.URI, found bool) { var ( forwardHash, reverseHash Key err error ) forwardHash, err = tx.getHash(forward) if err != nil { logrus.WithFields(logrus.Fields{ "predicate": forward, "err": err, }).Error("transaction") found = false return } if reverseHash, found = tx.inverseRelationships[forwardHash]; !found { return } else if reverse, err = tx.getURI(reverseHash); err != nil { logrus.WithFields(logrus.Fields{ "predicate": forward, "err": err, }).Error("transaction") found = false return } return } func (tx *transaction) iterAllEntities(F func(Key, *Entity) bool) error { iter := tx.graph.NewIterator(nil, nil) for iter.Next() { var subjectHash Key entityHash := iter.Key() copy(subjectHash[:], entityHash[:8]) var entity = NewEntity() _, err := entity.UnmarshalMsg(iter.Value()) if err != nil { return err } if F(subjectHash, entity) { return nil } } return nil }
born2net/mediaArduino
dev/node_modules/cylon-firmata/node_modules/cylon-gpio/test/specs/continuous-servo.spec.js
<filename>dev/node_modules/cylon-firmata/node_modules/cylon-gpio/test/specs/continuous-servo.spec.js "use strict"; var ContinuousServo = source("continuous-servo"); describe("ContinuousServo", function() { var driver = new ContinuousServo({ name: 'serv', device: { connection: { servoWrite: spy() }, pin: 13 } }); describe("#constructor", function() { it("sets @pin to the provided device's pin", function() { expect(driver.pin).to.be.eql(13); }); it("sets @angleValue to 0 by default", function() { expect(driver.angleValue).to.be.eql(0); }); }); describe("#commands", function() { it("is an object containing ContinuousServo commands", function() { for (var c in driver.commands) { expect(driver.commands[c]).to.be.a('function'); } }); }); describe("#stop", function() { it('writes a value of 90 to the servo', function() { driver.stop(); expect(driver.connection.servoWrite).to.be.calledWith(13, 90); }); }); describe("#clockwise", function() { it('writes a value of 180 to the servo', function() { driver.clockwise(); expect(driver.connection.servoWrite).to.be.calledWith(13, 180); }); }); describe("#counterClockwise", function() { it('writes a value of 180 to the servo', function() { driver.counterClockwise(); expect(driver.connection.servoWrite).to.be.calledWith(13, 89); }); }); });
wainshine/tensorflow
tensorflow/compiler/xla/primitive_util.h
/* Copyright 2017 The TensorFlow 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. ==============================================================================*/ // Utilities for dealing with XLA primitive types. #ifndef TENSORFLOW_COMPILER_XLA_PRIMITIVE_UTIL_H_ #define TENSORFLOW_COMPILER_XLA_PRIMITIVE_UTIL_H_ #include <string> #include <type_traits> #include "absl/strings/string_view.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { namespace primitive_util { // Returns the count of significand (mantissa) bits for float datatypes. // For non-float datatypes, results in a LOG(FATAL). int SignificandWidth(PrimitiveType type); // Returns the count of exponent bits for float datatypes. // For non-float datatypes, results in a LOG(FATAL). int ExponentWidth(PrimitiveType type); // Returns the exponent of the smallest number which cannot be represented. // For non-float datatypes, results in a LOG(FATAL). int OverflowExponent(PrimitiveType type); // Returns the XLA primitive type (eg, F32) corresponding to the given // template parameter native type (eg, float). template <typename NativeT> PrimitiveType NativeToPrimitiveType() { // Make the expression depend on the template parameter NativeT so // that this compile-time error only appears if this function is // instantiated with some concrete type that is not specialized // below. static_assert(!std::is_same<NativeT, NativeT>::value, "Cannot map native type to primitive type."); return PRIMITIVE_TYPE_INVALID; } // Declarations of specializations for each native type which correspond to a // XLA primitive type. As an optimization, these are declared inline in the // header. template <> inline PrimitiveType NativeToPrimitiveType<bool>() { return PRED; } // Unsigned integer template <> inline PrimitiveType NativeToPrimitiveType<uint8_t>() { return U8; } template <> inline PrimitiveType NativeToPrimitiveType<uint16_t>() { return U16; } template <> inline PrimitiveType NativeToPrimitiveType<uint32_t>() { return U32; } template <> inline PrimitiveType NativeToPrimitiveType<uint64_t>() { return U64; } // Signed integer template <> inline PrimitiveType NativeToPrimitiveType<int8_t>() { return S8; } template <> inline PrimitiveType NativeToPrimitiveType<int16_t>() { return S16; } template <> inline PrimitiveType NativeToPrimitiveType<int32_t>() { return S32; } template <> inline PrimitiveType NativeToPrimitiveType<int64_t>() { return S64; } // Floating point template <> inline PrimitiveType NativeToPrimitiveType<float>() { return F32; } template <> inline PrimitiveType NativeToPrimitiveType<double>() { return F64; } template <> inline PrimitiveType NativeToPrimitiveType<half>() { return F16; } template <> inline PrimitiveType NativeToPrimitiveType<bfloat16>() { return BF16; } // Complex template <> inline PrimitiveType NativeToPrimitiveType<complex64>() { return C64; } template <> inline PrimitiveType NativeToPrimitiveType<complex128>() { return C128; } bool IsFloatingPointType(PrimitiveType type); bool IsComplexType(PrimitiveType type); bool IsSignedIntegralType(PrimitiveType type); bool IsUnsignedIntegralType(PrimitiveType type); bool IsIntegralType(PrimitiveType type); // Returns true if values of the given primitive type are held in array shapes. bool IsArrayType(PrimitiveType primitive_type); // Returns the number of bits in the representation for a given type. int BitWidth(PrimitiveType type); // Returns the number of bytes in the representation for a given type. int ByteWidth(PrimitiveType type); PrimitiveType UnsignedIntegralTypeForBitWidth(int64_t src_bitwidth); PrimitiveType SignedIntegralTypeForBitWidth(int64_t src_bitwidth); // Returns the real, imag component type underlying the given complex type. // LOG(FATAL)'s if complex_type is not complex. PrimitiveType ComplexComponentType(PrimitiveType complex_type); // Returns the higher-precision element type if a and b are both floating // point types; otherwise, checks that they have the same element type // and returns it. inline PrimitiveType HigherPrecisionType(PrimitiveType a, PrimitiveType b) { // Returns a tuple where the elements are lexicographically ordered in terms // of importance. auto type_properties = [](PrimitiveType type) { auto component_type = IsComplexType(type) ? ComplexComponentType(type) : type; return std::make_tuple( // Prefer complex types over non-complex types. IsComplexType(type), // Prefer floating point types with more range over other // floating-point types or non-floating point types. IsFloatingPointType(component_type) ? OverflowExponent(component_type) : -1, // Prefer floating point types with more precision over less precise // types. IsFloatingPointType(component_type) ? SignificandWidth(component_type) : -1, // Prefer wider types over narrower types. BitWidth(component_type), // Prefer signed integer types over unsigned integer types. IsSignedIntegralType(component_type)); }; auto a_properties = type_properties(a); auto b_properties = type_properties(b); if (a_properties > b_properties) { return a; } if (b_properties > a_properties) { return b; } CHECK_EQ(a, b); return a; } // Returns true if a convert from from_type to to_type loses no precision. inline bool CastPreservesValues(PrimitiveType from_type, PrimitiveType to_type) { // * -> * if (from_type == to_type) { return true; } // PRED -> * if (from_type == PRED) { return true; } // ~PRED -> PRED is not safe because it drops almost all numbers. if (to_type == PRED) { return false; } // * -> C is safe if the components of * and C can be safely converted. if (primitive_util::IsComplexType(to_type)) { auto from_component_type = primitive_util::IsComplexType(from_type) ? primitive_util::ComplexComponentType(from_type) : from_type; auto to_component_type = primitive_util::ComplexComponentType(to_type); return CastPreservesValues(from_component_type, to_component_type); } // ~C -> C is not safe because it drops imaginary components. if (primitive_util::IsComplexType(from_type)) { return false; } // F -> F is safe if the exponent and significand are preserved. if (primitive_util::IsFloatingPointType(from_type) && primitive_util::IsFloatingPointType(to_type)) { return primitive_util::SignificandWidth(from_type) <= primitive_util::SignificandWidth(to_type) && primitive_util::ExponentWidth(from_type) <= primitive_util::ExponentWidth(to_type) && primitive_util::OverflowExponent(from_type) <= primitive_util::OverflowExponent(to_type); } // F -> I is not safe because it drops fractional numbers. if (!primitive_util::IsIntegralType(from_type)) { return false; } // An n-bit unsigned integer takes on values from [0, 2^n - 1]. // An n-bit signed integer takes on values from [-2^(n-1), 2^(n-1) - 1]. // from_bits/to_bits considers the number of non-sign bits. const int from_bits = primitive_util::IsSignedIntegralType(from_type) ? primitive_util::BitWidth(from_type) - 1 : primitive_util::BitWidth(from_type); const int to_bits = primitive_util::IsSignedIntegralType(to_type) ? primitive_util::BitWidth(to_type) - 1 : primitive_util::BitWidth(to_type); // I -> F is safe if the integer can be represented exactly. if (primitive_util::IsFloatingPointType(to_type)) { // In both cases, we need to handle an exponent of n-1. // However, the significand needed to represent signed two's complement // numbers is smaller by one bit because it will only have a non-zero // trailing significand field when the exponent is smaller than n-1. return from_bits <= primitive_util::SignificandWidth(to_type) && primitive_util::BitWidth(from_type) - 1 < primitive_util::OverflowExponent(to_type); } // S -> U is not safe because it drops negative numbers. if (primitive_util::IsSignedIntegralType(from_type) && primitive_util::IsUnsignedIntegralType(to_type)) { return false; } // I -> I is safe if the integer can be represented exactly; we've already // ensured that signed to unsigned conversions won't happen here. CHECK(primitive_util::IsIntegralType(to_type)); return from_bits <= to_bits; } // Returns the native type (eg, float) corresponding to the given template // parameter XLA primitive type (eg, F32). template <PrimitiveType> struct PrimitiveTypeToNative; // Declarations of specializations for each native type which correspond to a // XLA primitive type. template <> struct PrimitiveTypeToNative<PRED> { using type = bool; }; // Unsigned integer template <> struct PrimitiveTypeToNative<U8> { using type = uint8_t; }; template <> struct PrimitiveTypeToNative<U16> { using type = uint16_t; }; template <> struct PrimitiveTypeToNative<U32> { using type = uint32_t; }; template <> struct PrimitiveTypeToNative<U64> { using type = uint64_t; }; // Signed integer template <> struct PrimitiveTypeToNative<S8> { using type = int8_t; }; template <> struct PrimitiveTypeToNative<S16> { using type = int16_t; }; template <> struct PrimitiveTypeToNative<S32> { using type = int32_t; }; template <> struct PrimitiveTypeToNative<S64> { using type = int64_t; }; // Floating point template <> struct PrimitiveTypeToNative<F32> { using type = float; }; template <> struct PrimitiveTypeToNative<F64> { using type = double; }; template <> struct PrimitiveTypeToNative<F16> { using type = half; }; template <> struct PrimitiveTypeToNative<BF16> { using type = bfloat16; }; // Complex template <> struct PrimitiveTypeToNative<C64> { using type = complex64; }; template <> struct PrimitiveTypeToNative<C128> { using type = complex128; }; // Returns the lower-case name of the given primitive type. const std::string& LowercasePrimitiveTypeName(PrimitiveType s); // Returns the PrimitiveType matching the given name. The given name is expected // to be lower-case. StatusOr<PrimitiveType> StringToPrimitiveType(absl::string_view name); // Returns true if the given name is a primitive type string (lower-case). bool IsPrimitiveTypeName(absl::string_view name); } // namespace primitive_util } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_PRIMITIVE_UTIL_H_
valavanisleonidas/Machine_Learning_Toolkit
Utils/Tuning/NeuralNetworks_Tuning.py
import sklearn.cross_validation as cross_val import sys sys.path.append('../../MachineLearning/DeepLearning/Keras') from Keras_test import CNN, MLP def neural_tuning(features_train, labels_train, features_test, labels_test, outputClasses=None, modelType="CNN", batch_size=(10, 500, 50), # CNN nb_epoch=(10, 100, 20), nb_filters=(10, 50, 5), nb_pool=(2, 10, 1), nb_conv=(2, 10, 1),border_mode=['same' , 'valid'], # MLP activation=['relu', 'tanh'], num_input=(100, 1024, 100), depths=(1, 10, 1), optimizers=['adam', 'sgd', 'rms', 'adadelta', 'adagrad'], performCrossVal=False, K_Fold=10): bestAccuracy = -1 bestBatchSize = [] bestEpochs = [] bestNumInputs = [] bestDepth = [] bestActivation = [] bestOptimizer = [] if modelType == "CNN": bestNbFilters = [] bestNbPool = [] bestNbConv = [] bestBorderMode=[] for batch in range(batch_size[0], batch_size[1], batch_size[2]): for epochs in range(nb_epoch[0], nb_epoch[1], nb_epoch[2]): for filter in range(nb_filters[0], nb_filters[1], nb_filters[2]): for poolSize in range(nb_pool[0], nb_pool[1], nb_pool[2]): for conv in range(nb_conv[0], nb_conv[1], nb_conv[2]): for activ in activation: for opt in optimizers: for inputs in range(num_input[0], num_input[1], num_input[2]): for depth in range(depths[0], depths[1], depths[2]): for border in border_mode: print 'current batch :', str(batch) print 'current epochs :', str(epochs) print 'current filter :', str(filter) print 'current poolSize :', str(poolSize) print 'current conv :', str(conv) print 'current activ :', str(activ) print 'current optimizer :', str(opt) print 'current inputs :', str(inputs) print 'current depth :', str(depth) print 'current border :', str(border) if performCrossVal: assert outputClasses != None, "Give Number of classes" accuracy = neural_crossValidation(features_train=features_train, labels_train=labels_train, batch_size=batch, nb_epoch=epochs, nb_filters=filter, nb_pool=poolSize, nb_conv=conv, outputClasses=outputClasses, mode="CNN", K_Fold=K_Fold) else: model = CNN().train(features=features_train, labels=labels_train, batch_size=batch, nb_epoch=epochs, nb_filters=filter, nb_conv=conv, nb_pool=poolSize, activation=activ, num_inputs=inputs, depth=depth, optimizer=opt, outputClasses=outputClasses, learning_curves_OR_Cross_Val=True, data_augmentation=True) accuracy = CNN().predict(features=features_test, labels=labels_test, model=model) print 'accuracy :', str(accuracy) if accuracy >= bestAccuracy: bestAccuracy = accuracy bestBatchSize = batch bestEpochs = epochs bestNbFilters = filter bestNbPool = poolSize bestNbConv = conv bestBorderMode=border bestActivation = activ bestNumInputs = inputs bestDepth = depth bestOptimizer = opt print '\nBest parameters so far:' print 'best acc:', bestAccuracy print 'best batch size:', bestBatchSize print 'best epochs:', bestEpochs print 'best filter:', bestNbFilters print 'best pool size:', bestNbPool print 'best conv:', bestNbConv print 'best activ :', bestActivation print 'best optimizer :', bestOptimizer print 'best inputs :', bestNumInputs print 'best depth :', bestDepth print 'best border :', bestBorderMode return [bestAccuracy, bestBatchSize, bestEpochs, bestNbFilters, bestNbPool, bestNbConv,bestBorderMode,bestActivation,bestNumInputs,bestDepth,bestOptimizer] if modelType == "MLP": for batch in range(batch_size[0], batch_size[1], batch_size[2]): for epochs in range(nb_epoch[0], nb_epoch[1], nb_epoch[2]): for activ in activation: for opt in optimizers: for inputs in range(num_input[0], num_input[1], num_input[2]): for depth in range(depths[0], depths[1], depths[2]): print 'current batch :', str(batch) print 'current epochs :', str(epochs) print 'current activ :', str(activ) print 'current optimizer :', str(opt) print 'current inputs :', str(inputs) print 'current depth :', str(depth) if performCrossVal: assert outputClasses != None, "Give Number of classes" accuracy = neural_crossValidation(features_train=features_train, labels_train=labels_train, batch_size=batch, nb_epoch=epochs, activation=activ, num_input=inputs, depth=depth, outputClasses=outputClasses, optimizer=opt, mode="MLP", K_Fold=K_Fold) else: model = MLP().train(features=features_train, labels=labels_train, nb_epoch=epochs, activation=activ, num_input=inputs, depth=depth, optimizer=opt, batch_size=batch, outputClasses=outputClasses, learning_curves_OR_Cross_Val=True) accuracy = MLP().predict(features=features_test, labels=labels_test, model=model) print 'accuracy :', str(accuracy) if accuracy >= bestAccuracy: bestAccuracy = accuracy bestBatchSize = batch bestEpochs = epochs bestActivation = activ bestNumInputs = inputs bestDepth = depth bestOptimizer = opt print 'Best parameters so far:' print 'best acc:', bestAccuracy print 'best batch size:', bestBatchSize print 'best epochs:', bestEpochs print 'best activation:', bestActivation print 'best optimizer :', bestOptimizer print 'bestNumInputs:', bestNumInputs print 'bestDepth:', bestDepth return [bestAccuracy, bestBatchSize, bestEpochs, bestActivation, bestOptimizer, bestNumInputs, bestDepth] def neural_crossValidation(features_train, labels_train, mode, batch_size=100, nb_filters=32, nb_epoch=100, nb_pool=2, nb_conv=2, optimizer='sgd', activation='relu', num_input=1024, depth=1,border_mode='same', outputClasses=None, K_Fold=10): folds = cross_val.KFold(n=len(labels_train), n_folds=K_Fold, shuffle=True) print len(folds) bestAccuracy = [] i = 0 for train_index, test_index in folds: i +=1 print 'Cross Validation iteration : ' , i if mode == "CNN": model = CNN().train(features=features_train[train_index], labels=labels_train[train_index], nb_epoch=nb_epoch, batch_size=batch_size, nb_filters=nb_filters, nb_pool=nb_pool, nb_conv=nb_conv, num_inputs=num_input, depth=depth, border_mode=border_mode, activation=activation, optimizer=optimizer, data_augmentation=True, outputClasses=outputClasses, learning_curves_OR_Cross_Val=True) accuracy = CNN().predict(features=features_train[test_index], labels=labels_train[test_index], model=model, outputClasses=outputClasses,learning_curves_OR_Cross_Val=True) elif mode == "MLP": model = MLP().train(features=features_train[train_index], labels=labels_train[train_index], outputClasses=outputClasses, nb_epoch=nb_epoch, batch_size=batch_size, activation=activation, num_input=num_input, optimizer=optimizer, depth=depth, learning_curves_OR_Cross_Val=True) accuracy = MLP().predict(features=features_train[test_index], labels=labels_train[test_index], model=model,outputClasses=outputClasses, learning_curves_OR_Cross_Val=True) bestAccuracy.append(accuracy) # return mean of accuracies return float(sum(bestAccuracy)) / len(bestAccuracy) if len(bestAccuracy) > 0 else float('nan')
pyranja/pants
src/python/pants/binaries/binary_tool.py
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import threading from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union, cast from pants.binaries.binary_util import ( BinaryRequest, BinaryToolUrlGenerator, BinaryUtil, HostPlatform, ) from pants.engine.fs import Digest, PathGlobs, PathGlobsAndRoot, Snapshot, UrlToFetch from pants.engine.platform import Platform, PlatformConstraint from pants.engine.rules import RootRule, rule from pants.engine.selectors import Get from pants.fs.archive import create_archiver from pants.subsystem.subsystem import Subsystem from pants.util.enums import match from pants.util.memo import memoized_method, memoized_property from pants.util.meta import frozen_after_init from pants.util.osutil import get_closest_mac_host_platform_pair logger = logging.getLogger(__name__) @dataclass(frozen=True) class ToolVersion: version: str @dataclass(frozen=True) class ToolForPlatform: version: ToolVersion digest: Digest def into_tuple(self) -> Tuple[str, str, int]: return (self.version.version, self.digest.fingerprint, self.digest.serialized_bytes_length) @rule def translate_host_platform( platform_constraint: PlatformConstraint, binary_util: BinaryUtil, ) -> HostPlatform: # This method attempts to provide a uname function to BinaryUtil.host_platform() so that the # download urls can be calculated. For platforms that are different than the current host, we try # to "spoof" the most appropriate value. if Platform.current == Platform.darwin: darwin_uname: Any = os.uname linux_uname: Any = lambda: ("linux", None, None, None, "x86_64") else: assert Platform.current == Platform.linux darwin_uname = lambda: ( "darwin", None, get_closest_mac_host_platform_pair(), None, "x86_64", ) linux_uname = os.uname return cast( HostPlatform, match( platform_constraint, { PlatformConstraint.none: lambda: HostPlatform.empty, PlatformConstraint.darwin: lambda: binary_util.host_platform(uname=darwin_uname()), PlatformConstraint.linux: lambda: binary_util.host_platform(uname=linux_uname()), }, )(), ) # TODO: Add integration tests for this file. class BinaryToolBase(Subsystem): """Base class for subsytems that configure binary tools. Subclasses can be further subclassed, manually, e.g., to add any extra options. :API: public """ # Subclasses must set these to appropriate values for the tool they define. # They must also set options_scope appropriately. platform_dependent: Optional[bool] = None archive_type: Optional[str] = None # See pants.fs.archive.archive for valid string values. default_version: Optional[str] = None default_versions_and_digests: Dict[PlatformConstraint, ToolForPlatform] = {} # Subclasses may set this to the tool name as understood by BinaryUtil. # If unset, it defaults to the value of options_scope. name: Optional[str] = None # Subclasses may set this to a suffix (e.g., '.pex') to add to the computed remote path. # Note that setting archive_type will add an appropriate archive suffix after this suffix. suffix = "" # Subclasses may set these to effect migration from an old --version option to this one. # TODO(benjy): Remove these after migration to the mixin is complete. replaces_scope: Optional[str] = None replaces_name: Optional[str] = None # Subclasses may set this to provide extra register() kwargs for the --version option. extra_version_option_kwargs = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._snapshot_lock = threading.Lock() @classmethod def subsystem_dependencies(cls): return super().subsystem_dependencies() + (BinaryUtil.Factory,) @memoized_method def _get_archiver(self): if not self.archive_type: return None return create_archiver(self.archive_type) def get_external_url_generator(self): """Override and return an instance of BinaryToolUrlGenerator to download from those urls. If this method returns None, urls to download the tool will be constructed from --binaries-baseurls. Otherwise, generate_urls() will be invoked on the result with the requested version and host platform. If the bootstrap option --allow-external-binary-tool-downloads is False, the result of this method will be ignored. Implementations of BinaryTool must be aware of differences (e.g., in archive structure) between the external and internal versions of the downloaded tool, if any. See the :class:`LLVM` subsystem for an example of usage. """ return None @classmethod def register_options(cls, register): super().register_options(register) version_registration_kwargs = { "type": str, "default": cls.default_version, } if cls.extra_version_option_kwargs: version_registration_kwargs.update(cls.extra_version_option_kwargs) version_registration_kwargs["help"] = version_registration_kwargs.get( "help" ) or "Version of the {} {} to use".format( cls._get_name(), "binary" if cls.platform_dependent else "script" ) # The default for fingerprint in register() is False, but we want to default to True. if "fingerprint" not in version_registration_kwargs: version_registration_kwargs["fingerprint"] = True register("--version", **version_registration_kwargs) register( "--version-digest-mapping", type=dict, default={ # "Serialize" the default value dict into "basic" types that can be easily specified # in pants.toml. platform_constraint.value: tool.into_tuple() for platform_constraint, tool in cls.default_versions_and_digests.items() }, fingerprint=True, help="A dict mapping <platform constraint> -> (<version>, <fingerprint>, <size_bytes>)." f'A "platform constraint" is any of {[c.value for c in PlatformConstraint]}, and ' "is the platform to fetch the tool for. A platform-independent tool should " f"use {PlatformConstraint.none.value}, while a platform-dependent tool should specify " 'all environments it needs to be used for. The "fingerprint" and "size_bytes" ' "arguments are the result printed when running `sha256sum` and `wc -c` on " "the downloaded file, respectively.", ) @memoized_method def select(self, context=None): """Returns the path to the specified binary tool. If replaces_scope and replaces_name are defined, then the caller must pass in a context, otherwise no context should be passed. # TODO: Once we're migrated, get rid of the context arg. :API: public """ return self._select_for_version(self.version(context)) @memoized_method def version(self, context=None): """Returns the version of the specified binary tool. If replaces_scope and replaces_name are defined, then the caller must pass in a context, otherwise no context should be passed. # TODO: Once we're migrated, get rid of the context arg. :API: public """ if self.replaces_scope and self.replaces_name: if context: # If the old option is provided explicitly, let it take precedence. old_opts = context.options.for_scope(self.replaces_scope) if old_opts.get(self.replaces_name) and not old_opts.is_default(self.replaces_name): return old_opts.get(self.replaces_name) else: logger.warning( "Cannot resolve version of {} from deprecated option {} in scope {} without a " "context!".format(self._get_name(), self.replaces_name, self.replaces_scope) ) return self.get_options().version @memoized_property def _binary_util(self): return BinaryUtil.Factory.create() @classmethod def _get_name(cls): return cls.name or cls.options_scope @classmethod def get_support_dir(cls): return "bin/{}".format(cls._get_name()) @classmethod def _name_to_fetch(cls): return "{}{}".format(cls._get_name(), cls.suffix) def make_binary_request(self, version): return BinaryRequest( supportdir=self.get_support_dir(), version=version, name=self._name_to_fetch(), platform_dependent=self.platform_dependent, external_url_generator=self.get_external_url_generator(), archiver=self._get_archiver(), ) def _select_for_version(self, version): binary_request = self.make_binary_request(version) return self._binary_util.select(binary_request) @memoized_method def _hackily_snapshot_exclusive(self, context): bootstrapdir = self.get_options().pants_bootstrapdir relpath = os.path.relpath(self.select(context), bootstrapdir) snapshot = context._scheduler.capture_snapshots( (PathGlobsAndRoot(PathGlobs((relpath,)), bootstrapdir,),) )[0] return (relpath, snapshot) def hackily_snapshot(self, context): """Returns a Snapshot of this tool after downloading it. TODO: See https://github.com/pantsbuild/pants/issues/7790, which would make this unnecessary due to the engine's memoization and caching. """ # We call a memoized method under a lock in order to avoid doing a bunch of redundant # fetching and snapshotting. with self._snapshot_lock: return self._hackily_snapshot_exclusive(context) class NativeTool(BinaryToolBase): """A base class for native-code tools. :API: public """ platform_dependent = True class Script(BinaryToolBase): """A base class for platform-independent scripts. :API: public """ platform_dependent = False @frozen_after_init @dataclass(unsafe_hash=True) class VersionDigestMapping: """Parse the --version-digest-mapping option back into a dictionary.""" version_digest_mapping: Tuple[Tuple[str, Tuple[str, str, int]], ...] def __init__(self, version_digest_mapping: Dict[str, List[Union[str, int]]]) -> None: self.version_digest_mapping = tuple( (platform_constraint, tuple(data)) # type: ignore[misc] for platform_constraint, data in version_digest_mapping.items() ) @memoized_property def _deserialized_mapping(self,) -> Dict[PlatformConstraint, ToolForPlatform]: deserialized: Dict[PlatformConstraint, ToolForPlatform] = {} for platform_constraint, (version, fingerprint, size_bytes) in self.version_digest_mapping: deserialized[PlatformConstraint(platform_constraint)] = ToolForPlatform( version=ToolVersion(version), digest=Digest(fingerprint, size_bytes), ) return deserialized def get(self, platform_constraint: PlatformConstraint) -> ToolForPlatform: return self._deserialized_mapping[platform_constraint] @dataclass(frozen=True) class BinaryToolUrlSet: tool_for_platform: ToolForPlatform host_platform: HostPlatform url_generator: BinaryToolUrlGenerator def get_urls(self) -> List[str]: return self.url_generator.generate_urls( version=self.tool_for_platform.version.version, host_platform=self.host_platform if self.host_platform != HostPlatform.empty else None, ) @frozen_after_init @dataclass(unsafe_hash=True) class BinaryToolFetchRequest: tool: BinaryToolBase platform_constraint: PlatformConstraint def __init__( self, tool: BinaryToolBase, platform_constraint: Optional[PlatformConstraint] = None, ) -> None: self.tool = tool if platform_constraint is None: if tool.platform_dependent: platform_constraint = PlatformConstraint.local_platform else: platform_constraint = PlatformConstraint.none self.platform_constraint = platform_constraint @rule async def get_binary_tool_urls( req: BinaryToolFetchRequest, binary_util: BinaryUtil, ) -> BinaryToolUrlSet: tool = req.tool platform_constraint = req.platform_constraint mapping = VersionDigestMapping(tool.get_options().version_digest_mapping) tool_for_platform = mapping.get(platform_constraint) version = tool_for_platform.version.version url_generator = binary_util.get_url_generator(tool.make_binary_request(version)) host_platform = await Get[HostPlatform](PlatformConstraint, platform_constraint) return BinaryToolUrlSet( tool_for_platform=tool_for_platform, host_platform=host_platform, url_generator=url_generator, ) @rule async def fetch_binary_tool(req: BinaryToolFetchRequest, url_set: BinaryToolUrlSet) -> Snapshot: digest = url_set.tool_for_platform.digest urls = url_set.get_urls() if not urls: raise ValueError( f"binary tool url generator {url_set.url_generator} produced an empty list of " f"urls for the request {req}" ) # TODO: allow fetching a UrlToFetch with failure! Consider FallibleUrlToFetch analog to # FallibleProcessResult! url_to_fetch = urls[0] return await Get[Snapshot](UrlToFetch(url_to_fetch, digest)) def rules(): return [ RootRule(PlatformConstraint), translate_host_platform, get_binary_tool_urls, fetch_binary_tool, RootRule(BinaryToolFetchRequest), ]
lechium/tvOS144Headers
usr/libexec/geod/GEOPlaceDataServer.h
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <GeoServices/GEOServer.h> @class NSMutableDictionary; @interface GEOPlaceDataServer : GEOServer { struct os_unfair_lock_s _uuidToRequestLock; // 16 = 0x10 NSMutableDictionary *_uuidToRequest; // 24 = 0x18 } + (_Bool)shouldStartImmediately; // IMP=0x0000000100011bc0 + (id)identifier; // IMP=0x0000000100011bb4 - (void).cxx_destruct; // IMP=0x0000000100006294 - (void)clearCacheWithMessage:(id)arg1; // IMP=0x000000010000624c - (void)shrinkBySizeSyncWithMessage:(id)arg1; // IMP=0x00000001000060fc - (void)shrinkBySizeWithMessage:(id)arg1; // IMP=0x0000000100005f34 - (void)calculateFreeableSpaceSyncWithMessage:(id)arg1; // IMP=0x0000000100005e40 - (void)calculateFreeableSpaceWithMessage:(id)arg1; // IMP=0x0000000100005cdc - (void)cancelPlaceDataRequestWithMessage:(id)arg1; // IMP=0x0000000100005bc4 - (void)performPlaceDataRequestWithMessage:(id)arg1; // IMP=0x00000001000054bc - (void)preservePlaceDataWithMessage:(id)arg1; // IMP=0x0000000100005240 - (void)fetchAllCacheEntriesWithMessage:(id)arg1; // IMP=0x0000000100005010 - (void)requestPhoneNumbersWithMessage:(id)arg1; // IMP=0x0000000100004a3c - (void)requestComponentsWithMessage:(id)arg1; // IMP=0x0000000100004490 - (id)_generateReplyFor:(id)arg1 userInfo:(id)arg2 error:(id)arg3; // IMP=0x000000010000437c - (void)requestMUIDsWithMessage:(id)arg1; // IMP=0x0000000100003dc0 - (id)init; // IMP=0x0000000100003d2c - (_Bool)handleIncomingMessage:(id)arg1 withObject:(id)arg2 fromPeer:(id)arg3; // IMP=0x0000000100011bc8 @end
YufeizhangRay/springboot-practice
springboot14starter/zyf-spring-boot-starter-autoconfigurer/src/main/java/cn/zyf/springboot/starter/HelloServiceAutoConfiguration.java
package cn.zyf.springboot.starter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnWebApplication//只有在web应用中引入自定义的启动器的时候,这个自动配置类才会生效 @EnableConfigurationProperties(HelloProperties.class)//这个注解可以将此配置类和HelloProperties(又和全局文件有关联)建立关联 public class HelloServiceAutoConfiguration { @Autowired private HelloProperties helloProperties; @Bean public HelloService helloService(){ HelloService helloService = new HelloService(); helloService.setHelloProperties(helloProperties);//将HelloProperties与HelloService建立关联 return helloService; } }
Pinafore/Karl-flashcards-web-app
backend/app/alembic/versions/b7b8acac9d4f_history_fact_id_should_be_optional.py
"""history fact.id should be optional Revision ID: b7b8acac9d4f Revises: <PASSWORD> Create Date: 2020-06-17 19:31:18.958679 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b7b8acac9d4f' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('history', 'fact_id', existing_type=sa.INTEGER(), nullable=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('history', 'fact_id', existing_type=sa.INTEGER(), nullable=False) # ### end Alembic commands ###
aaronwalsman/ltron
ltron/__init__.py
try: from gym.envs.registration import register gym_available = True except ModuleNotFoundError: gym_available = False # do this once we finalize the envs for the first paper ''' register( id='brick-graph-8-v0', entry_point='brick_gym.envs:TrainRandomStackGraphEnvVec8' ) '''
campusappcn/AndRouter
router/src/debug/java/cn/campusapp/router/DebugActivity.java
package cn.campusapp.router; import android.app.Activity; import android.os.Bundle; public class DebugActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_debug); } }
hpham17/esential
features/step_definitions/web_steps.rb
<reponame>hpham17/esential # TL;DR: YOU SHOULD DELETE THIS FILE # # This file was generated by Cucumber-Rails and is only here to get you a head start # These step definitions are thin wrappers around the Capybara/Webrat API that lets you # visit pages, interact with widgets and make assertions about page content. # # If you use these step definitions as basis for your features you will quickly end up # with features that are: # # * Hard to maintain # * Verbose to read # # A much better approach is to write your own higher level step definitions, following # the advice in the following blog posts: # # * http://benmabey.com/2008/05/19/imperative-vs-declarative-scenarios-in-user-stories.html # * http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/ # * http://elabs.se/blog/15-you-re-cuking-it-wrong # require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors")) module WithinHelpers def with_scope(locator) locator ? within(*selector_for(locator)) { yield } : yield end end World(WithinHelpers) Given /^(?:|I )am on (.+)$/ do |page_name| visit path_to(page_name) end # Then /^(?:|I )should be on "([^"]*)"$/ do |page_name| # current_path = URI.parse(current_url).path # if current_path.respond_to? :should # current_path.should == path_to(page_name) # else # assert_equal path_to(page_name), current_path # end # end When /^(?:|I )press "([^"]*)"$/ do |button| click_button(button) end When /^(?:|I )follow "([^"]*)"$/ do |link| click_link(link) end Then /^(?:|I )should see "([^"]*)"$/ do |text| if page.respond_to? :expect expect.to have_content(text) end end Then /^(?:|I )should be on (.+)$/ do |page_name| current_path = URI.parse(current_url).path if current_path.respond_to? :should current_path.should == path_to(page_name) else assert_equal path_to(page_name), current_path end end
bestseason/ZHData
app/src/main/java/edu/zhdata/android/zhapp/tools/HtmlUtil.java
package edu.zhdata.android.zhapp.tools; /** * Created by pink2 on 2017/3/22. */ import java.util.regex.Matcher; import java.util.regex.Pattern; /** * html处理工具类 * @author huweijun * @date 2016年7月13日 下午7:25:09 */ public class HtmlUtil { /** * 替换指定标签的属性和值 * @param str 需要处理的字符串 * @param tag 标签名称 * @param tagAttrib 要替换的标签属性值 * @param startTag 新标签开始标记 * @param endTag 新标签结束标记 * @return * @author huweijun * @date 2016年7月13日 下午7:15:32 */ public static String replaceHtmlTag(String str, String tag, String tagAttrib, String startTag, String endTag) { String regxpForTag = "<\\s*" + tag + "\\s+([^>]*)\\s*" ; String regxpForTagAttrib = tagAttrib + "=\\s*\"([^\"]+)\"" ; Pattern patternForTag = Pattern.compile (regxpForTag,Pattern. CASE_INSENSITIVE ); Pattern patternForAttrib = Pattern.compile (regxpForTagAttrib,Pattern. CASE_INSENSITIVE ); Matcher matcherForTag = patternForTag.matcher(str); StringBuffer sb = new StringBuffer(); boolean result = matcherForTag.find(); while (result) { StringBuffer sbreplace = new StringBuffer( "<"+tag+" "); Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1)); if (matcherForAttrib.find()) { String attributeStr = matcherForAttrib.group(1); matcherForAttrib.appendReplacement(sbreplace, startTag + attributeStr + endTag); } matcherForAttrib.appendTail(sbreplace); matcherForTag.appendReplacement(sb, sbreplace.toString()); result = matcherForTag.find(); } matcherForTag.appendTail(sb); return sb.toString(); } public static String replaceUploadHtmlTag(String str) { String temp=""; String regex = "<img src=\"http://.*/images"; Pattern pat = Pattern.compile(regex); Matcher matcher = pat.matcher(str); while (matcher.find()) { temp = str.substring(matcher.start(),matcher.end()); str = str.replaceAll(temp, "<img src=\"/images"); } return str; } }
ste93cry/idea-php-symfony2-plugin
src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/doctrine/querybuilder/QueryBuilderCompletionContributorTest.java
<filename>src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/doctrine/querybuilder/QueryBuilderCompletionContributorTest.java package fr.adrienbrault.idea.symfony2plugin.tests.doctrine.querybuilder; import fr.adrienbrault.idea.symfony2plugin.doctrine.querybuilder.QueryBuilderCompletionContributor; import fr.adrienbrault.idea.symfony2plugin.tests.SymfonyLightCodeInsightFixtureTestCase; /** * @see QueryBuilderCompletionContributor * @author <NAME> <<EMAIL>> */ public class QueryBuilderCompletionContributorTest extends SymfonyLightCodeInsightFixtureTestCase { public void setUp() throws Exception { super.setUp(); myFixture.copyFileToProject("doctrine.orm.yml"); myFixture.copyFileToProject("QueryBuilderCompletionContributor.php"); } public String getTestDataPath() { return "src/test/java/fr/adrienbrault/idea/symfony2plugin/tests/doctrine/querybuilder/fixtures"; } public void testServiceEntityRepositoryConstructorModelContextOnQueryBuilderJoin() { assertCompletionContains("test.php", "<?php\n" + "\n" + "use Doctrine\\Bundle\\DoctrineBundle\\Repository\\ServiceEntityRepository;\n" + "\n" + "class Repository extends ServiceEntityRepository\n" + "{\n" + " public function __construct(RegistryInterface $registry)\n" + " {\n" + " parent::__construct($registry, \\App\\Entity::class);\n" + " }\n" + "\n" + " public function foobar()\n" + " {\n" + " $qb = $this->createQueryBuilder('s');\n" + " $qb->andWhere('s.<caret>');\n" + " }\n" + "}", "s.name", "s.id"); } }
cyberatz/go-choria
broker/network/network_cluster.go
// Copyright (c) 2020-2021, <NAME> and the Choria Project contributors // // SPDX-License-Identifier: Apache-2.0 package network import ( "fmt" gnatsd "github.com/nats-io/nats-server/v2/server" ) func (s *Server) setupCluster() (err error) { peers, err := s.choria.NetworkBrokerPeers() if err != nil { return fmt.Errorf("could not determine network broker peers: %s", err) } if peers.Count() == 0 { s.log.Infof("Skipping clustering configuration without any peers") return nil } if s.config.Choria.NetworkClientTLSAnon && (s.config.Choria.NetworkPeerPort > 0 || peers.Count() > 0) { return fmt.Errorf("clustering is disabled when anonymous TLS is configured") } if peers.Count() > 0 && s.config.Choria.NetworkPeerPort == 0 { s.log.Info("Defaulting Choria Broker Peer port to 5222") s.config.Choria.NetworkPeerPort = 5222 } s.opts.Cluster.Host = s.config.Choria.NetworkListenAddress s.opts.Cluster.NoAdvertise = true s.opts.Cluster.Port = s.config.Choria.NetworkPeerPort s.opts.Cluster.Username = s.config.Choria.NetworkPeerUser s.opts.Cluster.Password = s.config.Choria.NetworkPeerPassword for _, p := range peers.Servers() { u, err := p.URL() if err != nil { return fmt.Errorf("could not parse Peer configuration: %s", err) } s.log.Infof("Adding %s as network peer", u.String()) s.opts.Routes = append(s.opts.Routes, u) } // Remove any host/ip that points to itself in Route newroutes, err := gnatsd.RemoveSelfReference(s.opts.Cluster.Port, s.opts.Routes) if err != nil { s.log.Warnf("could not remove own Self from cluster configuration: %s", err) } else { s.opts.Routes = newroutes } return }
jacadcaps/webkitty
Source/WebCore/platform/mediastream/mac/ScreenDisplayCapturerMac.h
/* * Copyright (C) 2017-2019 Apple 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: * 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 APPLE INC. ``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 APPLE INC. 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 #if ENABLE(MEDIA_STREAM) && PLATFORM(MAC) #include "DisplayCaptureSourceCocoa.h" #include "IOSurface.h" #include <CoreGraphics/CGDisplayConfiguration.h> #include <CoreGraphics/CGDisplayStream.h> #include <wtf/Lock.h> #include <wtf/OSObjectPtr.h> typedef struct __CVBuffer *CVPixelBufferRef; typedef struct opaqueCMSampleBuffer *CMSampleBufferRef; namespace WebCore { class ScreenDisplayCapturerMac final : public DisplayCaptureSourceCocoa::Capturer, public CanMakeWeakPtr<ScreenDisplayCapturerMac> { public: static Expected<UniqueRef<DisplayCaptureSourceCocoa::Capturer>, String> create(const String&); explicit ScreenDisplayCapturerMac(uint32_t); ~ScreenDisplayCapturerMac(); static Optional<CaptureDevice> screenCaptureDeviceWithPersistentID(const String&); static void screenCaptureDevices(Vector<CaptureDevice>&); private: static void displayReconfigurationCallBack(CGDirectDisplayID, CGDisplayChangeSummaryFlags, void*); // DisplayCaptureSourceCocoa::Capturer bool start(float frameRate) final; void stop() final; DisplayCaptureSourceCocoa::DisplayFrameType generateFrame() final; RealtimeMediaSourceSettings::DisplaySurfaceType surfaceType() const final { return RealtimeMediaSourceSettings::DisplaySurfaceType::Monitor; } void commitConfiguration(float frameRate) final; CaptureDevice::DeviceType deviceType() const final { return CaptureDevice::DeviceType::Screen; } #if !RELEASE_LOG_DISABLED const char* logClassName() const final { return "ScreenDisplayCapturerMac"; } #endif void displayWasReconfigured(CGDirectDisplayID, CGDisplayChangeSummaryFlags); bool createDisplayStream(float frameRate); bool startDisplayStream(float frameRate); class DisplaySurface { public: DisplaySurface() = default; explicit DisplaySurface(IOSurfaceRef surface) : m_surface(surface) { if (m_surface) IOSurfaceIncrementUseCount(m_surface.get()); } ~DisplaySurface() { if (m_surface) IOSurfaceDecrementUseCount(m_surface.get()); } DisplaySurface& operator=(IOSurfaceRef surface) { if (m_surface) IOSurfaceDecrementUseCount(m_surface.get()); if (surface) IOSurfaceIncrementUseCount(surface); m_surface = surface; return *this; } IOSurfaceRef ioSurface() const { return m_surface.get(); } private: RetainPtr<IOSurfaceRef> m_surface; }; void newFrame(CGDisplayStreamFrameStatus, DisplaySurface&&); DisplaySurface m_currentFrame; RetainPtr<CGDisplayStreamRef> m_displayStream; OSObjectPtr<dispatch_queue_t> m_captureQueue; uint32_t m_displayID { 0 }; bool m_isRunning { false }; bool m_observingDisplayChanges { false }; }; } // namespace WebCore #endif // ENABLE(MEDIA_STREAM) && PLATFORM(MAC)
ark100/multi-os-engine
moe/moe-core/moe.apple/moe.platform.ios/src/main/java/apple/coretelephony/c/CoreTelephony.java
/* Copyright 2014-2016 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. */ package apple.coretelephony.c; import org.moe.natj.c.CRuntime; import org.moe.natj.c.ann.CVariable; import org.moe.natj.general.NatJ; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.Runtime; import org.moe.natj.objc.map.ObjCStringMapper; @Generated @Library("CoreTelephony") @Runtime(CRuntime.class) public final class CoreTelephony { static { NatJ.register(); } @Generated private CoreTelephony() { } @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTCallStateDialing(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTCallStateIncoming(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTCallStateConnected(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTCallStateDisconnected(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTSubscriberTokenRefreshed(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyDidChangeNotification(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyGPRS(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyEdge(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyWCDMA(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyHSDPA(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyHSUPA(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyCDMA1x(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyCDMAEVDORev0(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyCDMAEVDORevA(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyCDMAEVDORevB(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyeHRPD(); @Generated @CVariable() @MappedReturn(ObjCStringMapper.class) public static native String CTRadioAccessTechnologyLTE(); }
candidomorantepelaez/kanbion-back
src/main/java/com/kannoakuma/kanbionback/accounts/api/proxies/impl/AccountProxyImpl.java
<filename>src/main/java/com/kannoakuma/kanbionback/accounts/api/proxies/impl/AccountProxyImpl.java package com.kannoakuma.kanbionback.accounts.api.proxies.impl; import com.kannoakuma.kanbionback.accounts.api.proxies.AccountProxy; import com.kannoakuma.kanbionback.accounts.api.dtos.CreateAccountRequestDto; import com.kannoakuma.kanbionback.accounts.api.dtos.AccountDto; import com.kannoakuma.kanbionback.accounts.api.mappers.CreateAccountRequestMapper; import com.kannoakuma.kanbionback.accounts.api.mappers.AccountMapper; import com.kannoakuma.kanbionback.accounts.model.services.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AccountProxyImpl implements AccountProxy { @Autowired AccountService accountService; @Autowired AccountMapper accountMapper; @Autowired CreateAccountRequestMapper accountCreatedMapper; @Override public AccountDto create(CreateAccountRequestDto accountCreatedDto) { return this.accountMapper.accountToAccountDto(this.accountService .create(this.accountCreatedMapper .createAccountRequestDtoToCreateAccountRequest( accountCreatedDto))); } }
qeebr/none
none-lwjgl/src/test/java/none/lwjgl/scenes/renderer/TextScene.java
<filename>none-lwjgl/src/test/java/none/lwjgl/scenes/renderer/TextScene.java<gh_stars>0 package none.lwjgl.scenes.renderer; import none.engine.Game; import none.engine.component.Transform; import none.engine.component.common.uuid.UUIDFactory; import none.engine.component.renderer.Renderable; import none.engine.component.renderer.camera.Camera; import none.engine.component.renderer.camera.OrthographicCamera; import none.engine.component.renderer.primitives.Text; import org.joml.Vector3d; import java.util.List; /** * Displays a Simple Text. */ public class TextScene extends BaseScene { public static final String NAME = TextScene.class.getSimpleName(); private final UUIDFactory uuidFactory; private OrthographicCamera camera; public TextScene(UUIDFactory factory, Game game, List<String> availableScenes) { super(NAME, factory.createUUID(), game, availableScenes); this.uuidFactory = factory; } @Override public Camera getActiveCamera() { return camera; } @Override public void init() { int range = 100; camera = new OrthographicCamera(uuidFactory.createUUID(), getGame()); camera.setFrustum(-range, range, -range, range, -range, range); String message = "THIS IS A TEXT, PLEASE SEE ME!"; int textSize = range * 2 / message.length(); Text text = new Text(uuidFactory.createUUID(), message, textSize); Transform transform = new Transform(uuidFactory.createUUID(), new Vector3d(-message.length() * textSize / 2, 0, 0)); addObject(new Renderable("The Text", uuidFactory.createUUID(), text, transform)); super.init(); } @Override protected String getInfoMessage() { return "Displays a Text in the middle of the screen."; } }
LoveNek0/UCode-Connect-Marathone
Sprint07/t10/mx_strdel.c
<reponame>LoveNek0/UCode-Connect-Marathone #include <stdlib.h> #include <stddef.h> void mx_strdel(char **str); void mx_strdel(char **str){ if(str == NULL) return; if(*str == NULL) return; free(*str); *str = NULL; }
MewX/contendo-viewer-v1.6.3
org/w3c/dom/svg/SVGSymbolElement.java
<filename>org/w3c/dom/svg/SVGSymbolElement.java package org.w3c.dom.svg; import org.w3c.dom.events.EventTarget; public interface SVGSymbolElement extends EventTarget, SVGElement, SVGExternalResourcesRequired, SVGFitToViewBox, SVGLangSpace, SVGStylable {} /* Location: /mnt/r/ConTenDoViewer.jar!/org/w3c/dom/svg/SVGSymbolElement.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
sgholamian/log-aware-clone-detection
LACCPlus/Cloudstack/1368_1.java
<filename>LACCPlus/Cloudstack/1368_1.java //,temp,PaloAltoResource.java,781,863,temp,PaloAltoResource.java,668,771 //,3 public class xxx { public boolean managePublicInterface(ArrayList<IPaloAltoCommand> cmdList, PaloAltoPrimative prim, Long publicVlanTag, String publicIp, long privateVlanTag) throws ExecutionException { String interfaceName; if (publicVlanTag == null) { interfaceName = genPublicInterfaceName(new Long("9999")); } else { interfaceName = genPublicInterfaceName(publicVlanTag); } switch (prim) { case CHECK_IF_EXISTS: // check if one exists already Map<String, String> params = new HashMap<String, String>(); params.put("type", "config"); params.put("action", "get"); params.put("xpath", "/config/devices/entry/network/interface/" + _publicInterfaceType + "/entry[@name='" + _publicInterface + "']/layer3/units/entry[@name='" + interfaceName + "']/ip/entry[@name='" + publicIp + "']"); String response = request(PaloAltoMethod.GET, params); boolean result = (validResponse(response) && responseNotEmpty(response)); s_logger.debug("Public sub-interface & IP exists: " + interfaceName + " : " + publicIp + ", " + result); return result; case ADD: if (managePublicInterface(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, publicVlanTag, publicIp, privateVlanTag)) { return true; } // add IP to the sub-interface Map<String, String> a_sub_params = new HashMap<String, String>(); a_sub_params.put("type", "config"); a_sub_params.put("action", "set"); a_sub_params.put("xpath", "/config/devices/entry/network/interface/" + _publicInterfaceType + "/entry[@name='" + _publicInterface + "']/layer3/units/entry[@name='" + interfaceName + "']/ip"); a_sub_params.put("element", "<entry name='" + publicIp + "'/>"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, a_sub_params)); // add sub-interface to VR (does nothing if already done)... Map<String, String> a_vr_params = new HashMap<String, String>(); a_vr_params.put("type", "config"); a_vr_params.put("action", "set"); a_vr_params.put("xpath", "/config/devices/entry/network/virtual-router/entry[@name='" + _virtualRouter + "']/interface"); a_vr_params.put("element", "<member>" + interfaceName + "</member>"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, a_vr_params)); // add sub-interface to vsys (does nothing if already done)... Map<String, String> a_vsys_params = new HashMap<String, String>(); a_vsys_params.put("type", "config"); a_vsys_params.put("action", "set"); a_vsys_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/import/network/interface"); a_vsys_params.put("element", "<member>" + interfaceName + "</member>"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, a_vsys_params)); // add sub-interface to zone (does nothing if already done)... Map<String, String> a_zone_params = new HashMap<String, String>(); a_zone_params.put("type", "config"); a_zone_params.put("action", "set"); a_zone_params.put("xpath", "/config/devices/entry/vsys/entry[@name='vsys1']/zone/entry[@name='" + _publicZone + "']/network/layer3"); a_zone_params.put("element", "<member>" + interfaceName + "</member>"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, a_zone_params)); return true; case DELETE: if (!managePublicInterface(cmdList, PaloAltoPrimative.CHECK_IF_EXISTS, publicVlanTag, publicIp, privateVlanTag)) { return true; } // delete IP from sub-interface... Map<String, String> d_sub_params = new HashMap<String, String>(); d_sub_params.put("type", "config"); d_sub_params.put("action", "delete"); d_sub_params.put("xpath", "/config/devices/entry/network/interface/" + _publicInterfaceType + "/entry[@name='" + _publicInterface + "']/layer3/units/entry[@name='" + interfaceName + "']/ip/entry[@name='" + publicIp + "']"); cmdList.add(new DefaultPaloAltoCommand(PaloAltoMethod.GET, d_sub_params)); return true; default: s_logger.debug("Unrecognized command."); return false; } } };
the-frontend-guy/whiz-front
src/components/about-us-banner.js
<reponame>the-frontend-guy/whiz-front<filename>src/components/about-us-banner.js import React from "react" import "./component.css" const AboutUsBanner = ({ data }) => { return ( <section className="bg-black hero"> <div className="content-container m-auto text-center"> <h1 className="section-title text-white md:text-4xl lg:text-5xl xl:text-6xl 2xl:text-7xl leading-snug tracking-tight about-us-banner-text"> <span className="block"> {data.pre_blue} <span className="text-blue-100">{data.blue1}</span> </span> <span className="block"> <span className="text-blue-100">{data.blue2}</span> {data.post_blue} </span> </h1> <p className="text-white p-4 w-full text-center m-auto md:w-4/6 lg:text-lg tracking-body mb-5"> {data.banner_desc} </p> </div> </section> ) } export default AboutUsBanner