max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
402 | #
# filter_database.py
#
# Look through a COCO-ct database and find images matching some crtieria, writing
# a subset of images and annotations to a new file.
#
#%% Constants and imports
import os
import json
import math
#%% Configuration
baseDir = r'd:\temp\snapshot_serengeti_tfrecord_generation'
imageBaseDir = os.path.join(baseDir,'imerit_batch7_images_renamed')
annotationFile = os.path.join(baseDir,'imerit_batch7_renamed_uncorrupted.json')
outputFile = os.path.join(baseDir,'imerit_batch7_renamed_uncorrupted_filtered.json')
#%% Read database and build up convenience mappings
print("Loading json database")
with open(annotationFile, 'r') as f:
data = json.load(f)
images = data['images']
annotations = data['annotations']
categories = data['categories']
# Category ID to category name
categoryIDToCategoryName = {cat['id']:cat['name'] for cat in categories}
# Image ID to image info
imageIDToImage = {im['id']:im for im in images}
# Image ID to image path
imageIDToPath = {}
for im in images:
imageID = im['id']
imageIDToPath[imageID] = os.path.join(imageBaseDir,im['file_name'])
print('Finished loading .json data')
#%% Filter
filteredImages = {}
filteredAnnotations = []
nEmpty = 0
# ann = annotations[0]
for iAnn,ann in enumerate(annotations):
# Is this a tiny box or a group annotation?
MIN_BOX_SIZE = 50
minsize = math.inf
if ('bbox' in ann):
# x,y,w,h
bbox = ann['bbox']
w = bbox[2]; h = bbox[3]
minsize = min(w,h)
annotationType = ann['annotation_type']
if ((minsize >= MIN_BOX_SIZE) and (annotationType != 'group')):
imageID = ann['image_id']
imageInfo = imageIDToImage[imageID]
filteredImages[imageID] = imageInfo
filteredAnnotations.append(ann)
if (annotationType == 'empty'):
nEmpty +=1
assert 'bbox' not in ann
# All empty annotations should be classified as either empty or ambiguous
#
# The ambiguous cases are basically minor misses on the annotators' part,
# where two different small animals were present somewhere.
assert ann['category_id'] == 0 or ann['category_id'] == 1001
print('Filtered {} of {} images and {} of {} annotations ({} empty)'.format(
len(filteredImages),len(images),
len(filteredAnnotations),len(annotations),nEmpty))
#%% Write output file
dataFiltered = data
dataFiltered['images'] = list(filteredImages.values())
dataFiltered['annotations'] = filteredAnnotations
json.dump(dataFiltered,open(outputFile,'w'))
| 970 |
3,573 | <reponame>ex0ample/cryptopp<gh_stars>1000+
#include <altivec.h>
int main(int argc, char* argv[])
{
#if defined(__ibmxl__) || (defined(_AIX) && defined(__xlC__))
__vector unsigned int x = {1,2,3,4};
x=__vshasigmaw(x, 0, 0);
__vector unsigned long long y = {1,2};
y=__vshasigmad(y, 0, 0);
#elif defined(__clang__)
__vector unsigned int x = {1,2,3,4};
x=__builtin_altivec_crypto_vshasigmaw(x, 0, 0);
__vector unsigned long long y = {1,2};
y=__builtin_altivec_crypto_vshasigmad(y, 0, 0);
#elif defined(__GNUC__)
__vector unsigned int x = {1,2,3,4};
x=__builtin_crypto_vshasigmaw(x, 0, 0);
__vector unsigned long long y = {1,2};
y=__builtin_crypto_vshasigmad(y, 0, 0);
#else
int XXX[-1];
#endif
return 0;
}
| 393 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.glassfish.spi;
/**
*
* @author <NAME>
*/
public abstract class ResourceDecorator extends Decorator {
/**
* What property name does the delete resource command for this resource
* type use.
*
* @return property name to use to specify resource name in delete resource command
*/
public abstract String getCmdPropertyName();
/**
* Does this resource's delete command support --cascade to remove dependent
* resources (e.g. connection-pools)
*
* @return true if we should use cascade=true on delete
*/
public boolean isCascadeDelete() {
return false;
}
@Override
public boolean canEditDetails() {
return true;
}
}
| 450 |
312 | <filename>solutions/MultilingualPages/SPFxExt/config/config.json
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"multilingual-extension-application-customizer": {
"components": [
{
"entrypoint": "./lib/extensions/multilingualExtension/MultilingualExtensionApplicationCustomizer.js",
"manifest": "./src/extensions/multilingualExtension/MultilingualExtensionApplicationCustomizer.manifest.json"
}
]
},
"multilingual-redirector-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/multilingualRedirector/MultilingualRedirectorWebPart.js",
"manifest": "./src/webparts/multilingualRedirector/MultilingualRedirectorWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"MultilingualExtensionApplicationCustomizerStrings": "lib/extensions/multilingualExtension/loc/{locale}.js",
"MultilingualRedirectorWebPartStrings": "lib/webparts/multilingualRedirector/loc/{locale}.js"
}
}
| 441 |
315 | /*
* testpalette.c
*
* A simple test of runtime palette modification for animation
* (using the SDL_SetPalette() API).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/* This isn't in the Windows headers */
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#include "SDL.h"
/* screen size */
#define SCRW 640
#define SCRH 480
#define NBOATS 5
#define SPEED 2
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
/*
* wave colours: Made by taking a narrow cross-section of a wave picture
* in Gimp, saving in PPM ascii format and formatting with Emacs macros.
*/
static SDL_Color wavemap[] = {
{0,2,103}, {0,7,110}, {0,13,117}, {0,19,125},
{0,25,133}, {0,31,141}, {0,37,150}, {0,43,158},
{0,49,166}, {0,55,174}, {0,61,182}, {0,67,190},
{0,73,198}, {0,79,206}, {0,86,214}, {0,96,220},
{5,105,224}, {12,112,226}, {19,120,227}, {26,128,229},
{33,135,230}, {40,143,232}, {47,150,234}, {54,158,236},
{61,165,238}, {68,173,239}, {75,180,241}, {82,188,242},
{89,195,244}, {96,203,246}, {103,210,248}, {112,218,250},
{124,224,250}, {135,226,251}, {146,229,251}, {156,231,252},
{167,233,252}, {178,236,252}, {189,238,252}, {200,240,252},
{211,242,252}, {222,244,252}, {233,247,252}, {242,249,252},
{237,250,252}, {209,251,252}, {174,251,252}, {138,252,252},
{102,251,252}, {63,250,252}, {24,243,252}, {7,225,252},
{4,203,252}, {3,181,252}, {2,158,252}, {1,136,251},
{0,111,248}, {0,82,234}, {0,63,213}, {0,50,192},
{0,39,172}, {0,28,152}, {0,17,132}, {0,7,114}
};
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void sdlerr(char *when)
{
fprintf(stderr, "SDL error: %s: %s\n", when, SDL_GetError());
quit(1);
}
/* create a background surface */
static SDL_Surface *make_bg(SDL_Surface *screen, int startcol)
{
int i;
SDL_Surface *bg = SDL_CreateRGBSurface(SDL_SWSURFACE, screen->w, screen->h,
8, 0, 0, 0, 0);
if(!bg)
sdlerr("creating background surface");
/* set the palette to the logical screen palette so that blits
won't be translated */
SDL_SetColors(bg, screen->format->palette->colors, 0, 256);
/* Make a wavy background pattern using colours 0-63 */
if(SDL_LockSurface(bg) < 0)
sdlerr("locking background");
for(i = 0; i < SCRH; i++) {
Uint8 *p = (Uint8 *)bg->pixels + i * bg->pitch;
int j, d;
d = 0;
for(j = 0; j < SCRW; j++) {
int v = MAX(d, -2);
v = MIN(v, 2);
if(i > 0)
v += p[-bg->pitch] + 65 - startcol;
p[j] = startcol + (v & 63);
d += ((rand() >> 3) % 3) - 1;
}
}
SDL_UnlockSurface(bg);
return(bg);
}
/*
* Return a surface flipped horisontally. Only works for 8bpp;
* extension to arbitrary bitness is left as an exercise for the reader.
*/
static SDL_Surface *hflip(SDL_Surface *s)
{
int i;
SDL_Surface *z = SDL_CreateRGBSurface(SDL_SWSURFACE, s->w, s->h, 8,
0, 0, 0, 0);
/* copy palette */
SDL_SetColors(z, s->format->palette->colors,
0, s->format->palette->ncolors);
if(SDL_LockSurface(s) < 0 || SDL_LockSurface(z) < 0)
sdlerr("locking flip images");
for(i = 0; i < s->h; i++) {
int j;
Uint8 *from = (Uint8 *)s->pixels + i * s->pitch;
Uint8 *to = (Uint8 *)z->pixels + i * z->pitch + s->w - 1;
for(j = 0; j < s->w; j++)
to[-j] = from[j];
}
SDL_UnlockSurface(z);
SDL_UnlockSurface(s);
return z;
}
int main(int argc, char **argv)
{
SDL_Color cmap[256];
SDL_Surface *screen;
SDL_Surface *bg;
SDL_Surface *boat[2];
unsigned vidflags = 0;
unsigned start;
int fade_max = 400;
int fade_level, fade_dir;
int boatcols, frames, i, red;
int boatx[NBOATS], boaty[NBOATS], boatdir[NBOATS];
int gamma_fade = 0;
int gamma_ramp = 0;
if(SDL_Init(SDL_INIT_VIDEO) < 0)
sdlerr("initialising SDL");
while(--argc) {
++argv;
if(strcmp(*argv, "-hw") == 0)
vidflags |= SDL_HWSURFACE;
else if(strcmp(*argv, "-fullscreen") == 0)
vidflags |= SDL_FULLSCREEN;
else if(strcmp(*argv, "-nofade") == 0)
fade_max = 1;
else if(strcmp(*argv, "-gamma") == 0)
gamma_fade = 1;
else if(strcmp(*argv, "-gammaramp") == 0)
gamma_ramp = 1;
else {
fprintf(stderr,
"usage: testpalette "
" [-hw] [-fullscreen] [-nofade] [-gamma] [-gammaramp]\n");
quit(1);
}
}
/* Ask explicitly for 8bpp and a hardware palette */
if((screen = SDL_SetVideoMode(SCRW, SCRH, 8, vidflags | SDL_HWPALETTE)) == NULL) {
fprintf(stderr, "error setting %dx%d 8bpp indexed mode: %s\n",
SCRW, SCRH, SDL_GetError());
quit(1);
}
if (vidflags & SDL_FULLSCREEN) SDL_ShowCursor (SDL_FALSE);
if((boat[0] = SDL_LoadBMP("sail.bmp")) == NULL)
sdlerr("loading sail.bmp");
/* We've chosen magenta (#ff00ff) as colour key for the boat */
SDL_SetColorKey(boat[0], SDL_SRCCOLORKEY | SDL_RLEACCEL,
SDL_MapRGB(boat[0]->format, 0xff, 0x00, 0xff));
boatcols = boat[0]->format->palette->ncolors;
boat[1] = hflip(boat[0]);
SDL_SetColorKey(boat[1], SDL_SRCCOLORKEY | SDL_RLEACCEL,
SDL_MapRGB(boat[1]->format, 0xff, 0x00, 0xff));
/*
* First set the physical screen palette to black, so the user won't
* see our initial drawing on the screen.
*/
memset(cmap, 0, sizeof(cmap));
SDL_SetPalette(screen, SDL_PHYSPAL, cmap, 0, 256);
/*
* Proper palette management is important when playing games with the
* colormap. We have divided the palette as follows:
*
* index 0..(boatcols-1): used for the boat
* index boatcols..(boatcols+63): used for the waves
*/
SDL_SetPalette(screen, SDL_LOGPAL,
boat[0]->format->palette->colors, 0, boatcols);
SDL_SetPalette(screen, SDL_LOGPAL, wavemap, boatcols, 64);
/*
* Now the logical screen palette is set, and will remain unchanged.
* The boats already have the same palette so fast blits can be used.
*/
memcpy(cmap, screen->format->palette->colors, 256 * sizeof(SDL_Color));
/* save the index of the red colour for later */
red = SDL_MapRGB(screen->format, 0xff, 0x00, 0x00);
bg = make_bg(screen, boatcols); /* make a nice wavy background surface */
/* initial screen contents */
if(SDL_BlitSurface(bg, NULL, screen, NULL) < 0)
sdlerr("blitting background to screen");
SDL_Flip(screen); /* actually put the background on screen */
/* determine initial boat placements */
for(i = 0; i < NBOATS; i++) {
boatx[i] = (rand() % (SCRW + boat[0]->w)) - boat[0]->w;
boaty[i] = i * (SCRH - boat[0]->h) / (NBOATS - 1);
boatdir[i] = ((rand() >> 5) & 1) * 2 - 1;
}
start = SDL_GetTicks();
frames = 0;
fade_dir = 1;
fade_level = 0;
do {
SDL_Event e;
SDL_Rect updates[NBOATS];
SDL_Rect r;
int redphase;
/* A small event loop: just exit on any key or mouse button event */
while(SDL_PollEvent(&e)) {
if(e.type == SDL_KEYDOWN || e.type == SDL_QUIT
|| e.type == SDL_MOUSEBUTTONDOWN) {
if(fade_dir < 0)
fade_level = 0;
fade_dir = -1;
}
}
/* move boats */
for(i = 0; i < NBOATS; i++) {
int old_x = boatx[i];
/* update boat position */
boatx[i] += boatdir[i] * SPEED;
if(boatx[i] <= -boat[0]->w || boatx[i] >= SCRW)
boatdir[i] = -boatdir[i];
/* paint over the old boat position */
r.x = old_x;
r.y = boaty[i];
r.w = boat[0]->w;
r.h = boat[0]->h;
if(SDL_BlitSurface(bg, &r, screen, &r) < 0)
sdlerr("blitting background");
/* construct update rectangle (bounding box of old and new pos) */
updates[i].x = MIN(old_x, boatx[i]);
updates[i].y = boaty[i];
updates[i].w = boat[0]->w + SPEED;
updates[i].h = boat[0]->h;
/* clip update rectangle to screen */
if(updates[i].x < 0) {
updates[i].w += updates[i].x;
updates[i].x = 0;
}
if(updates[i].x + updates[i].w > SCRW)
updates[i].w = SCRW - updates[i].x;
}
for(i = 0; i < NBOATS; i++) {
/* paint boat on new position */
r.x = boatx[i];
r.y = boaty[i];
if(SDL_BlitSurface(boat[(boatdir[i] + 1) / 2], NULL,
screen, &r) < 0)
sdlerr("blitting boat");
}
/* cycle wave palette */
for(i = 0; i < 64; i++)
cmap[boatcols + ((i + frames) & 63)] = wavemap[i];
if(fade_dir) {
/* Fade the entire palette in/out */
fade_level += fade_dir;
if(gamma_fade) {
/* Fade linearly in gamma level (lousy) */
float level = (float)fade_level / fade_max;
if(SDL_SetGamma(level, level, level) < 0)
sdlerr("setting gamma");
} else if(gamma_ramp) {
/* Fade using gamma ramp (better) */
Uint16 ramp[256];
for(i = 0; i < 256; i++)
ramp[i] = (i * fade_level / fade_max) << 8;
if(SDL_SetGammaRamp(ramp, ramp, ramp) < 0)
sdlerr("setting gamma ramp");
} else {
/* Fade using direct palette manipulation (best) */
memcpy(cmap, screen->format->palette->colors,
boatcols * sizeof(SDL_Color));
for(i = 0; i < boatcols + 64; i++) {
cmap[i].r = cmap[i].r * fade_level / fade_max;
cmap[i].g = cmap[i].g * fade_level / fade_max;
cmap[i].b = cmap[i].b * fade_level / fade_max;
}
}
if(fade_level == fade_max)
fade_dir = 0;
}
/* pulse the red colour (done after the fade, for a night effect) */
redphase = frames % 64;
cmap[red].r = (int)(255 * sin(redphase * M_PI / 63));
SDL_SetPalette(screen, SDL_PHYSPAL, cmap, 0, boatcols + 64);
/* update changed areas of the screen */
SDL_UpdateRects(screen, NBOATS, updates);
frames++;
} while(fade_level > 0);
printf("%d frames, %.2f fps\n",
frames, 1000.0 * frames / (SDL_GetTicks() - start));
if (vidflags & SDL_FULLSCREEN) SDL_ShowCursor (SDL_TRUE);
SDL_Quit();
return 0;
}
| 4,502 |
18,396 | <reponame>attenuation/srs<filename>trunk/3rdparty/srt-1-fit/srtcore/channel.h
/*
* SRT - Secure, Reliable, Transport
* Copyright (c) 2018 Haivision Systems Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
/*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
nor the names of its contributors may be used to
endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
/*****************************************************************************
written by
<NAME>, last updated 01/27/2011
modified by
Haivision Systems Inc.
*****************************************************************************/
#ifndef __UDT_CHANNEL_H__
#define __UDT_CHANNEL_H__
#include "udt.h"
#include "packet.h"
#include "netinet_any.h"
class CChannel
{
public:
// XXX There's currently no way to access the socket ID set for
// whatever the channel is currently working for. Required to find
// some way to do this, possibly by having a "reverse pointer".
// Currently just "unimplemented".
std::string CONID() const { return ""; }
CChannel();
CChannel(int version);
~CChannel();
/// Open a UDP channel.
/// @param [in] addr The local address that UDP will use.
void open(const sockaddr* addr = NULL);
/// Open a UDP channel based on an existing UDP socket.
/// @param [in] udpsock UDP socket descriptor.
void attach(UDPSOCKET udpsock);
/// Disconnect and close the UDP entity.
void close() const;
/// Get the UDP sending buffer size.
/// @return Current UDP sending buffer size.
int getSndBufSize();
/// Get the UDP receiving buffer size.
/// @return Current UDP receiving buffer size.
int getRcvBufSize();
/// Set the UDP sending buffer size.
/// @param [in] size expected UDP sending buffer size.
void setSndBufSize(int size);
/// Set the UDP receiving buffer size.
/// @param [in] size expected UDP receiving buffer size.
void setRcvBufSize(int size);
/// Set the IPV6ONLY option.
/// @param [in] IPV6ONLY value.
void setIpV6Only(int ipV6Only);
/// Query the socket address that the channel is using.
/// @param [out] addr pointer to store the returned socket address.
void getSockAddr(sockaddr* addr) const;
/// Query the peer side socket address that the channel is connect to.
/// @param [out] addr pointer to store the returned socket address.
void getPeerAddr(sockaddr* addr) const;
/// Send a packet to the given address.
/// @param [in] addr pointer to the destination address.
/// @param [in] packet reference to a CPacket entity.
/// @return Actual size of data sent.
int sendto(const sockaddr* addr, CPacket& packet) const;
/// Receive a packet from the channel and record the source address.
/// @param [in] addr pointer to the source address.
/// @param [in] packet reference to a CPacket entity.
/// @return Actual size of data received.
EReadStatus recvfrom(sockaddr* addr, CPacket& packet) const;
#ifdef SRT_ENABLE_IPOPTS
/// Set the IP TTL.
/// @param [in] ttl IP Time To Live.
/// @return none.
void setIpTTL(int ttl);
/// Set the IP Type of Service.
/// @param [in] tos IP Type of Service.
void setIpToS(int tos);
/// Get the IP TTL.
/// @param [in] ttl IP Time To Live.
/// @return TTL.
int getIpTTL() const;
/// Get the IP Type of Service.
/// @return ToS.
int getIpToS() const;
#endif
int ioctlQuery(int type) const;
int sockoptQuery(int level, int option) const;
const sockaddr* bindAddress() { return &m_BindAddr; }
const sockaddr_any& bindAddressAny() { return m_BindAddr; }
private:
void setUDPSockOpt();
private:
const int m_iIPversion; // IP version
int m_iSockAddrSize; // socket address structure size (pre-defined to avoid run-time test)
UDPSOCKET m_iSocket; // socket descriptor
#ifdef SRT_ENABLE_IPOPTS
int m_iIpTTL;
int m_iIpToS;
#endif
int m_iSndBufSize; // UDP sending buffer size
int m_iRcvBufSize; // UDP receiving buffer size
int m_iIpV6Only; // IPV6_V6ONLY option (-1 if not set)
sockaddr_any m_BindAddr;
};
#endif
| 2,000 |
412 | <gh_stars>100-1000
inline int foo()
{
int *p;
return *p;
}
int main()
{
foo();
return 0;
}
| 48 |
1,103 | from recon.core.module import BaseModule
from recon.mixins.search import GoogleWebMixin
import urllib
import re
class Module(BaseModule, GoogleWebMixin):
meta = {
'name': 'Google Hostname Enumerator',
'author': '<NAME> (@LaNMaSteR53)',
'description': 'Harvests hosts from Google.com by using the \'site\' search operator. Updates the \'hosts\' table with the results.',
'query': 'SELECT DISTINCT domain FROM domains WHERE domain IS NOT NULL',
}
def module_run(self, domains):
for domain in domains:
self.heading(domain, level=0)
base_query = 'site:' + domain
regmatch = re.compile('//([^/]*\.%s)' % (domain))
hosts = []
# control variables
new = True
page = 1
nr = 100
# execute search engine queries and scrape results storing subdomains in a list
# loop until no new subdomains are found
while new:
# build query based on results of previous results
query = ''
for host in hosts:
query += ' -site:%s' % (host)
# send query to search engine
results = self.search_google_web(base_query + query, limit=1, start_page=page)
# extract hosts from search results
sites = []
for link in results:
site = regmatch.search(link)
if site is not None:
sites.append(site.group(1))
# create a unique list
sites = list(set(sites))
# add subdomain to list if not already exists
new = False
for site in sites:
if site not in hosts:
hosts.append(site)
new = True
self.add_hosts(site)
if not new:
# exit if all subdomains have been found
if not results:
break
else:
# intelligently paginate separate from the framework to optimize the number of queries required
page += 1
self.verbose('No New Subdomains Found on the Current Page. Jumping to Result %d.' % ((page*nr)+1))
new = True
| 1,219 |
771 | import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 密码加密测试
*
* @author tycoding
* @date 2019-05-29
*/
@Slf4j
public class PasswordEncoderTest {
private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
public static void main(String[] args) {
log.info("tycoding >> {}", passwordEncoder.encode("tycoding")); // $2a$10$akcNI/pr9l0kS7JAXFSsNeJpodmdCq2aaNBohjbxXhF1StVtmWTEu
log.info("admin >> {}", passwordEncoder.encode("admin")); // $2a$10$zVAf02ng.YxGK14F8Riq/uLsNLA.tUYbv5QTPpQNnxDfnEEXW0upK
log.info("test >> {}", passwordEncoder.encode("test")); // $2a$10$Rh//mbhIE6df8eUnR99gYuEKodd9.400uKMUhSCKnFMvy2pW/lSjy
}
}
| 356 |
339 | <filename>integration/dataservice-hosting-tests/tests-integration/tests/src/test/java/org/wso2/ei/dataservice/integration/test/samples/RDBMSSampleTestCase.java
/*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.ei.dataservice.integration.test.samples;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.dataservices.samples.rdbms_sample.DataServiceFault;
import org.wso2.carbon.dataservices.samples.rdbms_sample.RDBMSSampleStub;
import org.wso2.ei.dataservice.integration.test.DSSIntegrationTest;
import org.wso2.ws.dataservice.samples.rdbms_sample.Customer;
import org.wso2.ws.dataservice.samples.rdbms_sample.Employee;
import java.io.File;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RDBMSSampleTestCase extends DSSIntegrationTest {
private static final Log log = LogFactory.getLog(RDBMSSampleTestCase.class);
private final String serviceName = "RDBMSSample";
private RDBMSSampleStub stub;
private int randomNumber;
@Factory(dataProvider = "userModeDataProvider")
public RDBMSSampleTestCase(TestUserMode userMode) {
this.userMode = userMode;
}
@BeforeClass(alwaysRun = true)
public void serviceDeployment() throws Exception {
super.init(userMode);
String serviceEndPoint = getServiceUrlHttp(serviceName);
stub = new RDBMSSampleStub(serviceEndPoint);
List<File> sqlFileLis = new ArrayList<File>();
sqlFileLis.add(selectSqlFile("CreateTables.sql"));
sqlFileLis.add(selectSqlFile("Customers.sql"));
sqlFileLis.add(selectSqlFile("Employees.sql"));
deployService(serviceName,
createArtifact(getResourceLocation() + File.separator + "samples"
+ File.separator + "dbs" + File.separator
+ "rdbms" + File.separator + "RDBMSSample.dbs", sqlFileLis));
randomNumber = new Random().nextInt(2000) + 2000; //added 2000 because table already have ids up nearly to 2000
}
@Test(groups = {"wso2.dss"})
public void selectOperation() throws RemoteException, DataServiceFault {
for (int i = 0; i < 5; i++) {
Customer[] customers = stub.customersInBoston();
for (Customer customer : customers) {
Assert.assertEquals(customer.getCity(), "Boston", "City mismatched");
}
}
log.info("Select Operation Success");
}
@Test(groups = {"wso2.dss"}, dependsOnMethods = "selectOperation")
public void insertOperation() throws RemoteException, DataServiceFault {
for (int i = 0; i < 5; i++) {
stub.addEmployee(randomNumber + i, "FirstName", "LastName", "<EMAIL>", 50000.00);
}
log.info("Insert Operation Success");
}
@Test(groups = {"wso2.dss"}, dependsOnMethods = "selectOperation")
public void testLengthValidator() throws RemoteException, DataServiceFault {
try {
stub.addEmployee(1, "FN", "LN", "<EMAIL>", 50000.00);
} catch (DataServiceFault e){
assert "VALIDATION_ERROR".equals(e.getFaultMessage().getDs_code().trim());
assert "addEmployee".equals(e.getFaultMessage().getCurrent_request_name().trim());
}
}
@Test(groups = {"wso2.dss"}, dependsOnMethods = "selectOperation")
public void testPatternValidator() throws RemoteException, DataServiceFault {
try {
stub.addEmployee(1, "FirstName", "LastName", "wrong_email_pattern", 50000.00);
} catch (DataServiceFault e){
assert "VALIDATION_ERROR".equals(e.getFaultMessage().getDs_code().trim());
assert "addEmployee".equals(e.getFaultMessage().getCurrent_request_name().trim());
}
}
@Test(groups = {"wso2.dss"}, dependsOnMethods = {"insertOperation"})
public void selectByNumber() throws RemoteException, DataServiceFault {
for (int i = 0; i < 5; i++) {
Employee[] employees = stub.employeesByNumber(randomNumber + i);
Assert.assertNotNull(employees, "Employee not found");
Assert.assertEquals(employees.length, 1, "Employee count mismatched for given emp number");
}
log.info("Select operation with parameter success");
}
@Test(groups = {"wso2.dss"}, dependsOnMethods = {"selectByNumber"})
public void updateOperation() throws RemoteException, DataServiceFault {
for (int i = 0; i < 5; i++) {
stub.incrementEmployeeSalary(20000.00, randomNumber + i);
Employee[] employees = stub.employeesByNumber(randomNumber + i);
Assert.assertNotNull(employees, "Employee not found");
Assert.assertEquals(employees.length, 1, "Employee count mismatched for given emp number");
Assert.assertEquals(employees[0].getSalary(), 70000.00, "Salary Increment not set");
}
log.info("Update Operation success");
}
@Test(groups = {"wso2.dss"}, dependsOnMethods = {"updateOperation"}, enabled = false)
public void deleteOperation() throws RemoteException, DataServiceFault {
for (int i = 0; i < 5; i++) {
stub.begin_boxcar();
stub.thousandFive();
stub.incrementEmployeeSalaryEx(randomNumber + i);
stub.end_boxcar();
Employee[] employees = stub.employeesByNumber(randomNumber + i);
Assert.assertNotNull(employees, "Employee not found");
Assert.assertEquals(employees.length, 1, "Employee count mismatched for given emp number");
Assert.assertEquals(employees[0].getSalary(), 71500.00, "Salary Increment not setby boxcaring");
}
log.info("Delete operation success");
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
deleteService(serviceName);
cleanup();
stub = null;
}
}
| 2,686 |
421 | <gh_stars>100-1000
"""Restart containers associated with Dusty apps or services.
Upon restart, an app container will execute the command specified
in its `commands.always` spec key. Restarting app containers will
also perform a NFS mount of repos needed for restarted containers,
using your current repo override settings.
Usage:
restart ( --repos <repos>... | [<services>...] )
Options:
--repos <repos> If provided, Dusty will restart any containers
that are using the repos specified.
<services> If provided, Dusty will only restart the given
services. Otherwise, all currently running
services are restarted.
"""
from docopt import docopt
from ..payload import Payload
from ..commands.run import restart_apps_or_services, restart_apps_by_repo
def main(argv):
args = docopt(__doc__, argv)
if args['--repos']:
return Payload(restart_apps_by_repo, args['--repos'])
return Payload(restart_apps_or_services, args['<services>'])
| 358 |
387 | #ifndef _CPP_CSTD_STRING_H_
#define _CPP_CSTD_STRING_H_
#include "../export.h"
#include <string.h>
DLLEXPORT void* cstd_memcpy(void* buf1, const void* buf2, size_t n)
{
return memcpy(buf1, buf2, n);
}
#endif | 116 |
1,962 | package com.bolingcavalry.service.impl;
import com.bolingcavalry.service.MessageService;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Properties;
/**
* @author willzhao
* @version V1.0
* @Description: 实现消息服务
* @email <EMAIL>
* @Date 2017/10/28 上午9:58
*/
@Service
public class MessageServiceImpl implements MessageService{
private Producer<String, String> producer = null;
@PostConstruct
public void init(){
try {
Properties props = new Properties();
props.put("serializer.class", "kafka.serializer.StringEncoder");
props.put("zk.connect", "hostb1:2181,hostb1:2181,hostb1:2181");
props.put("metadata.broker.list", "hostb1:9092,hostb1:9092,hostb1:9092");
props.put("partitioner.class","com.bolingcavalry.service.BusinessPartition");
producer = new kafka.javaapi.producer.Producer<String, String>(new ProducerConfig(props));
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendSimpleMsg(String topic, String message) {
//producer的内部实现中,已经考虑了线程安全,所以此处不用加锁了
producer.send(new KeyedMessage<String, String>(topic, message));
}
public void sendKeyMsg(String topic, String key, String message) {
//producer的内部实现中,已经考虑了线程安全,所以此处不用加锁了
producer.send(new KeyedMessage<String, String>(topic, key, message));
}
}
| 724 |
2,291 | {
"id" : 371,
"status" : "Invalid",
"summary" : "How to create overlayItem by click on map?",
"labels" : [ "Type-Defect", "Priority-Medium" ],
"stars" : 0,
"commentCount" : 3,
"comments" : [ {
"id" : 0,
"commenterId" : 462469271112654667,
"content" : "Hello\r\nI'm developing an android program with Osmdroid & custom map. I want that the users could click on map to add a point ( overlayItem ) and then forward to an other activiy. how can I push a pin on map by clicking on it? thanks.",
"timestamp" : 1348726337,
"attachments" : [ ]
}, {
"id" : 1,
"commenterId" : 1558421220117089513,
"content" : "You can have a look here: http://code.google.com/p/osmbonuspack\r\n\r\nImplementation is done here:\r\nhttp://code.google.com/p/osmbonuspack/source/browse/trunk/OSMBonusPack/src/org/osmdroid/bonuspack/overlays/MapEventsOverlay.java\r\n\r\nAnd this class is used here: \r\nhttp://code.google.com/p/osmbonuspack/source/browse/trunk/OSMBonusPackDemo/src/com/osmbonuspackdemo/MapActivity.java\r\n\r\n",
"timestamp" : 1349708201,
"attachments" : [ ]
}, {
"id" : 2,
"commenterId" : 7646092065249173135,
"content" : "",
"timestamp" : 1357242793,
"attachments" : [ ]
} ]
} | 517 |
1,855 | <filename>SevenZip/CPP/7zip/Compress/LzfseDecoder.cpp
// LzfseDecoder.cpp
/*
This code implements LZFSE data decompressing.
The code from "LZFSE compression library" was used.
2018 : <NAME> : BSD 3-clause License : the code in this file
2015-2017 : Apple Inc : BSD 3-clause License : original "LZFSE compression library" code
The code in the "LZFSE compression library" is licensed under the "BSD 3-clause License":
----
Copyright (c) 2015-2016, 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----
*/
#include "StdAfx.h"
// #define SHOW_DEBUG_INFO
#ifdef SHOW_DEBUG_INFO
#include <stdio.h>
#endif
#ifdef SHOW_DEBUG_INFO
#define PRF(x) x
#else
#define PRF(x)
#endif
#include "../../../C/CpuArch.h"
#include "LzfseDecoder.h"
namespace NCompress {
namespace NLzfse {
static const Byte kSignature_LZFSE_V1 = 0x31; // '1'
static const Byte kSignature_LZFSE_V2 = 0x32; // '2'
HRESULT CDecoder::GetUInt32(UInt32 &val)
{
Byte b[4];
for (unsigned i = 0; i < 4; i++)
if (!m_InStream.ReadByte(b[i]))
return S_FALSE;
val = GetUi32(b);
return S_OK;
}
HRESULT CDecoder::DecodeUncompressed(UInt32 unpackSize)
{
PRF(printf("\nUncompressed %7u\n", unpackSize));
const unsigned kBufSize = 1 << 8;
Byte buf[kBufSize];
for (;;)
{
if (unpackSize == 0)
return S_OK;
UInt32 cur = unpackSize;
if (cur > kBufSize)
cur = kBufSize;
UInt32 cur2 = (UInt32)m_InStream.ReadBytes(buf, cur);
m_OutWindowStream.PutBytes(buf, cur2);
if (cur != cur2)
return S_FALSE;
}
}
HRESULT CDecoder::DecodeLzvn(UInt32 unpackSize)
{
UInt32 packSize;
RINOK(GetUInt32(packSize));
PRF(printf("\nLZVN %7u %7u", unpackSize, packSize));
UInt32 D = 0;
for (;;)
{
if (packSize == 0)
return S_FALSE;
Byte b;
if (!m_InStream.ReadByte(b))
return S_FALSE;
packSize--;
UInt32 M;
UInt32 L;
if (b >= 0xE0)
{
/*
large L - 11100000 LLLLLLLL <LITERALS>
small L - 1110LLLL <LITERALS>
large Rep - 11110000 MMMMMMMM
small Rep - 1111MMMM
*/
M = b & 0xF;
if (M == 0)
{
if (packSize == 0)
return S_FALSE;
Byte b1;
if (!m_InStream.ReadByte(b1))
return S_FALSE;
packSize--;
M = (UInt32)b1 + 16;
}
L = 0;
if ((b & 0x10) == 0)
{
// Literals only
L = M;
M = 0;
}
}
// ERROR codes
else if ((b & 0xF0) == 0x70) // 0111xxxx
return S_FALSE;
else if ((b & 0xF0) == 0xD0) // 1101xxxx
return S_FALSE;
else
{
if ((b & 0xE0) == 0xA0)
{
// medium - 101LLMMM DDDDDDMM DDDDDDDD <LITERALS>
if (packSize < 2)
return S_FALSE;
Byte b1;
if (!m_InStream.ReadByte(b1))
return S_FALSE;
packSize--;
Byte b2;
if (!m_InStream.ReadByte(b2))
return S_FALSE;
packSize--;
L = (((UInt32)b >> 3) & 3);
M = (((UInt32)b & 7) << 2) + (b1 & 3);
D = ((UInt32)b1 >> 2) + ((UInt32)b2 << 6);
}
else
{
L = (UInt32)b >> 6;
M = ((UInt32)b >> 3) & 7;
if ((b & 0x7) == 6)
{
// REP - LLMMM110 <LITERALS>
if (L == 0)
{
// spec
if (M == 0)
break; // EOS
if (M <= 2)
continue; // NOP
return S_FALSE; // UNDEFINED
}
}
else
{
if (packSize == 0)
return S_FALSE;
Byte b1;
if (!m_InStream.ReadByte(b1))
return S_FALSE;
packSize--;
// large - LLMMM111 DDDDDDDD DDDDDDDD <LITERALS>
// small - LLMMMDDD DDDDDDDD <LITERALS>
D = ((UInt32)b & 7);
if (D == 7)
{
if (packSize == 0)
return S_FALSE;
Byte b2;
if (!m_InStream.ReadByte(b2))
return S_FALSE;
packSize--;
D = b2;
}
D = (D << 8) + b1;
}
}
M += 3;
}
{
for (unsigned i = 0; i < L; i++)
{
if (packSize == 0 || unpackSize == 0)
return S_FALSE;
Byte b1;
if (!m_InStream.ReadByte(b1))
return S_FALSE;
packSize--;
m_OutWindowStream.PutByte(b1);
unpackSize--;
}
}
if (M != 0)
{
if (unpackSize == 0 || D == 0)
return S_FALSE;
unsigned cur = M;
if (cur > unpackSize)
cur = (unsigned)unpackSize;
if (!m_OutWindowStream.CopyBlock(D - 1, cur))
return S_FALSE;
unpackSize -= cur;
if (cur != M)
return S_FALSE;
}
}
if (unpackSize != 0)
return S_FALSE;
// LZVN encoder writes 7 additional zero bytes
if (packSize != 7)
return S_FALSE;
do
{
Byte b;
if (!m_InStream.ReadByte(b))
return S_FALSE;
packSize--;
if (b != 0)
return S_FALSE;
}
while (packSize != 0);
return S_OK;
}
// ---------- LZFSE ----------
#define MATCHES_PER_BLOCK 10000
#define LITERALS_PER_BLOCK (4 * MATCHES_PER_BLOCK)
#define NUM_L_SYMBOLS 20
#define NUM_M_SYMBOLS 20
#define NUM_D_SYMBOLS 64
#define NUM_LIT_SYMBOLS 256
#define NUM_SYMBOLS ( \
NUM_L_SYMBOLS + \
NUM_M_SYMBOLS + \
NUM_D_SYMBOLS + \
NUM_LIT_SYMBOLS)
#define NUM_L_STATES (1 << 6)
#define NUM_M_STATES (1 << 6)
#define NUM_D_STATES (1 << 8)
#define NUM_LIT_STATES (1 << 10)
typedef UInt32 CFseState;
static UInt32 SumFreqs(const UInt16 *freqs, unsigned num)
{
UInt32 sum = 0;
for (unsigned i = 0; i < num; i++)
sum += (UInt32)freqs[i];
return sum;
}
static MY_FORCE_INLINE unsigned CountZeroBits(UInt32 val, UInt32 mask)
{
for (unsigned i = 0;;)
{
if (val & mask)
return i;
i++;
mask >>= 1;
}
}
static MY_FORCE_INLINE void InitLitTable(const UInt16 *freqs, UInt32 *table)
{
for (unsigned i = 0; i < NUM_LIT_SYMBOLS; i++)
{
unsigned f = freqs[i];
if (f == 0)
continue;
// 0 < f <= numStates
// 0 <= k <= numStatesLog
// numStates <= (f<<k) < numStates * 2
// 0 < j0 <= f
// (f + j0) = next_power_of_2 for f
unsigned k = CountZeroBits(f, NUM_LIT_STATES);
unsigned j0 = (((unsigned)NUM_LIT_STATES * 2) >> k) - f;
/*
CEntry
{
Byte k;
Byte symbol;
UInt16 delta;
};
*/
UInt32 e = ((UInt32)i << 8) + k;
k += 16;
UInt32 d = e + ((UInt32)f << k) - ((UInt32)NUM_LIT_STATES << 16);
UInt32 step = (UInt32)1 << k;
unsigned j = 0;
do
{
*table++ = d;
d += step;
}
while (++j < j0);
e--;
step >>= 1;
for (j = j0; j < f; j++)
{
*table++ = e;
e += step;
}
}
}
typedef struct
{
Byte totalBits;
Byte extraBits;
UInt16 delta;
UInt32 vbase;
} CExtraEntry;
static void InitExtraDecoderTable(unsigned numStates,
unsigned numSymbols,
const UInt16 *freqs,
const Byte *vbits,
CExtraEntry *table)
{
UInt32 vbase = 0;
for (unsigned i = 0; i < numSymbols; i++)
{
unsigned f = freqs[i];
unsigned extraBits = vbits[i];
if (f != 0)
{
unsigned k = CountZeroBits(f, numStates);
unsigned j0 = ((2 * numStates) >> k) - f;
unsigned j = 0;
do
{
CExtraEntry *e = table++;
e->totalBits = (Byte)(k + extraBits);
e->extraBits = (Byte)extraBits;
e->delta = (UInt16)(((f + j) << k) - numStates);
e->vbase = vbase;
}
while (++j < j0);
f -= j0;
k--;
for (j = 0; j < f; j++)
{
CExtraEntry *e = table++;
e->totalBits = (Byte)(k + extraBits);
e->extraBits = (Byte)extraBits;
e->delta = (UInt16)(j << k);
e->vbase = vbase;
}
}
vbase += ((UInt32)1 << extraBits);
}
}
static const Byte k_L_extra[NUM_L_SYMBOLS] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 5, 8
};
static const Byte k_M_extra[NUM_M_SYMBOLS] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 8, 11
};
static const Byte k_D_extra[NUM_D_SYMBOLS] =
{
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,
8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11,
12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15
};
// ---------- CBitStream ----------
typedef struct
{
UInt32 accum;
unsigned numBits; // [0, 31] - Number of valid bits in (accum), other bits are 0
} CBitStream;
static MY_FORCE_INLINE int FseInStream_Init(CBitStream *s,
int n, // [-7, 0], (-n == number_of_unused_bits) in last byte
const Byte **pbuf)
{
*pbuf -= 4;
s->accum = GetUi32(*pbuf);
if (n)
{
s->numBits = n + 32;
if ((s->accum >> s->numBits) != 0)
return -1; // ERROR, encoder should have zeroed the upper bits
}
else
{
*pbuf += 1;
s->accum >>= 8;
s->numBits = 24;
}
return 0; // OK
}
// 0 <= numBits < 32
#define mask31(x, numBits) ((x) & (((UInt32)1 << (numBits)) - 1))
#define FseInStream_FLUSH \
{ unsigned nbits = (31 - in.numBits) & -8; \
if (nbits) { \
buf -= (nbits >> 3); \
if (buf < buf_check) return S_FALSE; \
UInt32 v = GetUi32(buf); \
in.accum = (in.accum << nbits) | mask31(v, nbits); \
in.numBits += nbits; }}
static MY_FORCE_INLINE UInt32 BitStream_Pull(CBitStream *s, unsigned numBits)
{
s->numBits -= numBits;
UInt32 v = s->accum >> s->numBits;
s->accum = mask31(s->accum, s->numBits);
return v;
}
#define DECODE_LIT(dest, pstate) { \
UInt32 e = lit_decoder[pstate]; \
pstate = (CFseState)((e >> 16) + BitStream_Pull(&in, e & 0xff)); \
dest = (Byte)(e >> 8); }
static MY_FORCE_INLINE UInt32 FseDecodeExtra(CFseState *pstate,
const CExtraEntry *table,
CBitStream *s)
{
const CExtraEntry *e = &table[*pstate];
UInt32 v = BitStream_Pull(s, e->totalBits);
unsigned extraBits = e->extraBits;
*pstate = (CFseState)(e->delta + (v >> extraBits));
return e->vbase + mask31(v, extraBits);
}
#define freqs_L (freqs)
#define freqs_M (freqs_L + NUM_L_SYMBOLS)
#define freqs_D (freqs_M + NUM_M_SYMBOLS)
#define freqs_LIT (freqs_D + NUM_D_SYMBOLS)
#define GET_BITS_64(v, offset, num, dest) dest = (UInt32) ((v >> (offset)) & ((1 << (num)) - 1));
#define GET_BITS_32(v, offset, num, dest) dest = (CFseState)((v >> (offset)) & ((1 << (num)) - 1));
HRESULT CDecoder::DecodeLzfse(UInt32 unpackSize, Byte version)
{
PRF(printf("\nLZFSE-%d %7u", version - '0', unpackSize));
UInt32 numLiterals;
UInt32 litPayloadSize;
Int32 literal_bits;
UInt32 lit_state_0;
UInt32 lit_state_1;
UInt32 lit_state_2;
UInt32 lit_state_3;
UInt32 numMatches;
UInt32 lmdPayloadSize;
Int32 lmd_bits;
CFseState l_state;
CFseState m_state;
CFseState d_state;
UInt16 freqs[NUM_SYMBOLS];
if (version == kSignature_LZFSE_V1)
{
return E_NOTIMPL;
// we need examples to test LZFSE-V1 code
/*
const unsigned k_v1_SubHeaderSize = 7 * 4 + 7 * 2;
const unsigned k_v1_HeaderSize = k_v1_SubHeaderSize + NUM_SYMBOLS * 2;
_buffer.AllocAtLeast(k_v1_HeaderSize);
if (m_InStream.ReadBytes(_buffer, k_v1_HeaderSize) != k_v1_HeaderSize)
return S_FALSE;
const Byte *buf = _buffer;
#define GET_32(offs, dest) dest = GetUi32(buf + offs)
#define GET_16(offs, dest) dest = GetUi16(buf + offs)
UInt32 payload_bytes;
GET_32(0, payload_bytes);
GET_32(4, numLiterals);
GET_32(8, numMatches);
GET_32(12, litPayloadSize);
GET_32(16, lmdPayloadSize);
if (litPayloadSize > (1 << 20) || lmdPayloadSize > (1 << 20))
return S_FALSE;
GET_32(20, literal_bits);
if (literal_bits < -7 || literal_bits > 0)
return S_FALSE;
GET_16(24, lit_state_0);
GET_16(26, lit_state_1);
GET_16(28, lit_state_2);
GET_16(30, lit_state_3);
GET_32(32, lmd_bits);
if (lmd_bits < -7 || lmd_bits > 0)
return S_FALSE;
GET_16(36, l_state);
GET_16(38, m_state);
GET_16(40, d_state);
for (unsigned i = 0; i < NUM_SYMBOLS; i++)
freqs[i] = GetUi16(buf + k_v1_SubHeaderSize + i * 2);
*/
}
else
{
UInt32 headerSize;
{
const unsigned kPreHeaderSize = 4 * 2; // signature and upackSize
const unsigned kHeaderSize = 8 * 3;
Byte temp[kHeaderSize];
if (m_InStream.ReadBytes(temp, kHeaderSize) != kHeaderSize)
return S_FALSE;
UInt64 v;
v = GetUi64(temp);
GET_BITS_64(v, 0, 20, numLiterals);
GET_BITS_64(v, 20, 20, litPayloadSize);
GET_BITS_64(v, 40, 20, numMatches);
GET_BITS_64(v, 60, 3 + 1, literal_bits); // (NumberOfUsedBits - 1)
literal_bits -= 7; // (-NumberOfUnusedBits)
if (literal_bits > 0)
return S_FALSE;
// GET_BITS_64(v, 63, 1, unused);
v = GetUi64(temp + 8);
GET_BITS_64(v, 0, 10, lit_state_0);
GET_BITS_64(v, 10, 10, lit_state_1);
GET_BITS_64(v, 20, 10, lit_state_2);
GET_BITS_64(v, 30, 10, lit_state_3);
GET_BITS_64(v, 40, 20, lmdPayloadSize);
GET_BITS_64(v, 60, 3 + 1, lmd_bits);
lmd_bits -= 7;
if (lmd_bits > 0)
return S_FALSE;
// GET_BITS_64(v, 63, 1, unused)
UInt32 v32 = GetUi32(temp + 20);
// (total header size in bytes; this does not
// correspond to a field in the uncompressed header version,
// but is required; we wouldn't know the size of the
// compresssed header otherwise.
GET_BITS_32(v32, 0, 10, l_state);
GET_BITS_32(v32, 10, 10, m_state);
GET_BITS_32(v32, 20, 10 + 2, d_state);
// GET_BITS_64(v, 62, 2, unused);
headerSize = GetUi32(temp + 16);
if (headerSize <= kPreHeaderSize + kHeaderSize)
return S_FALSE;
headerSize -= kPreHeaderSize + kHeaderSize;
}
// no freqs case is not allowed ?
// memset(freqs, 0, sizeof(freqs));
// if (headerSize != 0)
{
static const Byte numBitsTable[32] =
{
2, 3, 2, 5, 2, 3, 2, 8, 2, 3, 2, 5, 2, 3, 2, 14,
2, 3, 2, 5, 2, 3, 2, 8, 2, 3, 2, 5, 2, 3, 2, 14
};
static const Byte valueTable[32] =
{
0, 2, 1, 4, 0, 3, 1, 8, 0, 2, 1, 5, 0, 3, 1, 24,
0, 2, 1, 6, 0, 3, 1, 8, 0, 2, 1, 7, 0, 3, 1, 24
};
UInt32 accum = 0;
unsigned numBits = 0;
for (unsigned i = 0; i < NUM_SYMBOLS; i++)
{
while (numBits <= 14 && headerSize != 0)
{
Byte b;
if (!m_InStream.ReadByte(b))
return S_FALSE;
accum |= (UInt32)b << numBits;
numBits += 8;
headerSize--;
}
unsigned b = (unsigned)accum & 31;
unsigned n = numBitsTable[b];
if (numBits < n)
return S_FALSE;
numBits -= n;
UInt32 f = valueTable[b];
if (n >= 8)
f += ((accum >> 4) & (0x3ff >> (14 - n)));
accum >>= n;
freqs[i] = (UInt16)f;
}
if (numBits >= 8 || headerSize != 0)
return S_FALSE;
}
}
PRF(printf(" Literals=%6u Matches=%6u", numLiterals, numMatches));
if (numLiterals > LITERALS_PER_BLOCK
|| (numLiterals & 3) != 0
|| numMatches > MATCHES_PER_BLOCK
|| lit_state_0 >= NUM_LIT_STATES
|| lit_state_1 >= NUM_LIT_STATES
|| lit_state_2 >= NUM_LIT_STATES
|| lit_state_3 >= NUM_LIT_STATES
|| l_state >= NUM_L_STATES
|| m_state >= NUM_M_STATES
|| d_state >= NUM_D_STATES)
return S_FALSE;
// only full table is allowed ?
if ( SumFreqs(freqs_L, NUM_L_SYMBOLS) != NUM_L_STATES
|| SumFreqs(freqs_M, NUM_M_SYMBOLS) != NUM_M_STATES
|| SumFreqs(freqs_D, NUM_D_SYMBOLS) != NUM_D_STATES
|| SumFreqs(freqs_LIT, NUM_LIT_SYMBOLS) != NUM_LIT_STATES)
return S_FALSE;
const unsigned kPad = 16;
// ---------- Decode literals ----------
{
_literals.AllocAtLeast(LITERALS_PER_BLOCK + 16);
_buffer.AllocAtLeast(kPad + litPayloadSize);
memset(_buffer, 0, kPad);
if (m_InStream.ReadBytes(_buffer + kPad, litPayloadSize) != litPayloadSize)
return S_FALSE;
UInt32 lit_decoder[NUM_LIT_STATES];
InitLitTable(freqs_LIT, lit_decoder);
const Byte *buf_start = _buffer + kPad;
const Byte *buf_check = buf_start - 4;
const Byte *buf = buf_start + litPayloadSize;
CBitStream in;
if (FseInStream_Init(&in, literal_bits, &buf) != 0)
return S_FALSE;
Byte *lit = _literals;
const Byte *lit_limit = lit + numLiterals;
for (; lit < lit_limit; lit += 4)
{
FseInStream_FLUSH
DECODE_LIT (lit[0], lit_state_0);
DECODE_LIT (lit[1], lit_state_1);
FseInStream_FLUSH
DECODE_LIT (lit[2], lit_state_2);
DECODE_LIT (lit[3], lit_state_3);
}
if ((buf_start - buf) * 8 != (int)in.numBits)
return S_FALSE;
}
// ---------- Decode LMD ----------
_buffer.AllocAtLeast(kPad + lmdPayloadSize);
memset(_buffer, 0, kPad);
if (m_InStream.ReadBytes(_buffer + kPad, lmdPayloadSize) != lmdPayloadSize)
return S_FALSE;
CExtraEntry l_decoder[NUM_L_STATES];
CExtraEntry m_decoder[NUM_M_STATES];
CExtraEntry d_decoder[NUM_D_STATES];
InitExtraDecoderTable(NUM_L_STATES, NUM_L_SYMBOLS, freqs_L, k_L_extra, l_decoder);
InitExtraDecoderTable(NUM_M_STATES, NUM_M_SYMBOLS, freqs_M, k_M_extra, m_decoder);
InitExtraDecoderTable(NUM_D_STATES, NUM_D_SYMBOLS, freqs_D, k_D_extra, d_decoder);
const Byte *buf_start = _buffer + kPad;
const Byte *buf_check = buf_start - 4;
const Byte *buf = buf_start + lmdPayloadSize;
CBitStream in;
if (FseInStream_Init(&in, lmd_bits, &buf))
return S_FALSE;
const Byte *lit = _literals;
const Byte *lit_limit = lit + numLiterals;
UInt32 D = 0;
for (;;)
{
if (numMatches == 0)
break;
numMatches--;
FseInStream_FLUSH
unsigned L = (unsigned)FseDecodeExtra(&l_state, l_decoder, &in);
FseInStream_FLUSH
unsigned M = (unsigned)FseDecodeExtra(&m_state, m_decoder, &in);
FseInStream_FLUSH
{
UInt32 new_D = FseDecodeExtra(&d_state, d_decoder, &in);
if (new_D)
D = new_D;
}
if (L != 0)
{
if (L > (size_t)(lit_limit - lit))
return S_FALSE;
unsigned cur = L;
if (cur > unpackSize)
cur = (unsigned)unpackSize;
m_OutWindowStream.PutBytes(lit, cur);
unpackSize -= cur;
lit += cur;
if (cur != L)
return S_FALSE;
}
if (M != 0)
{
if (unpackSize == 0 || D == 0)
return S_FALSE;
unsigned cur = M;
if (cur > unpackSize)
cur = (unsigned)unpackSize;
if (!m_OutWindowStream.CopyBlock(D - 1, cur))
return S_FALSE;
unpackSize -= cur;
if (cur != M)
return S_FALSE;
}
}
if (unpackSize != 0)
return S_FALSE;
// LZFSE encoder writes 8 additional zero bytes before LMD payload
// We test it:
if ((buf - buf_start) * 8 + in.numBits != 64)
return S_FALSE;
if (GetUi64(buf_start) != 0)
return S_FALSE;
return S_OK;
}
STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
{
PRF(printf("\n\nLzfseDecoder %7u %7u\n", (unsigned)*outSize, (unsigned)*inSize));
const UInt32 kLzfseDictSize = 1 << 18;
if (!m_OutWindowStream.Create(kLzfseDictSize))
return E_OUTOFMEMORY;
if (!m_InStream.Create(1 << 18))
return E_OUTOFMEMORY;
m_OutWindowStream.SetStream(outStream);
m_OutWindowStream.Init(false);
m_InStream.SetStream(inStream);
m_InStream.Init();
CCoderReleaser coderReleaser(this);
UInt64 prevOut = 0;
UInt64 prevIn = 0;
for (;;)
{
const UInt64 pos = m_OutWindowStream.GetProcessedSize();
const UInt64 packPos = m_InStream.GetProcessedSize();
if (progress && ((pos - prevOut) >= (1 << 22) || (packPos - prevIn) >= (1 << 22)))
{
RINOK(progress->SetRatioInfo(&packPos, &pos));
prevIn = packPos;
prevOut = pos;
}
const UInt64 rem = *outSize - pos;
UInt32 v;
RINOK(GetUInt32(v))
if ((v & 0xFFFFFF) != 0x787662) // bvx
return S_FALSE;
v >>= 24;
if (v == 0x24) // '$', end of stream
break;
UInt32 unpackSize;
RINOK(GetUInt32(unpackSize));
UInt32 cur = unpackSize;
if (cur > rem)
cur = (UInt32)rem;
unpackSize -= cur;
HRESULT res;
if (v == kSignature_LZFSE_V1 || v == kSignature_LZFSE_V2)
res = DecodeLzfse(cur, (Byte)v);
else if (v == 0x6E) // 'n'
res = DecodeLzvn(cur);
else if (v == 0x2D) // '-'
res = DecodeUncompressed(cur);
else
return E_NOTIMPL;
if (res != S_OK)
return res;
if (unpackSize != 0)
return S_FALSE;
}
coderReleaser.NeedFlush = false;
HRESULT res = m_OutWindowStream.Flush();
if (res == S_OK)
if (*inSize != m_InStream.GetProcessedSize()
|| *outSize != m_OutWindowStream.GetProcessedSize())
res = S_FALSE;
return res;
}
STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
{
try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
catch(const CInBufferException &e) { return e.ErrorCode; }
catch(const CLzOutWindowException &e) { return e.ErrorCode; }
catch(...) { return E_OUTOFMEMORY; }
// catch(...) { return S_FALSE; }
}
}}
| 11,272 |
589 | package rocks.inspectit.agent.java.core.disruptor.impl;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired;
import rocks.inspectit.agent.java.config.IConfigurationStorage;
import rocks.inspectit.agent.java.core.disruptor.IDisruptorStrategy;
/**
* Default strategy for configuring the disruptor. Holds the buffer size of disruptor.
*
* @author <NAME>
*
*/
public class DefaultDisruptorStrategy implements IDisruptorStrategy {
/**
* Configuration storage to read properties from.
*/
@Autowired
private IConfigurationStorage configurationStorage;
/**
* Size of the buffer.
*/
private int dataBufferSize;
/**
* {@inheritDoc}
*/
@Override
public int getDataBufferSize() {
return dataBufferSize;
}
/**
* Reads settings from the {@link #configurationStorage}. Should be called only after
* initialized as bean.
*
* @throws Exception
* If disruptor config can not be read from the {@link #configurationStorage} or
* settings don't contain the <i>bufferSize</i> property.
*/
@PostConstruct
protected void postConstruct() throws Exception {
Map<String, String> settings = configurationStorage.getDisruptorStrategyConfig().getSettings();
if (settings.containsKey("bufferSize")) {
this.dataBufferSize = Integer.parseInt(settings.get("bufferSize"));
} else {
throw new BeanInitializationException("Disruptor strategy can not be initialized without the buffer size property.");
}
}
}
| 501 |
10,608 | <gh_stars>1000+
""" Official evaluation script for CUAD dataset. """
import argparse
import json
import re
import string
import sys
import numpy as np
IOU_THRESH = 0.5
def get_jaccard(prediction, ground_truth):
remove_tokens = [".", ",", ";", ":"]
for token in remove_tokens:
ground_truth = ground_truth.replace(token, "")
prediction = prediction.replace(token, "")
ground_truth, prediction = ground_truth.lower(), prediction.lower()
ground_truth, prediction = ground_truth.replace("/", " "), prediction.replace("/", " ")
ground_truth, prediction = set(ground_truth.split(" ")), set(prediction.split(" "))
intersection = ground_truth.intersection(prediction)
union = ground_truth.union(prediction)
jaccard = len(intersection) / len(union)
return jaccard
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re.sub(r"\b(a|an|the)\b", " ", text)
def white_space_fix(text):
return " ".join(text.split())
def remove_punc(text):
exclude = set(string.punctuation)
return "".join(ch for ch in text if ch not in exclude)
def lower(text):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(s))))
def compute_precision_recall(predictions, ground_truths, qa_id):
tp, fp, fn = 0, 0, 0
substr_ok = "Parties" in qa_id
# first check if ground truth is empty
if len(ground_truths) == 0:
if len(predictions) > 0:
fp += len(predictions) # false positive for each one
else:
for ground_truth in ground_truths:
assert len(ground_truth) > 0
# check if there is a match
match_found = False
for pred in predictions:
if substr_ok:
is_match = get_jaccard(pred, ground_truth) >= IOU_THRESH or ground_truth in pred
else:
is_match = get_jaccard(pred, ground_truth) >= IOU_THRESH
if is_match:
match_found = True
if match_found:
tp += 1
else:
fn += 1
# now also get any fps by looping through preds
for pred in predictions:
# Check if there's a match. if so, don't count (don't want to double count based on the above)
# but if there's no match, then this is a false positive.
# (Note: we get the true positives in the above loop instead of this loop so that we don't double count
# multiple predictions that are matched with the same answer.)
match_found = False
for ground_truth in ground_truths:
assert len(ground_truth) > 0
if substr_ok:
is_match = get_jaccard(pred, ground_truth) >= IOU_THRESH or ground_truth in pred
else:
is_match = get_jaccard(pred, ground_truth) >= IOU_THRESH
if is_match:
match_found = True
if not match_found:
fp += 1
precision = tp / (tp + fp) if tp + fp > 0 else np.nan
recall = tp / (tp + fn) if tp + fn > 0 else np.nan
return precision, recall
def process_precisions(precisions):
"""
Processes precisions to ensure that precision and recall don't both get worse.
Assumes the list precision is sorted in order of recalls
"""
precision_best = precisions[::-1]
for i in range(1, len(precision_best)):
precision_best[i] = max(precision_best[i - 1], precision_best[i])
precisions = precision_best[::-1]
return precisions
def get_aupr(precisions, recalls):
processed_precisions = process_precisions(precisions)
aupr = np.trapz(processed_precisions, recalls)
if np.isnan(aupr):
return 0
return aupr
def get_prec_at_recall(precisions, recalls, recall_thresh):
"""Assumes recalls are sorted in increasing order"""
processed_precisions = process_precisions(precisions)
prec_at_recall = 0
for prec, recall in zip(processed_precisions, recalls):
if recall >= recall_thresh:
prec_at_recall = prec
break
return prec_at_recall
def exact_match_score(prediction, ground_truth):
return normalize_answer(prediction) == normalize_answer(ground_truth)
def metric_max_over_ground_truths(metric_fn, predictions, ground_truths):
score = 0
for pred in predictions:
for ground_truth in ground_truths:
score = metric_fn(pred, ground_truth)
if score == 1: # break the loop when one prediction matches the ground truth
break
if score == 1:
break
return score
def evaluate(dataset, predictions):
f1 = exact_match = total = 0
precisions = []
recalls = []
for article in dataset:
for paragraph in article["paragraphs"]:
for qa in paragraph["qas"]:
total += 1
if qa["id"] not in predictions:
message = "Unanswered question " + qa["id"] + " will receive score 0."
print(message, file=sys.stderr)
continue
ground_truths = list(map(lambda x: x["text"], qa["answers"]))
prediction = predictions[qa["id"]]
precision, recall = compute_precision_recall(prediction, ground_truths, qa["id"])
precisions.append(precision)
recalls.append(recall)
if precision == 0 and recall == 0:
f1 += 0
else:
f1 += 2 * (precision * recall) / (precision + recall)
exact_match += metric_max_over_ground_truths(exact_match_score, prediction, ground_truths)
precisions = [x for _, x in sorted(zip(recalls, precisions))]
recalls.sort()
f1 = 100.0 * f1 / total
exact_match = 100.0 * exact_match / total
aupr = get_aupr(precisions, recalls)
prec_at_90_recall = get_prec_at_recall(precisions, recalls, recall_thresh=0.9)
prec_at_80_recall = get_prec_at_recall(precisions, recalls, recall_thresh=0.8)
return {
"exact_match": exact_match,
"f1": f1,
"aupr": aupr,
"prec_at_80_recall": prec_at_80_recall,
"prec_at_90_recall": prec_at_90_recall,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Evaluation for CUAD")
parser.add_argument("dataset_file", help="Dataset file")
parser.add_argument("prediction_file", help="Prediction File")
args = parser.parse_args()
with open(args.dataset_file) as dataset_file:
dataset_json = json.load(dataset_file)
dataset = dataset_json["data"]
with open(args.prediction_file) as prediction_file:
predictions = json.load(prediction_file)
print(json.dumps(evaluate(dataset, predictions)))
| 3,046 |
537 | <gh_stars>100-1000
/*!
* @file
* Casting strings to tuples of primitive types including std::array.
*
* This file is a part of easyLambda(ezl) project for parallel data
* processing with modern C++ and MPI.
*
* @copyright <NAME> <<EMAIL>> 2015-2016
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying LICENSE.md or copy at * http://boost.org/LICENSE_1_0.txt)
* */
#ifndef LEXCASTTUPLE_EZL_H
#define LEXCASTTUPLE_EZL_H
#include <string>
#include <vector>
#include <boost/lexical_cast.hpp> // compile time increase by 2 secs!
namespace ezl {
namespace detail {
namespace meta {
// converts string values into tuple, uses boost-lexical
// throws exception boost::bad_lexical_cast if string can not be converted to
// the tuple datatype. std::array of some type is also supported.
// Used struct because a function will require enable if which is kind of
// equally complicated.
template <size_t I, class Tup, class T>
struct LexCastImpl {
LexCastImpl(std::vector<std::string>::iterator& it, Tup &out, bool strict) {
using T2 = typename std::remove_reference<T>::type;
--it;
if (!strict && *it == "") {
std::get<I>(out) = T2();
} else {
std::get<I>(out) = boost::lexical_cast<T2>(*it);
}
LexCastImpl<I - 1, Tup, std::tuple_element_t<I - 1, Tup>>(it, out, strict);
}
};
template <size_t I, class Tup, class T, size_t N>
struct LexCastImpl<I, Tup, std::array<T,N>> {
LexCastImpl(std::vector<std::string>::iterator &it, Tup &out, bool strict) {
using T2 = typename std::remove_reference<T>::type;
for(auto i = int(N-1); i >= 0; i--) {
--it;
if (!strict && *it == "") {
std::get<I>(out)[i] = T2();
} else {
std::get<I>(out)[i] = boost::lexical_cast<T2>(*it);
}
}
LexCastImpl<I - 1, Tup, std::tuple_element_t<I - 1, Tup>>(it, out, strict);
}
};
template <class Tup, class T, size_t N>
struct LexCastImpl<0, Tup, std::array<T, N>> {
LexCastImpl(std::vector<std::string>::iterator &it, Tup& out, bool strict) {
using T2 = typename std::remove_reference<T>::type;
for(auto i = int(N-1); i >= 0; i--) {
--it;
if (!strict && *it == "") {
std::get<0>(out)[i] = T2();
} else {
std::get<0>(out)[i] = boost::lexical_cast<T2>(*it);
}
}
}
};
template <class Tup, class T>
struct LexCastImpl<0, Tup, T> {
LexCastImpl(std::vector<std::string>::iterator &it, Tup &out, bool strict) {
using T2 = typename std::remove_reference<T>::type;
--it;
if (!strict && *it == "") {
std::get<0>(out) = T2();
} else {
std::get<0>(out) = boost::lexical_cast<T2>(*it); // TODO: catch
}
}
};
// wrapper functions for string tuple conversion
template <class Tup>
void lexCastTuple(std::vector<std::string> &vstr, Tup &out, bool strict = true) {
constexpr auto tupSize = std::tuple_size<Tup>::value - 1;
auto it = std::end(vstr);
LexCastImpl<tupSize, Tup, std::tuple_element_t<tupSize, Tup>>(it, out, strict);
};
} // namespace meta
} // namespace detail
} // namespace ezl
#endif // _LEXCASTTUPLE_EZL_H__
| 1,253 |
423 | <reponame>karanjot21/meter
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.androidexperiments.meter;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ToggleButton;
import android.widget.TextView;
import com.androidexperiments.meter.fonts.RobotoBoldTypeface;
import com.androidexperiments.meter.fonts.RobotoLightTypeface;
/**
* The Main app activity, describes the wallpaper and directs user towards notification settings
*/
public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = MainActivity.class.getSimpleName();
protected SharedPreferences mSettings;
protected ToggleButton mWifiEnabled;
protected ToggleButton mBatteryEnabled;
protected ToggleButton mNotificationsEnabled;
protected Button mSetWallpaperBtn;
/**
* the click listener for all drawers buttons
*/
protected View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//if none of the buttons are on, this one must stay on
if (!anyChecked()) {
((ToggleButton)v).setChecked(true);
}
}
};
/**
* are any of the ToggleButtons currently checked?
*/
protected boolean anyChecked() {
ToggleButton[] btns = {mWifiEnabled, mBatteryEnabled, mNotificationsEnabled};
for (ToggleButton btn : btns) {
if (btn.isChecked()) {
return true;
}
}
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//grab button references
mWifiEnabled = (ToggleButton) findViewById(R.id.wifiEnableButton);
mBatteryEnabled = (ToggleButton) findViewById(R.id.batteryEnableButton);
mNotificationsEnabled = (ToggleButton) findViewById(R.id.notificationsEnableButton);
mSetWallpaperBtn = (Button) findViewById(R.id.choseWallpaperButton);
Typeface robotoLight = RobotoLightTypeface.getInstance(this);
Typeface robotoBold = RobotoBoldTypeface.getInstance(this);
mSetWallpaperBtn.setTypeface(robotoBold);
//grab shared preferences
mSettings = getSharedPreferences(WallpaperPreferences.PREFERENCES, MODE_PRIVATE);
((TextView)findViewById(R.id.descriptionTextView)).setTypeface(robotoLight);
//set listeners
mWifiEnabled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//use the basic one as well
mOnClickListener.onClick(v);
checkLocationPermission();
}
});
mBatteryEnabled.setOnClickListener(mOnClickListener);
mNotificationsEnabled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//use the basic one as well
mOnClickListener.onClick(v);
if (mNotificationsEnabled.isChecked() && !NotificationService.permissionsGranted) {
showNotificationPermissionAlert();
}
}
});
mSetWallpaperBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER);
startActivity(intent);
}
});
}
@Override
public void onResume() {
super.onResume();
updateGUI();
if (!isNotificationServiceRunning()) {
mNotificationsEnabled.setChecked(false);
}
this.checkLocationPermission();
//in the case where notifications was the only one selected
//and its permissions were revoked, turn back on WiFi
if (!anyChecked()) {
mBatteryEnabled.setChecked(true);
}
}
@Override
public void onPause() {
super.onPause();
this.updateSettings();
}
private void updateSettings(){
//update the shared preferences
SharedPreferences.Editor editor = mSettings.edit();
editor.putBoolean("wifi", mWifiEnabled.isChecked());
editor.putBoolean("battery", mBatteryEnabled.isChecked());
editor.putBoolean("notifications", mNotificationsEnabled.isChecked());
editor.apply();
}
private void checkLocationPermission(){
if(mWifiEnabled.isChecked()) {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
0);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)){
if(grantResults[0] == PackageManager.PERMISSION_DENIED ){
mWifiEnabled.setChecked(false);
this.updateSettings();
}
}
}
private void showNotificationPermissionAlert() {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setMessage(getString(R.string.notification_permission));
alertBuilder
.setCancelable(false)
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
moveToNotificationListenerSettings();
}
})
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mNotificationsEnabled.setChecked(false);
}
});
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}
private boolean isNotificationServiceRunning() {
ContentResolver resolver = getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(resolver, "enabled_notification_listeners");
String packageName = getPackageName();
return enabledNotificationListeners != null && enabledNotificationListeners.contains(packageName);
}
private void updateGUI() {
mWifiEnabled.setChecked(mSettings.getBoolean(WallpaperPreferences.WIFI_CELLULAR, false));
mBatteryEnabled.setChecked(mSettings.getBoolean(WallpaperPreferences.BATTERY, true));
mNotificationsEnabled.setChecked(mSettings.getBoolean(WallpaperPreferences.NOTIFICATIONS, false));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.open_settings:
moveToNotificationListenerSettings();
break;
case R.id.about:
moveToAbout();
break;
case R.id.licenses:
default:
moveToLicenses();
}
return true;
}
/**
* go to the OS-level notification listener settings
*/
private void moveToNotificationListenerSettings() {
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
startActivity(intent);
}
}
/**
* go to the about section
*/
private void moveToAbout() {
Intent intent = new Intent(this, LocalWebActivity.class);
intent.putExtra(LocalWebActivity.EXTRA_HTML_URI, "html/about.html");
startActivity(intent);
}
/**
* go to the licenses section
*/
private void moveToLicenses() {
//go to Licenses html here
Intent intent = new Intent(this, LocalWebActivity.class);
intent.putExtra(LocalWebActivity.EXTRA_HTML_URI, "html/licenses.html");
startActivity(intent);
}
}
| 4,164 |
1,006 | /****************************************************************************
* arch/arm/src/phy62xx/bus_dev.h
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Filename: bus_dev.h
* Revised:
* Revision:
*
* Description: This file contains the SoC MCU relate definitions
*
****************************************************************************/
#ifndef __BUS_DEV_H__
#define __BUS_DEV_H__
#ifdef __cplusplus
extern "C"
{
#endif
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/irq.h>
#include <nuttx/arch.h>
#include <arch/irq.h>
#include "mcu.h"
#define PHY_MCU_TYPE MCU_BUMBEE_M0
enum
{
RSTC_COLD_UP = 0,
RSTC_WARM_UP = 1,
RSTC_OFF_MODE = 2,
RSTC_WAKE_IO = 3,
RSTC_WAKE_RTC = 4,
RSTC_WARM_NDWC = 5 /* user mode, no dwc */
};
/* ---- Interrupt Number Definition ---- */
typedef enum IRQn
{
/* ---- Cortex-M0 Processor Exceptions Numbers ---- */
NonMaskableInt_IRQn = -14, /* 2 Non Maskable Interrupt */
HardFault_IRQn = -13, /* 3 HardFault Interrupt */
SVCall_IRQn = -5, /* 11 SV Call Interrupt */
PendSV_IRQn = -2, /* 14 Pend SV Interrupt */
SysTick_IRQn = -1, /* 15 System Tick Interrupt */
/* ---- PHY BUMBEE M0 Interrupt Numbers ---- */
BB_IRQn = 4, /* Base band Interrupt */
KSCAN_IRQn = 5, /* Key scan Interrupt */
RTC_IRQn = 6, /* RTC Timer Interrupt */
WDT_IRQn = 10, /* Watchdog Timer Interrupt */
UART0_IRQn = 11, /* UART0 Interrupt */
I2C0_IRQn = 12, /* I2C0 Interrupt */
I2C1_IRQn = 13, /* I2C1 Interrupt */
SPI0_IRQn = 14, /* SPI0 Interrupt */
SPI1_IRQn = 15, /* SPI1 Interrupt */
GPIO_IRQn = 16, /* GPIO Interrupt */
UART1_IRQn = 17, /* UART1 Interrupt */
SPIF_IRQn = 18, /* SPIF Interrupt */
DMAC_IRQn = 19, /* DMAC Interrupt */
TIM1_IRQn = 20, /* Timer1 Interrupt */
TIM2_IRQn = 21, /* Timer2 Interrupt */
TIM3_IRQn = 22, /* Timer3 Interrupt */
TIM4_IRQn = 23, /* Timer4 Interrupt */
TIM5_IRQn = 24, /* Timer5 Interrupt */
TIM6_IRQn = 25, /* Timer6 Interrupt */
AES_IRQn = 28, /* AES Interrupt */
ADCC_IRQn = 29, /* ADC Interrupt */
QDEC_IRQn = 30, /* QDEC Interrupt */
RNG_IRQn = 31, /* RNG Interrupt */
} IRQn_Type;
#ifdef __cplusplus
#define __I volatile /* < Defines 'read only' permissions */
#else
#define __I volatile const /* < Defines 'read only' permissions */
#endif
#define __O volatile /* < Defines 'write only' permissions */
#define __IO volatile /* < Defines 'read / write' permissions */
/* following defines should be used for structure members */
#define __IM volatile const /* Defines 'read only' structure member permissions */
#define __OM volatile /* Defines 'write only' structure member permissions */
#define __IOM volatile /* Defines 'read / write' structure member permissions */
#define NVIC_DisableIRQ(irqid) up_disable_irq(irqid)
#define NVIC_EnableIRQ(irqid) up_enable_irq(irqid)
#define NVIC_SetPriority(i,p)
#if 0
#if (PHY_MCU_TYPE == MCU_BUMBEE_M0)
#define ATTRIBUTE_ISR
#include "core_bumbee_m0.h"
#endif
#if(PHY_MCU_TYPE == MCU_BUMBEE_CK802)
#define ATTRIBUTE_ISR __attribute__((isr))
#include "core_802.h"
#endif
#endif //0
#if (PHY_MCU_TYPE == MCU_BUMBEE_M0 || PHY_MCU_TYPE == MCU_BUMBEE_CK802)
#include "mcu_phy_bumbee.h"
#elif ((PHY_MCU_TYPE == MCU_PRIME_A1) ||(PHY_MCU_TYPE == MCU_PRIME_A2))
#include "mcu_phy_prime.h"
#endif
#endif
| 2,442 |
5,250 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.cmmn.converter.export;
import javax.xml.stream.XMLStreamWriter;
import org.flowable.cmmn.model.CmmnModel;
import org.flowable.cmmn.model.PlanFragment;
import org.flowable.cmmn.model.PlanItem;
import org.flowable.cmmn.model.Sentry;
/**
* @author <NAME>
*/
public class PlanFragmentExport extends AbstractPlanItemDefinitionExport<PlanFragment> {
private static final PlanFragmentExport instance = new PlanFragmentExport();
public static PlanFragmentExport getInstance() {
return instance;
}
private PlanFragmentExport() {
}
@Override
protected Class<PlanFragment> getExportablePlanItemDefinitionClass() {
return PlanFragment.class;
}
@Override
protected String getPlanItemDefinitionXmlElementValue(PlanFragment planFragment) {
return ELEMENT_PLAN_FRAGMENT;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(PlanFragment planFragment, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(planFragment, xtw);
}
@Override
protected void writePlanItemDefinitionBody(CmmnModel model, PlanFragment planFragment, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionBody(model, planFragment, xtw);
for (PlanItem planItem : planFragment.getPlanItems()) {
PlanItemExport.writePlanItem(model, planItem, xtw);
}
for (Sentry sentry : planFragment.getSentries()) {
SentryExport.writeSentry(model, sentry, xtw);
}
}
}
| 703 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.loganalytics.models;
import com.azure.resourcemanager.loganalytics.fluent.models.AvailableServiceTierInner;
/** An immutable client-side representation of AvailableServiceTier. */
public interface AvailableServiceTier {
/**
* Gets the serviceTier property: The name of the Service Tier.
*
* @return the serviceTier value.
*/
SkuNameEnum serviceTier();
/**
* Gets the enabled property: True if the Service Tier is enabled for the workspace.
*
* @return the enabled value.
*/
Boolean enabled();
/**
* Gets the minimumRetention property: The minimum retention for the Service Tier, in days.
*
* @return the minimumRetention value.
*/
Long minimumRetention();
/**
* Gets the maximumRetention property: The maximum retention for the Service Tier, in days.
*
* @return the maximumRetention value.
*/
Long maximumRetention();
/**
* Gets the defaultRetention property: The default retention for the Service Tier, in days.
*
* @return the defaultRetention value.
*/
Long defaultRetention();
/**
* Gets the capacityReservationLevel property: The capacity reservation level in GB per day. Returned for the
* Capacity Reservation Service Tier.
*
* @return the capacityReservationLevel value.
*/
Long capacityReservationLevel();
/**
* Gets the lastSkuUpdate property: Time when the sku was last updated for the workspace. Returned for the Capacity
* Reservation Service Tier.
*
* @return the lastSkuUpdate value.
*/
String lastSkuUpdate();
/**
* Gets the inner com.azure.resourcemanager.loganalytics.fluent.models.AvailableServiceTierInner object.
*
* @return the inner object.
*/
AvailableServiceTierInner innerModel();
}
| 652 |
490 | #include <Halide.h>
#include "align.h"
#include "merge.h"
#include "finish.h"
namespace {
class HdrPlusPipeline : public Halide::Generator<HdrPlusPipeline> {
public:
// 'inputs' is really a series of raw 2d frames; extent[2] specifies the count
Input<Halide::Buffer<uint16_t>> inputs{"inputs", 3};
Input<uint16_t> black_point{"black_point"};
Input<uint16_t> white_point{"white_point"};
Input<float> white_balance_r{"white_balance_r"};
Input<float> white_balance_g0{"white_balance_g0"};
Input<float> white_balance_g1{"white_balance_g1"};
Input<float> white_balance_b{"white_balance_b"};
Input<int> cfa_pattern{"cfa_pattern"};
Input<Halide::Buffer<float>> ccm{"ccm", 2}; // ccm - color correction matrix
Input<float> compression{"compression"};
Input<float> gain{"gain"};
// RGB output
Output<Halide::Buffer<uint8_t>> output{"output", 3};
void generate() {
// Algorithm
Func alignment = align(inputs, inputs.width(), inputs.height());
Func merged = merge(inputs, inputs.width(), inputs.height(), inputs.dim(2).extent(), alignment);
CompiletimeWhiteBalance wb{ white_balance_r, white_balance_g0, white_balance_g1, white_balance_b };
Func finished = finish(merged, inputs.width(), inputs.height(), black_point, white_point, wb, cfa_pattern, ccm, compression, gain);
output = finished;
// Schedule handled inside included functions
}
};
} // namespace
HALIDE_REGISTER_GENERATOR(HdrPlusPipeline, hdrplus_pipeline)
| 695 |
310 | <reponame>dreeves/usesthis
{
"name": "Lifetime Folding Chair",
"description": "A folding chair.",
"url": "https://www.costco.com/Lifetime-Folding-Chair%2C-4-pack.product.11482116.html"
}
| 79 |
585 | <reponame>jinwyp/image-background-remove-tool
"""
Name: Pre-processing class file
Description: This file contains pre-processing classes.
Version: [release][3.2]
Source url: https://github.com/OPHoperHPO/image-background-remove-tool
Author: Anodev (OPHoperHPO)[https://github.com/OPHoperHPO] .
License: Apache License 2.0
License:
Copyright 2020 OPHoperHPO
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import time
import numpy as np
from PIL import Image
from libs.strings import PREPROCESS_METHODS
logger = logging.getLogger(__name__)
def method_detect(method: str):
"""Detects which method to use and returns its object"""
if method in PREPROCESS_METHODS:
if method == "bbmd-maskrcnn":
return BoundingBoxDetectionWithMaskMaskRcnn()
elif method == "bbd-fastrcnn":
return BoundingBoxDetectionFastRcnn()
else:
return None
else:
return False
class BoundingBoxDetectionFastRcnn:
"""
Class for the image preprocessing method.
This image pre-processing technique uses two neural networks ($used_model and Fast RCNN)
to first detect the boundaries of objects in a photograph,
cut them out, sequentially remove the background from each object in turn
and subsequently collect the entire image from separate parts
"""
def __init__(self):
self.__fast_rcnn__ = FastRcnn()
self.model = None
self.prep_image = None
self.orig_image = None
@staticmethod
def trans_paste(bg_img, fg_img, box=(0, 0)):
"""
Inserts an image into another image while maintaining transparency.
:param bg_img: Background pil image
:param fg_img: Foreground pil image
:param box: Bounding box
:return: Pil Image
"""
fg_img_trans = Image.new("RGBA", bg_img.size)
fg_img_trans.paste(fg_img, box, mask=fg_img)
new_img = Image.alpha_composite(bg_img, fg_img_trans)
return new_img
@staticmethod
def __orig_object_border__(border, orig_image, resized_image, indent=16):
"""
Rescales the bounding box of an object
:param indent: The boundary of the object will expand by this value.
:param border: array consisting of the coordinates of the boundaries of the object
:param orig_image: original pil image
:param resized_image: resized image ndarray
:return: tuple consisting of the coordinates of the boundaries of the object
"""
x_factor = resized_image.shape[1] / orig_image.size[0]
y_factor = resized_image.shape[0] / orig_image.size[1]
xmin, ymin, xmax, ymax = [int(x) for x in border]
if ymin < 0:
ymin = 0
if ymax > resized_image.shape[0]:
ymax = resized_image.shape[0]
if xmax > resized_image.shape[1]:
xmax = resized_image.shape[1]
if xmin < 0:
xmin = 0
if x_factor == 0:
x_factor = 1
if y_factor == 0:
y_factor = 1
border = (int(xmin / x_factor) - indent,
int(ymin / y_factor) - indent, int(xmax / x_factor) + indent, int(ymax / y_factor) + indent)
return border
def run(self, model, prep_image, orig_image):
"""
Runs an image preprocessing algorithm to improve background removal quality.
:param model: The class of the neural network used to remove the background.
:param prep_image: Prepared for the neural network image
:param orig_image: Source image
:returns: Image without background
"""
_, resized_image, results = self.__fast_rcnn__.process_image(orig_image)
classes = self.__fast_rcnn__.class_names
bboxes = results['bboxes']
ids = results['ids']
scores = results['scores']
object_num = len(bboxes) # We get the number of all objects in the photo
if object_num < 1: # If there are no objects, or they are not found,
# we try to remove the background using standard tools
return model.__get_output__(prep_image, orig_image)
else:
# Check that all arrays match each other in size
if ids is not None and not len(bboxes) == len(ids):
return model.__get_output__(prep_image,
orig_image) # we try to remove the background using standard tools
if scores is not None and not len(bboxes) == len(scores):
return model.__get_output__(prep_image, orig_image)
# we try to remove the background using standard tools
objects = []
for i, bbox in enumerate(bboxes):
if scores is not None and scores.flat[i] < 0.5:
continue
if ids is not None and ids.flat[i] < 0:
continue
object_cls_id = int(ids.flat[i]) if ids is not None else -1
if classes is not None and object_cls_id < len(classes):
object_label = classes[object_cls_id]
else:
object_label = str(object_cls_id) if object_cls_id >= 0 else ''
object_border = self.__orig_object_border__(bbox, orig_image, resized_image)
objects.append([object_label, object_border])
if objects:
if len(objects) == 1:
return model.__get_output__(prep_image, orig_image)
# we try to remove the background using standard tools
else:
obj_images = []
for obj in objects:
border = obj[1]
obj_crop = orig_image.crop(border)
# TODO: make a special algorithm to improve the removal of background from images with people.
if obj[0] == "person":
obj_img = model.process_image(obj_crop)
else:
obj_img = model.process_image(obj_crop)
obj_images.append([obj_img, obj])
image = Image.new("RGBA", orig_image.size)
for obj in obj_images:
image = self.trans_paste(image, obj[0], obj[1][1])
return image
else:
return model.__get_output__(prep_image, orig_image)
class BoundingBoxDetectionWithMaskMaskRcnn:
"""
Class for the image preprocessing method.
This image pre-processing technique uses two neural networks
to first detect the boundaries and masks of objects in a photograph,
cut them out, expand the masks by a certain number of pixels,
apply them and remove the background from each object in turn
and subsequently collect the entire image from separate parts
"""
def __init__(self):
self.__mask_rcnn__ = MaskRcnn()
self.model = None
self.prep_image = None
self.orig_image = None
@staticmethod
def __mask_extend__(mask, indent=10):
"""
Extends the mask of an object.
:param mask: 8-bit ndarray mask
:param indent: Indent on which to expand the mask
:return: extended 8-bit mask ndarray
"""
# TODO: Rewrite this function.
height, weight = mask.shape
old_val = 0
for h in range(height):
for w in range(weight):
val = mask[h, w]
if val == 1 and old_val == 0:
for i in range(1, indent + 1):
if w - i > 0:
mask[h, w - i] = 1
old_val = val
elif val == 0 and old_val == 1:
if weight - w >= indent:
for i in range(0, indent):
mask[h, w + i] = 1
else:
for i in range(0, weight - w):
mask[h, w + i] = 1
old_val = val
break
return mask
@staticmethod
def trans_paste(bg_img, fg_img, box=(0, 0)):
"""
Inserts an image into another image while maintaining transparency.
:param bg_img: Background pil image
:param fg_img: Foreground pil image
:param box: Bounding box
:return: Pil Image
"""
fg_img_trans = Image.new("RGBA", bg_img.size)
fg_img_trans.paste(fg_img, box, mask=fg_img)
new_img = Image.alpha_composite(bg_img, fg_img_trans)
return new_img
@staticmethod
def __orig_object_border__(border, orig_image, resized_image, indent=16):
"""
Rescales the bounding box of an object
:param indent: The boundary of the object will expand by this value.
:param border: array consisting of the coordinates of the boundaries of the object
:param orig_image: original pil image
:param resized_image: resized image ndarray
:return: tuple consisting of the coordinates of the boundaries of the object
"""
x_factor = resized_image.shape[1] / orig_image.size[0]
y_factor = resized_image.shape[0] / orig_image.size[1]
xmin, ymin, xmax, ymax = [int(x) for x in border]
if ymin < 0:
ymin = 0
if ymax > resized_image.shape[0]:
ymax = resized_image.shape[0]
if xmax > resized_image.shape[1]:
xmax = resized_image.shape[1]
if xmin < 0:
xmin = 0
if x_factor == 0:
x_factor = 1
if y_factor == 0:
y_factor = 1
border = (int(xmin / x_factor) - indent,
int(ymin / y_factor) - indent,
int(xmax / x_factor) + indent,
int(ymax / y_factor) + indent)
return border
@staticmethod
def __apply_mask__(image, mask):
"""
Applies a mask to an image.
:param image: Pil image
:param mask: 8 bit Mask ndarray
:return: Pil Image
"""
image = np.array(image)
image[:, :, 0] = np.where(
mask == 0,
255,
image[:, :, 0]
)
image[:, :, 1] = np.where(
mask == 0,
255,
image[:, :, 1]
)
image[:, :, 2] = np.where(
mask == 0,
255,
image[:, :, 2]
)
return Image.fromarray(image)
def run(self, model, prep_image, orig_image):
"""
Runs an image preprocessing algorithm to improve background removal quality.
:param model: The class of the neural network used to remove the background.
:param prep_image: Prepared for the neural network image
:param orig_image: Source image
:return: Image without background
"""
_, resized_image, results = self.__mask_rcnn__.process_image(orig_image)
classes = self.__mask_rcnn__.class_names
bboxes = results['bboxes']
masks = results['masks']
ids = results['ids']
scores = results['scores']
object_num = len(bboxes) # We get the number of all objects in the photo
if object_num < 1: # If there are no objects, or they are not found,
# we try to remove the background using standard tools
return model.__get_output__(prep_image, orig_image)
else:
# Check that all arrays match each other in size
if ids is not None and not len(bboxes) == len(ids):
return model.__get_output__(prep_image,
orig_image) # we try to remove the background using standard tools
if scores is not None and not len(bboxes) == len(scores):
return model.__get_output__(prep_image, orig_image)
# we try to remove the background using standard tools
objects = []
for i, bbox in enumerate(bboxes):
if scores is not None and scores.flat[i] < 0.5:
continue
if ids is not None and ids.flat[i] < 0:
continue
object_cls_id = int(ids.flat[i]) if ids is not None else -1
if classes is not None and object_cls_id < len(classes):
object_label = classes[object_cls_id]
else:
object_label = str(object_cls_id) if object_cls_id >= 0 else ''
object_border = self.__orig_object_border__(bbox, orig_image, resized_image)
object_mask = masks[i, :, :]
objects.append([object_label, object_border, object_mask])
if objects:
if len(objects) == 1:
return model.__get_output__(prep_image, orig_image)
# we try to remove the background using standard tools
else:
obj_images = []
for obj in objects:
extended_mask = self.__mask_extend__(obj[2])
obj_masked = self.__apply_mask__(orig_image, extended_mask)
border = obj[1]
obj_crop_masked = obj_masked.crop(border)
# TODO: make a special algorithm to improve the removal of background from images with people.
if obj[0] == "person":
obj_img = model.process_image(obj_crop_masked)
else:
obj_img = model.process_image(obj_crop_masked)
obj_images.append([obj_img, obj])
image = Image.new("RGBA", orig_image.size)
for obj in obj_images:
image = self.trans_paste(image, obj[0], obj[1][1])
return image
else:
return model.__get_output__(prep_image, orig_image)
class FastRcnn:
"""
Fast Rcnn Neural Network to detect objects in the photo.
"""
def __init__(self):
from gluoncv import model_zoo, data
from mxnet import nd
self.model_zoo = model_zoo
self.data = data
self.nd = nd
logger.debug("Loading Fast RCNN neural network")
self.__net__ = self.model_zoo.get_model('faster_rcnn_resnet50_v1b_voc',
pretrained=True) # Download the pre-trained model, if one is missing.
# noinspection PyUnresolvedReferences
self.class_names = self.__net__.classes
def __load_image__(self, data_input):
"""
Loads an image file for other processing
:param data_input: Path to image file or PIL image
:return: image
"""
if isinstance(data_input, str):
try:
data_input = Image.open(data_input)
# Fix https://github.com/OPHoperHPO/image-background-remove-tool/issues/19
data_input = data_input.convert("RGB")
image = np.array(data_input) # Convert PIL image to numpy arr
except IOError:
logger.error('Cannot retrieve image. Please check file: ' + data_input)
return False, False
else:
# Fix https://github.com/OPHoperHPO/image-background-remove-tool/issues/19
data_input = data_input.convert("RGB")
image = np.array(data_input) # Convert PIL image to numpy arr
x, resized_image = self.data.transforms.presets.rcnn.transform_test(self.nd.array(image))
return x, image, resized_image
def process_image(self, image):
"""
Detects objects in the photo and returns their names, borders.
:param image: Path to image or PIL image.
:return: original pil image, resized pil image, dict(ids, scores, bboxes)
"""
start_time = time.time() # Time counter
x, image, resized_image = self.__load_image__(image)
ids, scores, bboxes = [xx[0].asnumpy() for xx in self.__net__(x)]
logger.debug("Finished! Time spent: {}".format(time.time() - start_time))
return image, resized_image, {"ids": ids, "scores": scores, "bboxes": bboxes}
class MaskRcnn:
"""
Mask Rcnn Neural Network to detect objects in the photo.
"""
def __init__(self):
from gluoncv import model_zoo, utils, data
from mxnet import nd
self.model_zoo = model_zoo
self.utils = utils
self.data = data
self.nd = nd
logger.debug("Loading Mask RCNN neural network")
self.__net__ = self.model_zoo.get_model('mask_rcnn_resnet50_v1b_coco',
pretrained=True) # Download the pre-trained model, if one is missing.
# noinspection PyUnresolvedReferences
self.class_names = self.__net__.classes
def __load_image__(self, data_input):
"""
Loads an image file for other processing
:param data_input: Path to image file or PIL image
:return: neural network input, original pil image, resized image ndarray
"""
if isinstance(data_input, str):
try:
data_input = Image.open(data_input)
# Fix https://github.com/OPHoperHPO/image-background-remove-tool/issues/19
data_input = data_input.convert("RGB")
image = np.array(data_input) # Convert PIL image to numpy arr
except IOError:
logger.error('Cannot retrieve image. Please check file: ' + data_input)
return False, False
else:
# Fix https://github.com/OPHoperHPO/image-background-remove-tool/issues/19
data_input = data_input.convert("RGB")
image = np.array(data_input) # Convert PIL image to numpy arr
x, resized_image = self.data.transforms.presets.rcnn.transform_test(self.nd.array(image))
return x, image, resized_image
def process_image(self, image):
"""
Detects objects in the photo and returns their names, borders and a mask of poor quality.
:param image: Path to image or PIL image.
:return: original pil image, resized pil image, dict(ids, scores, bboxes, masks)
"""
start_time = time.time() # Time counter
x, image, resized_image = self.__load_image__(image)
ids, scores, bboxes, masks = [xx[0].asnumpy() for xx in self.__net__(x)]
masks, _ = self.utils.viz.expand_mask(masks, bboxes, (image.shape[1], image.shape[0]), scores)
logger.debug("Finished! Time spent: {}".format(time.time() - start_time))
return image, resized_image, {"ids": ids, "scores": scores, "bboxes": bboxes,
"masks": masks}
| 8,759 |
333 | /*
-------------------------------------------------------------------------
CxxTest: A lightweight C++ unit testing library.
Copyright (c) 2008 Sandia Corporation.
This software is distributed under the LGPL License v2.1
For more information, see the COPYING file in the top CxxTest directory.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------
*/
#ifndef __cxxtest__ValueTraits_h__
#define __cxxtest__ValueTraits_h__
//
// ValueTraits are used by CxxTest to convert arbitrary
// values used in TS_ASSERT_EQUALS() to a string representation.
//
// This header file contains value traits for builtin integral types.
// To declare value traits for new types you should instantiate the class
// ValueTraits<YourClass>.
//
#include <cxxtest/Flags.h>
#ifdef _CXXTEST_OLD_TEMPLATE_SYNTAX
# define CXXTEST_TEMPLATE_INSTANTIATION
#else // !_CXXTEST_OLD_TEMPLATE_SYNTAX
# define CXXTEST_TEMPLATE_INSTANTIATION template<>
#endif // _CXXTEST_OLD_TEMPLATE_SYNTAX
#ifdef _CXXTEST_HAVE_STD
#include <cmath>
#else
#include <math.h>
#endif
namespace CxxTest
{
//
// This is how we use the value traits
//
# define TS_AS_STRING(x) CxxTest::traits(x).asString()
//
// Char representation of a digit
//
char digitToChar( unsigned digit );
//
// Convert byte value to hex digits
// Returns pointer to internal buffer
//
const char *byteToHex( unsigned char byte );
//
// Convert byte values to string
// Returns one past the copied data
//
char *bytesToString( const unsigned char *bytes, unsigned numBytes, unsigned maxBytes, char *s );
//
// Copy a string.
// Returns one past the end of the destination string
// Remember -- we can't use the standard library!
//
char *copyString( char *dst, const char *src );
//
// Compare two strings.
// Remember -- we can't use the standard library!
//
bool stringsEqual( const char *s1, const char *s2 );
//
// Represent a character value as a string
// Returns one past the end of the string
// This will be the actual char if printable or '\xXXXX' otherwise
//
char *charToString( unsigned long c, char *s );
//
// Prevent problems with negative (signed char)s
//
char *charToString( char c, char *s );
//
// The default ValueTraits class dumps up to 8 bytes as hex values
//
template <class T>
class ValueTraits
{
enum { MAX_BYTES = 8 };
char _asString[sizeof("{ ") + sizeof("XX ") * MAX_BYTES + sizeof("... }")];
public:
ValueTraits( const T &t ) { bytesToString( (const unsigned char *)&t, sizeof(T), MAX_BYTES, _asString ); }
const char *asString( void ) const { return _asString; }
};
//
// traits( T t )
// Creates an object of type ValueTraits<T>
//
template <class T>
inline ValueTraits<T> traits( T t )
{
return ValueTraits<T>( t );
}
//
// You can duplicate the implementation of an existing ValueTraits
//
# define CXXTEST_COPY_TRAITS(CXXTEST_NEW_CLASS, CXXTEST_OLD_CLASS) \
CXXTEST_TEMPLATE_INSTANTIATION \
class ValueTraits< CXXTEST_NEW_CLASS > \
{ \
ValueTraits< CXXTEST_OLD_CLASS > _old; \
public: \
ValueTraits( CXXTEST_NEW_CLASS n ) : _old( (CXXTEST_OLD_CLASS)n ) {} \
const char *asString( void ) const { return _old.asString(); } \
}
//
// Certain compilers need separate declarations for T and const T
//
# ifdef _CXXTEST_NO_COPY_CONST
# define CXXTEST_COPY_CONST_TRAITS(CXXTEST_CLASS)
# else // !_CXXTEST_NO_COPY_CONST
# define CXXTEST_COPY_CONST_TRAITS(CXXTEST_CLASS) CXXTEST_COPY_TRAITS(CXXTEST_CLASS, const CXXTEST_CLASS)
# endif // _CXXTEST_NO_COPY_CONST
//
// Avoid compiler warnings about unsigned types always >= 0
//
template<class N> inline bool negative( N n ) { return n < 0; }
template<class N> inline N abs( N n ) { return negative(n) ? -n : n; }
# define CXXTEST_NON_NEGATIVE(Type) \
CXXTEST_TEMPLATE_INSTANTIATION \
inline bool negative<Type>( Type ) { return false; } \
CXXTEST_TEMPLATE_INSTANTIATION \
inline Type abs<Type>( Type value ) { return value; }
CXXTEST_NON_NEGATIVE( bool )
CXXTEST_NON_NEGATIVE( unsigned char )
CXXTEST_NON_NEGATIVE( unsigned short int )
CXXTEST_NON_NEGATIVE( unsigned int )
CXXTEST_NON_NEGATIVE( unsigned long int )
# ifdef _CXXTEST_LONGLONG
CXXTEST_NON_NEGATIVE( unsigned _CXXTEST_LONGLONG )
# endif // _CXXTEST_LONGLONG
//
// Represent (integral) number as a string
// Returns one past the end of the string
// Remember -- we can't use the standard library!
//
template<class N>
char *numberToString( N n, char *s,
N base = 10,
unsigned skipDigits = 0,
unsigned maxDigits = (unsigned)-1 )
{
if ( negative(n) ) {
*s++ = '-';
n = abs(n);
}
N digit = 1;
while ( digit <= (n / base) )
digit *= base;
N digitValue;
for ( ; digit >= 1 && skipDigits; n -= digit * digitValue, digit /= base, -- skipDigits )
digitValue = (unsigned)(n / digit);
for ( ; digit >= 1 && maxDigits; n -= digit * digitValue, digit /= base, -- maxDigits )
*s++ = digitToChar( (unsigned)(digitValue = (unsigned)(n / digit)) );
*s = '\0';
return s;
}
//
// All the specific ValueTraits follow.
// You can #define CXXTEST_USER_VALUE_TRAITS if you don't want them
//
#ifndef CXXTEST_USER_VALUE_TRAITS
//
// ValueTraits: const char * const &
// This is used for printing strings, as in TS_FAIL( "Message" )
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const char * const &>
{
ValueTraits &operator=( const ValueTraits & );
const char *_asString;
public:
ValueTraits( const char * const &value ) : _asString( value ) {}
ValueTraits( const ValueTraits &other ) : _asString( other._asString ) {}
const char *asString( void ) const { return _asString; }
};
CXXTEST_COPY_TRAITS( const char *, const char * const & );
CXXTEST_COPY_TRAITS( char *, const char * const & );
//
// ValueTraits: bool
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const bool>
{
bool _value;
public:
ValueTraits( const bool value ) : _value( value ) {}
const char *asString( void ) const { return _value ? "true" : "false"; }
};
CXXTEST_COPY_CONST_TRAITS( bool );
# ifdef _CXXTEST_LONGLONG
//
// ValueTraits: signed long long
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const signed _CXXTEST_LONGLONG>
{
typedef _CXXTEST_LONGLONG T;
char _asString[2 + 3 * sizeof(T)];
public:
ValueTraits( T t ) { numberToString<T>( t, _asString ); }
const char *asString( void ) const { return _asString; }
};
CXXTEST_COPY_CONST_TRAITS( signed _CXXTEST_LONGLONG );
//
// ValueTraits: unsigned long long
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const unsigned _CXXTEST_LONGLONG>
{
typedef unsigned _CXXTEST_LONGLONG T;
char _asString[1 + 3 * sizeof(T)];
public:
ValueTraits( T t ) { numberToString<T>( t, _asString ); }
const char *asString( void ) const { return _asString; }
};
CXXTEST_COPY_CONST_TRAITS( unsigned _CXXTEST_LONGLONG );
# endif // _CXXTEST_LONGLONG
//
// ValueTraits: signed long
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const signed long int>
{
typedef signed long int T;
char _asString[2 + 3 * sizeof(T)];
public:
ValueTraits( T t ) { numberToString<T>( t, _asString ); }
const char *asString( void ) const { return _asString; }
};
CXXTEST_COPY_CONST_TRAITS( signed long int );
//
// ValueTraits: unsigned long
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const unsigned long int>
{
typedef unsigned long int T;
char _asString[1 + 3 * sizeof(T)];
public:
ValueTraits( T t ) { numberToString<T>( t, _asString ); }
const char *asString( void ) const { return _asString; }
};
CXXTEST_COPY_CONST_TRAITS( unsigned long int );
//
// All decimals are the same as the long version
//
CXXTEST_COPY_TRAITS( const signed int, const signed long int );
CXXTEST_COPY_TRAITS( const unsigned int, const unsigned long int );
CXXTEST_COPY_TRAITS( const signed short int, const signed long int );
CXXTEST_COPY_TRAITS( const unsigned short int, const unsigned long int );
CXXTEST_COPY_TRAITS( const unsigned char, const unsigned long int );
CXXTEST_COPY_CONST_TRAITS( signed int );
CXXTEST_COPY_CONST_TRAITS( unsigned int );
CXXTEST_COPY_CONST_TRAITS( signed short int );
CXXTEST_COPY_CONST_TRAITS( unsigned short int );
CXXTEST_COPY_CONST_TRAITS( unsigned char );
//
// ValueTraits: char
// Returns 'x' for printable chars, '\x??' for others
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const char>
{
char _asString[sizeof("'\\xXX'")];
public:
ValueTraits( char c ) { copyString( charToString( c, copyString( _asString, "'" ) ), "'" ); }
const char *asString( void ) const { return _asString; }
};
CXXTEST_COPY_CONST_TRAITS( char );
//
// ValueTraits: signed char
// Same as char, some compilers need it
//
CXXTEST_COPY_TRAITS( const signed char, const char );
CXXTEST_COPY_CONST_TRAITS( signed char );
//
// ValueTraits: double
//
CXXTEST_TEMPLATE_INSTANTIATION
class ValueTraits<const double>
{
public:
ValueTraits( double t )
{
//if ( ( t != t ) || ( t >= 1.0/0.0 ) || ( t == -1.0/0.0 ) )
if ( ( t != t ) || ( t >= HUGE_VAL ) || ( t == -HUGE_VAL ) )
nonFiniteNumber( t );
else if ( requiredDigitsOnLeft( t ) > MAX_DIGITS_ON_LEFT )
hugeNumber( t );
else
normalNumber( t );
}
const char *asString( void ) const { return _asString; }
private:
enum { MAX_DIGITS_ON_LEFT = 24, DIGITS_ON_RIGHT = 4, BASE = 10 };
char _asString[1 + MAX_DIGITS_ON_LEFT + 1 + DIGITS_ON_RIGHT + 1];
static unsigned requiredDigitsOnLeft( double t );
char *doNegative( double &t );
void hugeNumber( double t );
void normalNumber( double t );
void nonFiniteNumber( double t );
char *doubleToString( double t, char *s, unsigned skip = 0, unsigned max = (unsigned)-1 );
};
CXXTEST_COPY_CONST_TRAITS( double );
//
// ValueTraits: float
//
CXXTEST_COPY_TRAITS( const float, const double );
CXXTEST_COPY_CONST_TRAITS( float );
#endif // !CXXTEST_USER_VALUE_TRAITS
}
#ifdef _CXXTEST_HAVE_STD
# include <cxxtest/StdValueTraits.h>
#endif // _CXXTEST_HAVE_STD
namespace dummy_enum_ns {}
//
// CXXTEST_ENUM_TRAITS
//
#define CXXTEST_ENUM_TRAITS( TYPE, VALUES ) \
namespace CxxTest \
{ \
CXXTEST_TEMPLATE_INSTANTIATION \
class ValueTraits<TYPE> \
{ \
TYPE _value; \
char _fallback[sizeof("(" #TYPE ")") + 3 * sizeof(TYPE)]; \
public: \
ValueTraits( TYPE value ) { \
_value = value; \
numberToString<unsigned long int>( _value, copyString( _fallback, "(" #TYPE ")" ) ); \
} \
const char *asString( void ) const \
{ \
switch ( _value ) \
{ \
VALUES \
default: return _fallback; \
} \
} \
}; \
} using namespace dummy_enum_ns
#define CXXTEST_ENUM_MEMBER( MEMBER ) \
case MEMBER: return #MEMBER;
#endif // __cxxtest__ValueTraits_h__
| 5,371 |
519 | # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test():
array = ak.Array(
[
[{"x": 0.0, "y": []}, {"x": 1.1, "y": [1]}, {"x": 2.2, "y": [1, 2]}],
[],
[
{"x": 3.3, "y": [1, 2, None, 3]},
False,
False,
True,
{"x": 4.4, "y": [1, 2, None, 3, 4]},
],
]
)
assert ak.full_like(array, 12.3).tolist() == [
[{"x": 12.3, "y": []}, {"x": 12.3, "y": [12]}, {"x": 12.3, "y": [12, 12]}],
[],
[
{"x": 12.3, "y": [12, 12, None, 12]},
True,
True,
True,
{"x": 12.3, "y": [12, 12, None, 12, 12]},
],
]
assert ak.zeros_like(array).tolist() == [
[{"x": 0.0, "y": []}, {"x": 0.0, "y": [0]}, {"x": 0.0, "y": [0, 0]}],
[],
[
{"x": 0.0, "y": [0, 0, None, 0]},
False,
False,
False,
{"x": 0.0, "y": [0, 0, None, 0, 0]},
],
]
assert ak.ones_like(array).tolist() == [
[{"x": 1.0, "y": []}, {"x": 1.0, "y": [1]}, {"x": 1.0, "y": [1, 1]}],
[],
[
{"x": 1.0, "y": [1, 1, None, 1]},
True,
True,
True,
{"x": 1.0, "y": [1, 1, None, 1, 1]},
],
]
array = ak.Array([["one", "two", "three"], [], ["four", "five"]])
assert ak.full_like(array, "hello").tolist() == [
["hello", "hello", "hello"],
[],
["hello", "hello"],
]
assert ak.full_like(array, 1).tolist() == [["1", "1", "1"], [], ["1", "1"]]
assert ak.full_like(array, 0).tolist() == [["0", "0", "0"], [], ["0", "0"]]
assert ak.ones_like(array).tolist() == [["1", "1", "1"], [], ["1", "1"]]
assert ak.zeros_like(array).tolist() == [["", "", ""], [], ["", ""]]
array = ak.Array([[b"one", b"two", b"three"], [], [b"four", b"five"]])
assert ak.full_like(array, b"hello").tolist() == [
[b"hello", b"hello", b"hello"],
[],
[b"hello", b"hello"],
]
assert ak.full_like(array, 1).tolist() == [[b"1", b"1", b"1"], [], [b"1", b"1"]]
assert ak.full_like(array, 0).tolist() == [[b"0", b"0", b"0"], [], [b"0", b"0"]]
assert ak.ones_like(array).tolist() == [[b"1", b"1", b"1"], [], [b"1", b"1"]]
assert ak.zeros_like(array).tolist() == [[b"", b"", b""], [], [b"", b""]]
| 1,511 |
1,006 | /****************************************************************************
* libs/libc/misc/lib_mkfifo.c
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <nuttx/fs/fs.h>
#if defined(CONFIG_PIPES) && CONFIG_DEV_FIFO_SIZE > 0
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: mkfifo
*
* Description:
* mkfifo() makes a FIFO device driver file with name 'pathname.' Unlike
* Linux, a NuttX FIFO is not a special file type but simply a device
* driver instance. 'mode' specifies the FIFO's permissions.
*
* Once the FIFO has been created by mkfifo(), any thread can open it for
* reading or writing, in the same way as an ordinary file. However, it
* must have been opened from both reading and writing before input or
* output can be performed. This FIFO implementation will block all
* attempts to open a FIFO read-only until at least one thread has opened
* the FIFO for writing.
*
* If all threads that write to the FIFO have closed, subsequent calls to
* read() on the FIFO will return 0 (end-of-file).
*
* Input Parameters:
* pathname - The full path to the FIFO instance to attach to or to create
* (if not already created).
* mode - Ignored for now
*
* Returned Value:
* 0 is returned on success; otherwise, -1 is returned with errno set
* appropriately.
*
****************************************************************************/
int mkfifo(FAR const char *pathname, mode_t mode)
{
int ret;
ret = nx_mkfifo(pathname, mode, CONFIG_DEV_FIFO_SIZE);
if (ret < 0)
{
set_errno(-ret);
ret = ERROR;
}
return ret;
}
#endif /* CONFIG_PIPES && CONFIG_DEV_FIFO_SIZE > 0 */
| 786 |
454 | package com.waylau.spring.boot.security.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.waylau.spring.boot.security.domain.User;
/**
* 用户仓库.
*
* @since 1.0.0 2017年3月2日
* @author <a href="https://waylau.com"><NAME></a>
*/
public interface UserRepository extends JpaRepository<User, Long>{
User findByUsername(String username);
}
| 164 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-7983-c95j-wcr3",
"modified": "2022-05-02T04:00:25Z",
"published": "2022-05-02T04:00:25Z",
"aliases": [
"CVE-2009-4997"
],
"details": "gnome-power-manager 2.27.92 does not properly implement the lock_on_suspend and lock_on_hibernate settings for locking the screen when the suspend or hibernate button is pressed, which might make it easier for physically proximate attackers to access an unattended laptop via a resume action, a related issue to CVE-2010-2532. NOTE: this issue exists because of a regression that followed a gnome-power-manager fix a few years earlier.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-4997"
},
{
"type": "WEB",
"url": "https://bugs.launchpad.net/ubuntu/+source/gnome-power-manager/+bug/42052"
},
{
"type": "WEB",
"url": "https://bugs.launchpad.net/ubuntu/+source/gnome-power-manager/+bug/428115"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "HIGH",
"github_reviewed": false
}
} | 461 |
501 | /*
* Decode tests.
*
* Test that cover aspects of the front-end instruction and uop deliver
* such as decoding, DSB, LSD, etc.
*/
#include "benchmark.hpp"
#include "util.hpp"
#include "boost/preprocessor/repetition/repeat_from_to.hpp"
extern "C" {
/* misc benches */
bench2_f decode33334;
bench2_f decode333322;
bench2_f decode3333211;
bench2_f decode33333;
bench2_f decode16x1;
bench2_f decode8x2;
bench2_f decode4x4;
bench2_f decode664;
bench2_f decode88;
bench2_f decode871;
bench2_f decode8833334;
bench2_f decode884444;
bench2_f decode_monoid;
bench2_f decode_monoid2;
bench2_f decode_monoid3;
bench2_f decode_complex_211;
bench2_f decode_complex_2111;
bench2_f decode_complex_21111;
bench2_f decode_complex_31;
bench2_f decode_complex_311;
bench2_f decode_complex_3111;
// bench2_f quadratic;
BOOST_PP_REPEAT_FROM_TO(35, 47, DECL_BENCH2, quadratic)
BOOST_PP_REPEAT_FROM_TO(48, 50, DECL_BENCH2, quadratic)
}
template <typename TIMER>
void register_decode(GroupList& list) {
#if !UARCH_BENCH_PORTABLE
auto group = std::make_shared<BenchmarkGroup>("decode", "Decode tests");
const size_t decode_ops = 50400/2;
auto maker = DeltaMaker<TIMER>(group.get(), 1000);
// legacy (MITE) decode tests
maker.template make<decode33334> ("decode33334", "Decode 3-3-3-3-4 byte nops", decode_ops);
maker.template make<decode333322> ("decode333322", "Decode 3-3-3-3-2-2 byte nops", decode_ops);
maker.template make<decode3333211> ("decode3333211","Decode 3-3-3-3-2-1-1 byte nops", decode_ops);
maker.template make<decode33333> ("decode33333", "Decode 3-3-3-3-3 byte nops", decode_ops);
maker.template make<decode16x1> ("decode16x1", "Decode 16x1 byte nops", decode_ops);
maker.template make<decode8x2> ("decode8x2", "Decode 8x2 byte nops", decode_ops);
maker.template make<decode4x4> ("decode4x4", "Decode 4x4 byte nops", decode_ops);
maker.template make<decode664> ("decode664", "Decode 6-6-4 byte nops", decode_ops);
maker.template make<decode88> ("decode88", "Decode 8-8 byte nops", decode_ops);
maker.template make<decode8833334> ("decode8833334", "Decode 8-8-3-3-3-3-4 byte nops", decode_ops);
maker.template make<decode884444> ("decode884444", "Decode 8-8-4-4-4-4 byte nops", decode_ops);
maker.template make<decode_monoid> ("decode-monoid", "Decode 33334x10, 556x10 blocks", 3200);
maker.template make<decode_monoid2>("decode-monoid2", "monoid2", 9000);
maker.template make<decode_monoid3>("decode-monoid3", "monoid3", 9000);
// these tests use a complex instruction (2 uops) to test the patterns that can be decoded
// in 1 cycle. If the decoder cannot decode the entire sequence (e.g., 2111 is 4 instructions with
// 2, 1, 1, 1 uops each) it will take 2 cycles, otherwise less (with the exact amount usually depending
// on the rename limit of 4).
#define DEFINE_DECODE_COMPLEX(suffix) maker.setLoopCount(10000).template make<decode_complex_##suffix> \
("decode_complex_" #suffix, "decode_complex_" #suffix, 200)
DEFINE_DECODE_COMPLEX(211);
DEFINE_DECODE_COMPLEX(2111);
DEFINE_DECODE_COMPLEX(21111);
DEFINE_DECODE_COMPLEX(31);
DEFINE_DECODE_COMPLEX(311);
DEFINE_DECODE_COMPLEX(3111);
// shows that a loop split by a 64-byte boundary takes at least 2 cycles, probably because the DSB can deliever
// from only one set per cycle
#define MAKE_QUAD(z, n, _) \
maker.template make<quadratic ## n>("quad" #n, "nested loops offset: " #n, 1000, \
[=]{ return aligned_ptr(4, 1024 * sizeof(uint32_t)); });
BOOST_PP_REPEAT_FROM_TO(35, 37, MAKE_QUAD, ignore)
BOOST_PP_REPEAT_FROM_TO(48, 50, MAKE_QUAD, ignore)
list.push_back(group);
#endif // #if !UARCH_BENCH_PORTABLE
}
#define REG_DEFAULT(CLOCK) template void register_decode<CLOCK>(GroupList& list);
ALL_TIMERS_X(REG_DEFAULT)
| 1,631 |
530 | import pytest
from tartiflette import Resolver, create_engine
_SDL = """
type Entry {
id: Int!
name: String!
}
input SubSubEntry {
name: String!
}
input SubEntryInput {
name: String!
subSubEntry: SubSubEntry
}
input AddEntryInput {
clientMutationId: String
subEntry1: SubEntryInput!
subEntry2: SubEntryInput!
}
type AddEntryPayload {
clientMutationId: String
}
type Query {
entry(id: Int!): Entry!
}
type Mutation {
addEntry(input: AddEntryInput!): AddEntryPayload!
}
"""
@pytest.fixture(scope="module")
async def ttftt_engine():
@Resolver("Mutation.addEntry", schema_name="test_issue205")
async def resolver_mutation_add_entry(parent, args, ctx, info):
return {"clientMutationId": args["input"].get("clientMutationId")}
return await create_engine(sdl=_SDL, schema_name="test_issue205")
@pytest.mark.asyncio
@pytest.mark.parametrize(
"query,variables,expected",
[
(
"""
mutation AddEntry($input: AddEntryInput!) {
addEntry(input: $input) {
clientMutationId
}
}
""",
{
"input": {
"clientMutationId": "addEntryId",
"subEntry1": {"name": "Entry1", "subSubEntry": None},
"subEntry2": {"name": "Entry1", "subSubEntry": None},
}
},
{"data": {"addEntry": {"clientMutationId": "addEntryId"}}},
),
(
"""
mutation AddEntry {
addEntry(input: {
clientMutationId: "addEntryId",
subEntry1: {
name: "Entry1",
subSubEntry: null
},
subEntry2: {
name: "Entry1",
subSubEntry: null
}
}) {
clientMutationId
}
}
""",
None,
{"data": {"addEntry": {"clientMutationId": "addEntryId"}}},
),
],
)
async def test_issue205(query, variables, expected, ttftt_engine):
assert await ttftt_engine.execute(query, variables=variables) == expected
| 1,134 |
336 | <reponame>eik00d/CANSploit
load_modules = {
'hw_CAN232': {'port': '/dev/cu.usbmodem1421', 'speed': '500KBPS', 'serial_speed': 115200, 'debug': 3},
'mod_stat': {'debug': 0},
}
actions = [
{'hw_CAN232': {'action': 'read', 'pipe': 1}},
{'mod_stat': {'pipe': 1}},
]
| 132 |
903 | <gh_stars>100-1000
package php.runtime.reflection;
import php.runtime.Memory;
import php.runtime.common.HintType;
import php.runtime.common.Messages;
import php.runtime.common.Modifier;
import php.runtime.env.Context;
import php.runtime.env.Environment;
import php.runtime.env.TraceInfo;
import php.runtime.exceptions.CriticalException;
import php.runtime.exceptions.support.ErrorType;
import php.runtime.invoke.InvokeArgumentHelper;
import php.runtime.invoke.ObjectInvokeHelper;
import php.runtime.lang.IObject;
import php.runtime.lang.exception.BaseTypeError;
import php.runtime.memory.ArrayMemory;
import php.runtime.memory.ReferenceMemory;
import php.runtime.memory.UninitializedMemory;
import php.runtime.memory.support.MemoryOperation;
import php.runtime.memory.support.ObjectPropertyMemory;
import php.runtime.reflection.support.Entity;
import php.runtime.reflection.support.ReflectionUtils;
import php.runtime.reflection.support.TypeChecker;
import java.lang.reflect.Field;
public class PropertyEntity extends Entity {
protected ClassEntity clazz;
protected ClassEntity trait;
protected Modifier modifier = Modifier.PUBLIC;
private Memory defaultValue;
protected DocumentComment docComment;
protected boolean isStatic;
protected Field field;
protected String specificName;
protected PropertyEntity prototype;
protected boolean isDefault;
protected MethodEntity getter;
protected MethodEntity setter;
protected TypeChecker typeChecker;
protected boolean nullable = false;
protected boolean hiddenInDebugInfo = false;
public PropertyEntity(Context context) {
super(context);
}
public PropertyEntity getPrototype() {
return prototype;
}
public void setPrototype(PropertyEntity prototype) {
this.prototype = prototype;
}
public TypeChecker getTypeChecker() {
return typeChecker;
}
public void setTypeChecker(TypeChecker typeChecker) {
this.typeChecker = typeChecker;
}
public boolean isNullable() {
return nullable;
}
public void setNullable(boolean nullable) {
this.nullable = nullable;
}
public void setTypeClass(String typeClass) {
typeChecker = typeClass == null ? null : TypeChecker.of(typeClass);
}
public void setTypeNativeClass(Class<?> typeNativeClass) {
Class<?> baseWrapper = MemoryOperation.getWrapper(typeNativeClass);
if (baseWrapper == null) {
throw new CriticalException("Support only wrapper classes");
}
typeChecker = TypeChecker.of(ReflectionUtils.getClassName(baseWrapper));
}
public Class<? extends Enum> getTypeEnum() {
return typeChecker instanceof TypeChecker.EnumClass ? ((TypeChecker.EnumClass) typeChecker).getTypeEnum() : null;
}
public void setTypeEnum(Class<? extends Enum> typeEnum) {
this.typeChecker = typeEnum == null ? null : TypeChecker.ofEnum(typeEnum);
}
public void setType(String type) {
HintType _type = HintType.of(type);
this.typeChecker = _type == null ? null : TypeChecker.of(_type);
}
public HintType getType() {
return typeChecker instanceof TypeChecker.Simple ? ((TypeChecker.Simple) typeChecker).getType() : HintType.ANY;
}
public String getTypeClass() {
return typeChecker instanceof TypeChecker.ClassName ? ((TypeChecker.ClassName) typeChecker).getTypeClass() : null;
}
public String getTypeClassLower() {
return typeChecker instanceof TypeChecker.ClassName ? ((TypeChecker.ClassName) typeChecker).getTypeClassLower() : null;
}
public void setType(HintType type) {
this.typeChecker = type == null || type == HintType.ANY ? null : TypeChecker.of(type);
}
public boolean checkTypeHinting(Environment env, Memory value) {
return checkTypeHinting(env, value, (String) null);
}
public boolean checkTypeHinting(Environment env, Memory value, String staticClassName) {
if (typeChecker != null) {
return typeChecker.check(
env, value, nullable, staticClassName
);
}
return true;
}
public Memory applyTypeHinting(Environment env, Memory value, boolean strict) {
if (typeChecker != null) {
return typeChecker.apply(
env, value, nullable, strict
);
}
return null;
}
public boolean isDefault() {
return isDefault;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
public Field getField() {
return field;
}
public void setField(Field field) {
field.setAccessible(true);
this.field = field;
}
public DocumentComment getDocComment() {
return docComment;
}
public void setDocComment(DocumentComment docComment) {
this.docComment = docComment;
}
public boolean isHiddenInDebugInfo() {
return hiddenInDebugInfo;
}
public void setHiddenInDebugInfo(boolean hiddenInDebugInfo) {
this.hiddenInDebugInfo = hiddenInDebugInfo;
}
public Memory getDefaultValue(){
return defaultValue;
}
public Memory getDefaultValue(Environment env) {
if (defaultValue == null) {
Memory r = env.getStatic(isStatic ? specificName : internalName);
return r == null ? Memory.NULL : r;
} else {
return defaultValue;
}
}
public void setDefaultTypedValue(Memory defaultValue, Environment env) {
if (defaultValue == null) {
setDefaultValue(getUninitializedValue());
} else {
this.setDefaultValue(env == null ? null : typedDefaultValue(env, defaultValue));
}
}
public Memory getUninitializedValue() {
String arg = null;
if (getType() != HintType.ANY) {
arg = getType().toString();
} else if (getTypeClass() != null) {
arg = getTypeClass();
}
if (arg != null) {
return UninitializedMemory.valueOf((nullable ? "?" : "") + arg);
}
return Memory.NULL;
}
public void setDefaultValue(Memory defaultValue) {
/*if (defaultValue == null) {
Memory uninitializedValue = getUninitializedValue();
defaultValue = uninitializedValue == Memory.NULL ? null : uninitializedValue;
}*/
this.defaultValue = defaultValue;
}
public Modifier getModifier() {
return modifier;
}
public boolean isPrivate(){
return modifier == Modifier.PRIVATE;
}
public boolean isProtected(){
return modifier == Modifier.PROTECTED;
}
public boolean isPublic(){
return modifier == Modifier.PUBLIC;
}
public void setModifier(Modifier modifier) {
this.modifier = modifier;
updateSpecificName();
}
public boolean isStatic() {
return isStatic;
}
public void setStatic(boolean aStatic) {
isStatic = aStatic;
}
public ClassEntity getClazz() {
return clazz;
}
public void setClazz(ClassEntity clazz) {
this.clazz = clazz;
updateSpecificName();
}
public boolean isDeprecated(){
return false; // TODO
}
public void updateSpecificName(){
switch (modifier){
case PRIVATE: if (clazz != null) { specificName = "\0" + clazz.getName() + "\0" + name; } break;
case PROTECTED: specificName = "\0*\0" + name; break;
default:
specificName = name;
}
if (isStatic && clazz != null)
specificName = "\0" + clazz.getLowerName() + "#" + specificName;
if (clazz != null)
internalName = "\0" + clazz.getLowerName() + "\0#" + name;
}
@Override
public void setName(String name) {
super.setName(name);
updateSpecificName();
}
public String getSpecificName() {
return specificName;
}
public ClassEntity getTrait() {
return trait;
}
public void setTrait(ClassEntity trait) {
this.trait = trait;
}
public boolean isOwned(ClassEntity entity){
return clazz.getId() == entity.getId();
}
public int canAccess(Environment env) {
return canAccess(env, null, false);
}
public MethodEntity getGetter() {
return getter;
}
public void setGetter(MethodEntity getter) {
this.getter = getter;
}
public MethodEntity getSetter() {
return setter;
}
public void setSetter(MethodEntity setter) {
this.setter = setter;
}
public int canAccess(Environment env, ClassEntity context) {
return canAccess(env, context, false);
}
/**
* 0 - success
* 1 - invalid protected
* 2 - invalid private
* @param env
* @return
*/
public int canAccess(Environment env, ClassEntity context, boolean lateStaticCall) {
switch (modifier){
case PUBLIC: return 0;
case PRIVATE:
ClassEntity cl = context == null ? (lateStaticCall ? env.getLateStaticClass() : env.getLastClassOnStack()) : context;
return cl != null && cl.getId() == this.clazz.getId() ? 0 : 2;
case PROTECTED:
ClassEntity clazz = context == null ? (lateStaticCall ? env.getLateStaticClass() : env.getLastClassOnStack()) : context;
if (clazz == null)
return 1;
long id = this.clazz.getId();
do {
if (clazz.getId() == id)
return 0;
clazz = clazz.parent;
} while (clazz != null);
return 1;
}
return 2;
}
public boolean canAccessAsNonStatic(Environment env, TraceInfo trace){
if (isStatic){
env.error(
trace, ErrorType.E_STRICT, Messages.ERR_ACCESSING_STATIC_PROPERTY_AS_NON_STATIC,
getClazz().getName(), name
);
return false;
}
return true;
}
public boolean isReadOnly() {
return getter == null && setter != null;
}
public PropertyEntity duplicate() {
PropertyEntity propertyEntity = new PropertyEntity(context);
propertyEntity.setStatic(isStatic);
propertyEntity.setDocComment(docComment);
propertyEntity.setName(name);
propertyEntity.setDefault(isDefault);
propertyEntity.setDefaultValue(defaultValue);
propertyEntity.setModifier(modifier);
propertyEntity.setPrototype(propertyEntity);
propertyEntity.setTrace(trace);
propertyEntity.setGetter(getter);
propertyEntity.setSetter(setter);
return propertyEntity;
}
protected Memory typedDefaultValue(Environment env, Memory defaultValue) {
if (typeChecker != null && defaultValue != null && !defaultValue.isUninitialized()) {
if (!checkTypeHinting(env, defaultValue)) {
ModuleEntity module = env.getModuleManager().findModule(trace);
Memory memory = applyTypeHinting(env, defaultValue, module != null && module.isStrictTypes());
if (memory == null) {
String mustBe = typeChecker.getSignature();
if (!nullable && defaultValue.isNull()) {
env.error(trace,
"Default value for property of type %s may not be null. Use the nullable type ?%s to allow null default value",
mustBe, mustBe
);
} else {
env.error(trace,
"Cannot use %s as default value for property %s::$%s of type %s",
InvokeArgumentHelper.getGiven(defaultValue, true), getClazz().getName(), getName(), mustBe
);
}
}
return memory;
}
}
return defaultValue;
}
public Memory typedValue(Environment env, TraceInfo trace, Memory value) {
if (typeChecker != null) {
if (!checkTypeHinting(env, value)) {
ModuleEntity module = env.getModuleManager().findModule(trace);
Memory memory = applyTypeHinting(env, value, module != null && module.isStrictTypes());
if (memory != null) {
value = memory;
} else {
String mustBe = typeChecker.getSignature();
if (nullable) {
mustBe = "?" + mustBe;
}
env.exception(trace,
BaseTypeError.class,
"Cannot assign %s to property %s::$%s of type %s",
InvokeArgumentHelper.getGiven(value, true), getClazz().getName(), getName(), mustBe
);
}
}
}
return value;
}
public Memory assignValue(Environment env, TraceInfo trace, Object object, String name, Memory value) {
return ((IObject) object).getProperties().refOfIndex(name).assign(typedValue(env, trace, value));
}
public Memory getStaticValue(Environment env, TraceInfo trace) {
return env.getOrCreateStatic(
specificName,
getDefaultValue(env).fast_toImmutable()
);
}
public Memory getValue(Environment env, TraceInfo trace, Object object) throws Throwable {
if (getter != null && object instanceof IObject) {
return ObjectInvokeHelper.invokeMethod((IObject) object, getter, env, trace, null, false);
}
ArrayMemory props = ((IObject) object).getProperties();
ReferenceMemory result = props.getByScalar(specificName);
if (result == null) {
result = props.getByScalar(name);
}
if (result != null && isTyped()) {
return new ObjectPropertyMemory(env, trace, result, this);
}
return result;
}
public boolean isTyped() {
return typeChecker != null;
}
public boolean isSameTyped(PropertyEntity el) {
if (typeChecker == null && el.typeChecker == null) {
return true;
}
return typeChecker != null && typeChecker.identical(el.typeChecker);
}
}
| 6,137 |
778 | <filename>libcxx/test/std/utilities/time/time.hms/time.hms.members/minutes.pass.cpp
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// <chrono>
// template <class Duration>
// class hh_mm_ss
//
// constexpr chrono::minutes minutes() const noexcept;
//
// See the table in hours.pass.cpp for correspondence between the magic values used below
#include <chrono>
#include <cassert>
#include "test_macros.h"
template <typename Duration>
constexpr long check_minutes(Duration d)
{
using HMS = std::chrono::hh_mm_ss<Duration>;
ASSERT_SAME_TYPE(std::chrono::minutes, decltype(std::declval<HMS>().minutes()));
ASSERT_NOEXCEPT( std::declval<HMS>().minutes());
return HMS(d).minutes().count();
}
int main(int, char**)
{
using microfortnights = std::chrono::duration<int, std::ratio<756, 625>>;
static_assert( check_minutes(std::chrono::minutes( 1)) == 1, "");
static_assert( check_minutes(std::chrono::minutes(-1)) == 1, "");
assert( check_minutes(std::chrono::seconds( 5000)) == 23);
assert( check_minutes(std::chrono::seconds(-5000)) == 23);
assert( check_minutes(std::chrono::minutes( 5000)) == 20);
assert( check_minutes(std::chrono::minutes(-5000)) == 20);
assert( check_minutes(std::chrono::hours( 11)) == 0);
assert( check_minutes(std::chrono::hours(-11)) == 0);
assert( check_minutes(std::chrono::milliseconds( 123456789LL)) == 17);
assert( check_minutes(std::chrono::milliseconds(-123456789LL)) == 17);
assert( check_minutes(std::chrono::microseconds( 123456789LL)) == 2);
assert( check_minutes(std::chrono::microseconds(-123456789LL)) == 2);
assert( check_minutes(std::chrono::nanoseconds( 123456789LL)) == 0);
assert( check_minutes(std::chrono::nanoseconds(-123456789LL)) == 0);
assert( check_minutes(microfortnights( 1000)) == 20);
assert( check_minutes(microfortnights( -1000)) == 20);
assert( check_minutes(microfortnights( 10000)) == 21);
assert( check_minutes(microfortnights(-10000)) == 21);
return 0;
}
| 907 |
7,676 | <reponame>Infi-zc/horovod
// Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ============================================================================
#ifndef HOROVOD_GLOO_HTTP_STORE_H
#define HOROVOD_GLOO_HTTP_STORE_H
#include "HTTPRequest.hpp"
#include "gloo_store.h"
namespace horovod {
namespace common {
#define MAX_RETRY_TIMES 3
#define RETRY_WAITING_TIME_MILLSEC 500
#define HTTP_GET_METHOD "GET"
#define HTTP_PUT_METHOD "PUT"
#define HTTP_DELETE_METHOD "DELETE"
#define HTTP_OK 200
#define HTTP_NOT_FOUND 404
class HTTPStore : public GlooStore {
public:
HTTPStore(const std::string& server_ip, int port, const std::string& scope,
int rank)
: rank_(rank) {
url_prefix_ +=
"http://" + server_ip + ":" + std::to_string(port) + "/" + scope + "/";
}
void set(const std::string& key, const std::vector<char>& data) override;
std::vector<char> get(const std::string& key) override;
void wait(const std::vector<std::string>& keys) override {
wait(keys, Store::kDefaultTimeout);
}
void wait(const std::vector<std::string>& keys,
const std::chrono::milliseconds& timeout) override;
bool CheckKeys(const std::vector<std::string>& keys);
void Finalize() override;
protected:
// Send HTTP request to server, retry if the status code is not 200 (OK) or
// 404 (Key not found).
http::Response PerformHTTP(http::Request& request, const std::string& method,
const std::string& body);
// HTTP GET: result is an out parameter for retrieved value for the key.
// Return a bool representing whether the key is found in the store.
bool HTTP_GET(const std::string& key, std::vector<char>& result);
// HTTP PUT: send HTTP PUT request to server with the key and value data.
// The key is a string and will be embed into the url; the data is
// the PUT body.
void HTTP_PUT(const std::string& key, const std::vector<char>& data);
// HTTP DELETE: send HTTP DELETE request to server, informing the server that
// this rank has finished.
void HTTP_DELETE(const std::string& key);
std::string url_prefix_;
int rank_;
};
} // namespace common
} // namespace horovod
#endif // HOROVOD_GLOO_HTTP_STORE_H
| 905 |
301 | //******************************************************************
//
// Copyright 2014 Intel Mobile Communications GmbH 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// garageclient.cpp is the client program for garageserver.cpp, which
// uses different representation in OCRepresention.
#include <string>
#include <cstdlib>
#include <mutex>
#include <condition_variable>
#include "OCPlatform.h"
#include "OCApi.h"
using namespace OC;
std::shared_ptr<OCResource> curResource;
std::mutex curResourceLock;
static void printUsage()
{
std::cout<<"Usage: garageclient <0|1> \n";
std::cout<<"ConnectivityType: Default IP\n";
std::cout<<"ConnectivityType 0: IP \n";
}
class Garage
{
public:
bool m_state;
std::string m_name;
std::vector<bool> m_lightStates;
std::vector<int> m_lightPowers;
OCRepresentation m_lightRep;
std::vector<OCRepresentation> m_reps;
std::vector<std::vector<int>> m_hingeStates;
Garage() : m_state(false), m_name("")
{
}
};
Garage myGarage;
void printRepresentation(const OCRepresentation& rep)
{
// Check if attribute "name" exists, and then getValue
if(rep.hasAttribute("name"))
{
myGarage.m_name = rep["name"];
}
std::cout << "\tname: " << myGarage.m_name << std::endl;
// You can directly try to get the value. this function
// return false if there is no attribute "state"
if(!rep.getValue("state", myGarage.m_state))
{
std::cout << "Attribute state doesn't exist in the representation\n";
}
std::cout << "\tstate: " << myGarage.m_state << std::endl;
OCRepresentation rep2 = rep;
std::cout << "Number of attributes in rep2: "
<< rep2.numberOfAttributes() << std::endl;
if(rep2.erase("name"))
{
std::cout << "attribute: name, was removed successfully from rep2.\n";
}
std::cout << "Number of attributes in rep2: "
<< rep2.numberOfAttributes() << std::endl;
if(rep.isNULL("nullAttribute"))
{
std::cout << "\tnullAttribute is null." << std::endl;
}
else
{
std::cout << "\tnullAttribute is not null." << std::endl;
}
myGarage.m_lightRep = rep["light"];
myGarage.m_lightStates = myGarage.m_lightRep["states"];
myGarage.m_lightPowers = myGarage.m_lightRep["powers"];
std::cout << "\tlightRep: states: ";
int first = 1;
for(auto state: myGarage.m_lightStates)
{
if(first)
{
std::cout << state;
first = 0;
}
else
{
std::cout << "," << state;
}
}
std::cout << std::endl;
std::cout << "\tlightRep: powers: ";
first = 1;
for(auto power: myGarage.m_lightPowers)
{
if(first)
{
std::cout << power;
first = 0;
}
else
{
std::cout << "," << power;
}
}
std::cout << std::endl;
// Get vector of representations
myGarage.m_reps = rep["reps"];
int ct = 0;
for(auto& rep : myGarage.m_reps)
{
for(auto& attribute : rep)
{
std::cout<< "\treps["<<ct<<"]."<<attribute.attrname()<<":"
<< attribute.type()<<" with value " <<attribute.getValueToString() <<std::endl;
}
++ct;
}
std::cout << "\tjson: " << rep["json"] << std::endl;
myGarage.m_hingeStates = rep["hinges"];
std::cout<< "\tHinge parameter is type: " << rep["hinges"].type() << " with depth "<<
rep["hinges"].depth() << " and a base type of "<< rep["hinges"].base_type()<<std::endl;
}
// callback handler on PUT request
void onPut(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
if (eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CHANGED)
{
std::cout << "PUT request was successful" << std::endl;
printRepresentation(rep);
}
else
{
std::cout << "onPut Response error: " << eCode << std::endl;
std::exit(-1);
}
}
// Local function to put a different state for this resource
void putLightRepresentation(std::shared_ptr<OCResource> resource)
{
if(resource)
{
OCRepresentation rep;
std::cout << "Putting light representation..."<<std::endl;
myGarage.m_state = true;
rep["state"] = myGarage.m_state;
// Create QueryParameters Map and add query params (if any)
QueryParamsMap queryParamsMap;
// Invoke resource's pit API with rep, query map and the callback parameter
resource->put(rep, queryParamsMap, &onPut);
}
}
// Callback handler on GET request
void onGet(const HeaderOptions& /*headerOptions*/, const OCRepresentation& rep, const int eCode)
{
if (eCode == OC_STACK_OK)
{
std::cout << "GET request was successful" << std::endl;
std::cout << "Resource URI: " << rep.getUri() << std::endl;
printRepresentation(rep);
putLightRepresentation(curResource);
}
else
{
std::cout << "onGET Response error: " << eCode << std::endl;
std::exit(-1);
}
}
// Local function to get representation of light resource
void getLightRepresentation(std::shared_ptr<OCResource> resource)
{
if(resource)
{
std::cout << "Getting Light Representation..."<<std::endl;
// Invoke resource's get API with the callback parameter
QueryParamsMap test;
resource->get(test, &onGet);
}
}
// Callback to found resources
void foundResource(std::shared_ptr<OCResource> resource)
{
std::lock_guard<std::mutex> lock(curResourceLock);
if(curResource)
{
std::cout << "Found another resource, ignoring"<<std::endl;
return;
}
std::string resourceURI;
std::string hostAddress;
try
{
// Do some operations with resource object.
if(resource)
{
std::cout<<"DISCOVERED Resource:"<<std::endl;
// Get the resource URI
resourceURI = resource->uri();
std::cout << "\tURI of the resource: " << resourceURI << std::endl;
// Get the resource host address
hostAddress = resource->host();
std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
// Get the resource types
std::cout << "\tList of resource types: " << std::endl;
for(auto &resourceTypes : resource->getResourceTypes())
{
std::cout << "\t\t" << resourceTypes << std::endl;
}
// Get the resource interfaces
std::cout << "\tList of resource interfaces: " << std::endl;
for(auto &resourceInterfaces : resource->getResourceInterfaces())
{
std::cout << "\t\t" << resourceInterfaces << std::endl;
}
if(resourceURI == "/a/garage")
{
curResource = resource;
// Call a local function which will internally invoke
// get API on the resource pointer
getLightRepresentation(resource);
}
}
else
{
// Resource is invalid
std::cout << "Resource is invalid" << std::endl;
}
}
catch(std::exception& e)
{
std::cerr << "Exception in foundResource: "<< e.what()<<std::endl;
}
}
int main(int argc, char* argv[]) {
std::ostringstream requestURI;
OCConnectivityType connectivityType = CT_ADAPTER_IP;
if(argc == 2)
{
try
{
std::size_t inputValLen;
int optionSelected = std::stoi(argv[1], &inputValLen);
if(inputValLen == strlen(argv[1]))
{
if(optionSelected == 0)
{
std::cout << "Using IP."<< std::endl;
connectivityType = CT_ADAPTER_IP;
}
else
{
std::cout << "Invalid connectivity type selected. Using default IP"
<< std::endl;
}
}
else
{
std::cout << "Invalid connectivity type selected. Using default IP" << std::endl;
}
}
catch(std::exception&)
{
std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
}
else
{
printUsage();
std::cout << "Invalid input argument. Using IP as connectivity type" << std::endl;
}
// Create PlatformConfig object
PlatformConfig cfg {
OC::ServiceType::InProc,
OC::ModeType::Client,
nullptr
};
OCPlatform::Configure(cfg);
try
{
OC_VERIFY(OCPlatform::start() == OC_STACK_OK);
// Find all resources
requestURI << OC_RSRVD_WELL_KNOWN_URI << "?rt=core.garage";
OCPlatform::findResource("", requestURI.str(),
connectivityType, &foundResource);
std::cout<< "Finding Resource... " <<std::endl;
// A condition variable will free the mutex it is given, then do a non-
// intensive block until 'notify' is called on it. In this case, since we
// don't ever call cv.notify, this should be a non-processor intensive version
// of while(true);
std::mutex blocker;
std::condition_variable cv;
std::unique_lock<std::mutex> lock(blocker);
cv.wait(lock);
OC_VERIFY(OCPlatform::stop() == OC_STACK_OK);
}
catch(OCException& e)
{
std::cerr << "Exception in GarageClient: "<<e.what();
}
return 0;
}
| 4,781 |
335 | {
"word": "Worthy",
"definitions": [
"Having or showing the qualities that deserve the specified action or regard.",
"Deserving effort, attention, or respect.",
"Good enough; suitable.",
"Characterized by good intent but lacking in humour or imagination."
],
"parts-of-speech": "Adjective"
} | 119 |
468 | <reponame>vinjn/glintercept
/*=============================================================================
GLIntercept - OpenGL intercept/debugging tool
Copyright (C) 2006 <NAME>
Licensed under the MIT license - See Docs\license.txt for details.
=============================================================================*/
#include "ConfigData.h"
#include <ConfigParser.h>
#include <FileUtils.h>
#include <InputUtils.h>
extern string dllPath;
USING_ERRORLOG
///////////////////////////////////////////////////////////////////////////////
//
ConfigData::ConfigData():
logEnabled(false),
logXMLFormat(false),
logFlush(false),
logMaxFrameLoggingEnabled(false),
logMaxNumLogFrames(0),
logXSLFile(""),
logXSLBaseDir(""),
errorGetOpenGLChecks(false),
errorThreadChecking(false),
errorBreakOnError(true),
errorLogOnError(true),
errorExtendedLogError(false),
errorDebuggerErrorLog(true),
logPerFrame(false),
logOneFrameOnly(true),
logPath(""),
logName("gliInterceptLog"),
functionDataFileName("gliIncludes.h"),
imageLogEnabled(false),
imageRenderCallStateLog(true),
imageSaveIcon(true),
imageIconSize(32),
imageIconFormat("jpg"),
imageSavePNG(true),
imageSaveTGA(false),
imageSaveJPG(false),
imageFlipXAxis(false),
imageCubeMapTile(true),
imageSave1D(true),
imageSave2D(true),
imageSave3D(true),
imageSaveCube(true),
imageSavePBufferTex(true),
shaderLogEnabled(false),
shaderRenderCallStateLog(true),
shaderAttachLogState(true),
shaderValidatePreRender(false),
shaderLogUniformsPreRender(false),
displayListLogEnabled(false),
frameLogEnabled(false),
frameImageFormat("jpg"),
framePreColorSave(false),
framePostColorSave(false),
frameDiffColorSave(false),
framePreDepthSave(false),
framePostDepthSave(false),
frameDiffDepthSave(false),
framePreStencilSave(false),
framePostStencilSave(false),
frameDiffStencilSave(false),
frameIconSave(false),
frameIconSize(40),
frameIconImageFormat("jpg"),
frameMovieEnabled(false),
frameMovieWidth(640),
frameMovieHeight(480),
frameMovieRate(15),
timerLogEnabled(false),
timerLogCutOff(1),
pluginBasePath("")
{
#ifdef GLI_BUILD_WINDOWS
//Construct the path to the OpenGL filename
char DefaultGLLibName[MAX_PATH];
//Get the default library name
GetSystemDirectory(DefaultGLLibName, MAX_PATH);
//Assign the name
openGLFileName = string(DefaultGLLibName) + FileUtils::dirSeparator + string("opengl32.dll");
#endif //GLI_BUILD_WINDOWS
#ifdef GLI_BUILD_LINUX
//On Linux, the SGI ABI spec states there is only one default path for OpenGL
// (http://oss.sgi.com/projects/ogl-sample/ABI/)
openGLFileName = "/usr/lib/libGL.so";
#endif //GLI_BUILD_LINUX
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadConfigData()
{
//Parse the config files
ConfigParser parser;
//If parsing was successful, add the data to the function table
if(!parser.Parse(dllPath + "gliConfig.ini"))
{
LOGERR(("ConfigData::ReadConfigData - Unable to read config data file - %sgliConfig.ini",dllPath.c_str()));
return;
}
// Read the main function log options
ReadFunctionLogConfigData(parser);
// Read the pre-frame config data
ReadPerFrameConfigData(parser);
// Read the input file names
ReadInputFilesConfigData(parser);
// Read the error checking options
ReadErrorCheckingConfigData(parser);
//Read in the image data
ReadImageConfigData(parser);
//Read the shader data
ReadShaderConfigData(parser);
//Read the display list data
ReadDisplayListConfigData(parser);
//Read the frame log data
ReadFrameConfigData(parser);
//Read the timer options
ReadTimerConfigData(parser);
//Read plugin data
ReadPluginData(parser);
//Log all unused tokens
parser.LogUnusedTokens();
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadFunctionLogConfigData(ConfigParser &parser)
{
// Get if logging the OpenGL function calls
const ConfigToken *functionLogToken = parser.GetToken("FunctionLog");
if(!functionLogToken)
{
return;
}
//Get if the log is enabled
const ConfigToken *testToken = functionLogToken->GetChildToken("LogEnabled");
if(testToken)
{
testToken->Get(logEnabled);
}
//Get if the log is flushed
testToken = functionLogToken->GetChildToken("LogFlush");
if(testToken)
{
testToken->Get(logFlush);
}
//Get list of additional render calls
testToken = functionLogToken->GetChildToken("AdditionalRenderCalls");
if(testToken)
{
//Loop for all values
for(uint i=0; i < testToken->GetNumValues(); i++)
{
//Get each function name and add to the array
string newValue;
testToken->Get(newValue,i);
frameAdditionalRenderCalls.push_back(newValue);
}
}
//Get if a maximum number of logging frames has been specified
testToken = functionLogToken->GetChildToken("LogMaxNumFrames");
if(testToken)
{
logMaxFrameLoggingEnabled = true;
testToken->Get(logMaxNumLogFrames);
}
//Get the log path
testToken = functionLogToken->GetChildToken("LogPath");
if(testToken)
{
testToken->Get(logPath);
if(logPath.size() == 0)
{
//Assign the dll path as the log path
logPath = dllPath;
}
//If no trailing slash is provided, add one
// (Perhaps check that it is a valid path?)
else if(logPath[logPath.size()-1] != '\\' &&
logPath[logPath.size()-1] != '/')
{
logPath = logPath + FileUtils::dirSeparator;
}
}
else
{
//Assign the dll path as the log path
logPath = dllPath;
}
//Get the log file name
testToken = functionLogToken->GetChildToken("LogFileName");
if(testToken)
{
testToken->Get(logName);
}
//Get if the format is XML or not
testToken = functionLogToken->GetChildToken("LogFormat");
if(testToken)
{
//Get an test the string for XML format
string value;
if(testToken->Get(value))
{
if(value == "XML" || value == "xml")
{
logXMLFormat = true;
}
}
}
//Get the XML format data
const ConfigToken *xmlFormatToken = functionLogToken->GetChildToken("XMLFormat");
if(xmlFormatToken)
{
//Get the XSL file
testToken = xmlFormatToken->GetChildToken("XSLFile");
if(testToken)
{
testToken->Get(logXSLFile);
}
//Get the base directory
testToken = xmlFormatToken->GetChildToken("BaseDir");
if(testToken)
{
testToken->Get(logXSLBaseDir);
//Add a trailing seperator
if(logXSLBaseDir.size() > 0 &&
logXSLBaseDir[logXSLBaseDir.size()-1] != '\\' &&
logXSLBaseDir[logXSLBaseDir.size()-1] != '/')
{
logXSLBaseDir = logXSLBaseDir + FileUtils::dirSeparator;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadPerFrameConfigData(ConfigParser &parser)
{
//Get if the logging is per-frame or not
const ConfigToken *perFrameToken = parser.GetToken("LogPerFrame");
if(!perFrameToken)
{
return;
}
//Get if per frame logging is enabled
const ConfigToken *testToken = perFrameToken->GetChildToken("Enabled");
if(testToken)
{
testToken->Get(logPerFrame);
}
//Get if per-frame logging is forced to one frame at a time
testToken = perFrameToken->GetChildToken("OneFrameOnly");
if(testToken)
{
testToken->Get(logOneFrameOnly);
}
//Get the key codes
testToken = perFrameToken->GetChildToken("FrameStartKeys");
if(testToken)
{
//Loop for the number of values in the token
for(uint i=0;i<testToken->GetNumValues();i++)
{
string value;
testToken->Get(value,i);
//Get the key code of the string
uint newValue = InputUtils::GetKeyCode(value);
if(newValue != 0)
{
//Add the value to the array
logFrameKeys.push_back(newValue);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadInputFilesConfigData(ConfigParser &parser)
{
// Get the inoput files section
const ConfigToken *inputFilesToken = parser.GetToken("InputFiles");
if(!inputFilesToken)
{
return;
}
//Get the OpenGL function defines
const ConfigToken *testToken = inputFilesToken->GetChildToken("GLFunctionDefines");
if(testToken)
{
testToken->Get(functionDataFileName);
}
//Get the OpenGL system library
testToken = inputFilesToken->GetChildToken("GLSystemLib");
if(testToken)
{
testToken->Get(openGLFileName);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadErrorCheckingConfigData(ConfigParser &parser)
{
// Get the error checking section
const ConfigToken *errorCheckToken = parser.GetToken("ErrorChecking");
if(!errorCheckToken)
{
return;
}
//Determine if we issue error check calls
const ConfigToken *testToken = errorCheckToken->GetChildToken("GLErrorChecking");
if(testToken)
{
testToken->Get(errorGetOpenGLChecks);
}
//Determine if thread checking is performed
testToken = errorCheckToken->GetChildToken("ThreadChecking");
if(testToken)
{
testToken->Get(errorThreadChecking);
}
//Determine if we break on errors
testToken = errorCheckToken->GetChildToken("BreakOnError");
if(testToken)
{
testToken->Get(errorBreakOnError);
}
//Determine if we log on OpenGL error
testToken = errorCheckToken->GetChildToken("LogOnError");
if(testToken)
{
testToken->Get(errorLogOnError);
}
//Get if there is extened error log reporting
testToken = errorCheckToken->GetChildToken("ExtendedErrorLog");
if(testToken)
{
testToken->Get(errorExtendedLogError);
}
//Determine if we mirror the error log to the debug window
testToken = errorCheckToken->GetChildToken("DebuggerErrorLog");
if(testToken)
{
testToken->Get(errorDebuggerErrorLog);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadImageConfigData(ConfigParser &parser)
{
//Get if the outer log section
const ConfigToken * imgToken = parser.GetToken("ImageLog");
if(!imgToken)
{
return;
}
const ConfigToken *imgTestToken;
//Get if the log is enabled
imgTestToken = imgToken->GetChildToken("LogEnabled");
if(imgTestToken)
{
imgTestToken->Get(imageLogEnabled);
}
//Get if we log the state on render calls
imgTestToken = imgToken->GetChildToken("RenderCallStateLog");
if(imgTestToken)
{
imgTestToken->Get(imageRenderCallStateLog);
}
//Get if icon image saving is enabled
const ConfigToken *imgIconToken = imgToken->GetChildToken("ImageIcon");
if(imgIconToken)
{
//Get if icon saving is enabled
imgTestToken = imgIconToken->GetChildToken("Enabled");
if(imgTestToken)
{
imgTestToken->Get(imageSaveIcon);
}
//Get the size of the icon image
imgTestToken = imgIconToken->GetChildToken("Size");
if(imgTestToken)
{
imgTestToken->Get(imageIconSize);
}
//Get the format of the icon file
imgTestToken = imgIconToken->GetChildToken("SaveFormat");
imageIconFormat = "jpg";
if(imgTestToken)
{
GetImageFormat(imgTestToken, imageIconFormat);
}
}
//Get the save formats
imgTestToken = imgToken->GetChildToken("SaveFormats");
if(imgTestToken)
{
//Reset all save formats
imageSavePNG = false;
imageSaveTGA = false;
imageSaveJPG = false;
//Loop for the number of values in the token
for(uint i=0;i<imgTestToken->GetNumValues();i++)
{
string value;
imgTestToken->Get(value,i);
if(value == "PNG")
{
imageSavePNG = true;
}
else if(value == "TGA")
{
imageSaveTGA = true;
}
else if(value == "JPG")
{
imageSaveJPG = true;
}
else
{
LOGERR(("ConfigData::ReadImageConfigData - Unknown texture save format %s",value.c_str()));
}
}
}
//Get the flip X axis
imgTestToken = imgToken->GetChildToken("FlipXAxis");
if(imgTestToken)
{
imgTestToken->Get(imageFlipXAxis);
}
//Get the cube map tile property
imgTestToken = imgToken->GetChildToken("TileCubeMaps");
if(imgTestToken)
{
imgTestToken->Get(imageCubeMapTile);
}
//Get the GL texture saveing formats
imgTestToken = imgToken->GetChildToken("SaveGLTypes");
if(imgTestToken)
{
//Reset all save formats
imageSave1D = false;
imageSave2D = false;
imageSave3D = false;
imageSaveCube= false;
//Loop for the number of values in the token
for(uint i=0;i<imgTestToken->GetNumValues();i++)
{
string value;
imgTestToken->Get(value,i);
if(value == "1D")
{
imageSave1D = true;
}
else if(value == "2D")
{
imageSave2D = true;
}
else if(value == "3D")
{
imageSave3D = true;
}
else if(value == "CUBE")
{
imageSaveCube = true;
}
else
{
LOGERR(("ConfigData::ReadImageConfigData - Unknown GL texture format %s",value.c_str()));
}
}
}
//Get the p-buffer save property
imgTestToken = imgToken->GetChildToken("SavePbufferTex");
if(imgTestToken)
{
imgTestToken->Get(imageSavePBufferTex);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadShaderConfigData(ConfigParser &parser)
{
//Get the outer log section
const ConfigToken * shaderToken = parser.GetToken("ShaderLog");
if(!shaderToken)
{
return;
}
const ConfigToken *shaderTestToken;
//Get if the log is enabled
shaderTestToken = shaderToken->GetChildToken("LogEnabled");
if(shaderTestToken)
{
shaderTestToken->Get(shaderLogEnabled);
}
//Get if we log the state on render calls
shaderTestToken = shaderToken->GetChildToken("RenderCallStateLog");
if(shaderTestToken)
{
shaderTestToken->Get(shaderRenderCallStateLog);
}
//Get if we append log info
shaderTestToken = shaderToken->GetChildToken("AttachLogState");
if(shaderTestToken)
{
shaderTestToken->Get(shaderAttachLogState);
}
//Get if we validate the shaders
shaderTestToken = shaderToken->GetChildToken("ValidatePreRender");
if(shaderTestToken)
{
shaderTestToken->Get(shaderValidatePreRender);
}
//Get if we log uniforms
shaderTestToken = shaderToken->GetChildToken("UniformLogPreRender");
if(shaderTestToken)
{
shaderTestToken->Get(shaderLogUniformsPreRender);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadDisplayListConfigData(ConfigParser &parser)
{
//Get the outer log section
const ConfigToken * listToken = parser.GetToken("DisplayListLog");
if(!listToken)
{
return;
}
const ConfigToken *listTestToken;
//Get if the log is enabled
listTestToken = listToken->GetChildToken("LogEnabled");
if(listTestToken)
{
listTestToken->Get(displayListLogEnabled);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadFrameConfigData(ConfigParser &parser)
{
//Get if the outer log section
const ConfigToken * frameLogToken = parser.GetToken("FrameLog");
if(!frameLogToken)
{
return;
}
const ConfigToken *frameTestToken;
//Get if the log is enabled
frameTestToken = frameLogToken->GetChildToken("LogEnabled");
if(frameTestToken)
{
frameTestToken->Get(frameLogEnabled);
}
//Get the save format
frameImageFormat = "jpg";
frameTestToken = frameLogToken->GetChildToken("SaveFormat");
if(frameTestToken)
{
GetImageFormat(frameTestToken, frameImageFormat);
}
//Get if icon frame buffer saving is enabled
const ConfigToken *frameIconToken = frameLogToken->GetChildToken("FrameIcon");
if(frameIconToken)
{
//Get if icon saving is enabled
frameTestToken = frameIconToken->GetChildToken("Enabled");
if(frameTestToken)
{
frameTestToken->Get(frameIconSave);
}
//Get the size of the icon image
frameTestToken = frameIconToken->GetChildToken("Size");
if(frameTestToken)
{
frameTestToken->Get(frameIconSize);
}
frameTestToken = frameIconToken->GetChildToken("SaveFormat");
if(frameTestToken)
{
GetImageFormat(frameTestToken, frameIconImageFormat);
}
}
//Load the frame movie token data
const ConfigToken *frameMovieToken = frameLogToken->GetChildToken("FrameMovie");
if(frameMovieToken)
{
//Get if movie saving is enabled
frameTestToken = frameMovieToken->GetChildToken("Enabled");
if(frameTestToken)
{
frameTestToken->Get(frameMovieEnabled);
}
//Get the width/height movie
frameTestToken = frameMovieToken->GetChildToken("Size");
if(frameTestToken)
{
if(frameTestToken->GetNumValues() != 2)
{
LOGERR(("FrameMovie - Config - Need two width/height values for size"));
}
else
{
frameTestToken->Get(frameMovieWidth,0);
frameTestToken->Get(frameMovieHeight,1);
}
}
//Get the frame rate of the movie
frameTestToken = frameMovieToken->GetChildToken("FrameRate");
if(frameTestToken)
{
frameTestToken->Get(frameMovieRate);
}
//Get the compression
frameTestToken = frameMovieToken->GetChildToken("Compression");
if(frameTestToken)
{
//Loop for all values
for(uint i=0; i<frameTestToken->GetNumValues(); i++)
{
//Get each codec and add to the array
string newValue;
frameTestToken->Get(newValue, i);
frameMovieCodecs.push_back(newValue);
}
}
//Add a no compression value if none are specified
if(frameMovieCodecs.size() == 0)
{
frameMovieCodecs.push_back("none");
}
}
//Get the pre/post color options
frameTestToken = frameLogToken->GetChildToken("ColorBufferLog");
if(frameTestToken)
{
ReadFramePrePostOptions(frameTestToken,framePreColorSave,framePostColorSave, frameDiffColorSave);
}
//Get the pre/post depth options
frameTestToken = frameLogToken->GetChildToken("DepthBufferLog");
if(frameTestToken)
{
ReadFramePrePostOptions(frameTestToken,framePreDepthSave,framePostDepthSave, frameDiffDepthSave);
}
//Get the pre/post stencil options
frameTestToken = frameLogToken->GetChildToken("StencilBufferLog");
if(frameTestToken)
{
ReadFramePrePostOptions(frameTestToken,framePreStencilSave,framePostStencilSave, frameDiffStencilSave);
}
frameTestToken = frameLogToken->GetChildToken("StencilColors");
if(frameTestToken)
{
//Test for the correct number of colors
if(frameTestToken->GetNumValues() % 2 == 1)
{
LOGERR(("ConfigData::ReadFrameConfigData - Uneven number of stencil colors"));
}
else
{
int currValue =-1;
int retIndex;
uint retColor;
//Loop for all the value pairs
for(uint i=0;i<frameTestToken->GetNumValues();i+=2)
{
//Get the index/color pair
if(!frameTestToken->Get(retIndex,i) ||
!frameTestToken->Get(retColor,i+1))
{
LOGERR(("ConfigData::ReadFrameConfigData - Error retrieving stencil color value/index"));
frameStencilColors.empty();
break;
}
//Check that the index data is sorted
if(retIndex <= currValue)
{
LOGERR(("ConfigData::ReadFrameConfigData - Unsorted array of stencil colors"));
frameStencilColors.empty();
break;
}
//Check bounds
if(retIndex > 255)
{
LOGERR(("ConfigData::ReadFrameConfigData - Stencil index is too large: %d",retIndex));
frameStencilColors.empty();
break;
}
currValue = retIndex;
//Add the pair to the return array
frameStencilColors.push_back(retIndex);
frameStencilColors.push_back(retColor);
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadFramePrePostOptions(const ConfigToken *frameTestToken, bool &preToken, bool &postToken, bool &diffToken) const
{
preToken = false;
postToken= false;
diffToken= false;
//Loop for the number of values in the token
for(uint i=0;i<frameTestToken->GetNumValues();i++)
{
string value;
frameTestToken->Get(value,i);
if(value == "pre")
{
preToken = true;
}
else if(value == "post")
{
postToken = true;
}
else if(value == "diff")
{
diffToken = true;
}
else
{
LOGERR(("ConfigData::ReadFramePrePostOptions - Unknown frame save option %s",value.c_str()));
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadTimerConfigData(ConfigParser &parser)
{
//Get if the outer log section
const ConfigToken * timerToken = parser.GetToken("TimerLog");
if(!timerToken)
{
return;
}
const ConfigToken *timerTestToken;
//Get if the log is enabled
timerTestToken = timerToken->GetChildToken("LogEnabled");
if(timerTestToken)
{
timerTestToken->Get(timerLogEnabled);
}
//Get if we log the state on render calls
timerTestToken = timerToken->GetChildToken("LogCutoff");
if(timerTestToken)
{
timerTestToken->Get(timerLogCutOff);
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::ReadPluginData(ConfigParser &parser)
{
//Get if the outer log section exists
const ConfigToken * pluginDataToken = parser.GetToken("PluginData");
if(!pluginDataToken)
{
return;
}
const ConfigToken *pluginTestToken;
//Get the plugin base directory
pluginTestToken = pluginDataToken->GetChildToken("BaseDir");
if(pluginTestToken)
{
pluginTestToken->Get(pluginBasePath);
//Add a directory seperator
pluginBasePath = pluginBasePath + FileUtils::dirSeparator;
}
//Get the plugin token
pluginTestToken = pluginDataToken->GetChildToken("Plugins");
if(pluginTestToken)
{
//Loop for all children
for(uint i=0;i<pluginTestToken->GetNumChildren();i++)
{
//Get the token and check that it has a value
const ConfigToken *pToken = pluginTestToken->GetChildToken(i);
if(pToken->GetNumValues() != 1)
{
LOGERR(("ConfigData::ReadPluginData - Error in PluginData:Plugins:%s -Expected one dll name value",pToken->GetName().c_str()));
return;
}
//Fill out the plugin data
PluginData newData;
newData.pluginName = pToken->GetName();
pToken->Get(newData.pluginDLLName,0);
//Compile all child config data for the token
for(uint childNum =0;childNum < pToken->GetNumChildren(); childNum++)
{
//Convert each child back to raw config string data
string retString;
if(parser.GenerateConfigString(pToken->GetChildToken(childNum),retString))
{
newData.pluginConfigData += retString;
}
}
//Add the plugin data to the array
pluginDataArray.push_back(newData);
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
void ConfigData::GetImageFormat(const ConfigToken *testToken, string &retValue)
{
//Only process valid tokens
if(!testToken)
{
return;
}
string value;
testToken->Get(value);
if(value == "PNG")
{
retValue = "png";
}
else if(value == "TGA")
{
retValue = "tga";
}
else if(value == "JPG")
{
retValue = "jpg";
}
else
{
LOGERR(("ConfigData::GetImageFormat - Unknown image save format %s",value.c_str()));
}
}
| 8,470 |
3,102 | // Make sure that arguments that begin with @ are left as is in the argument
// stream, and also that @file arguments continue to be processed.
// RUN: echo "-D FOO" > %t.args
// RUN: %clang -rpath @executable_path/../lib @%t.args %s -### 2>&1 | FileCheck %s
// CHECK: "-D" "FOO"
// CHECK: "-rpath" "@executable_path/../lib"
| 114 |
1,837 | //========================================================================
//Copyright 2007-2011 <NAME> <EMAIL>
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
package io.protostuff;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import io.protostuff.Foo.EnumSample;
/**
* Test for re-using a thread-local buffer across many serializations.
*
* @author <NAME>
* @created Jan 15, 2011
*/
public class BufferReuseTest extends StandardTest
{
private static final ThreadLocal<LinkedBuffer> localBuffer =
new ThreadLocal<LinkedBuffer>()
{
@Override
protected LinkedBuffer initialValue()
{
return buf();
}
};
@Override
protected <T> void mergeFrom(byte[] data, int offset, int length, T message, Schema<T> schema) throws IOException
{
ByteArrayInputStream in = new ByteArrayInputStream(data, offset, length);
ProtostuffIOUtil.mergeFrom(in, message, schema, localBuffer.get());
}
@Override
protected <T> byte[] toByteArray(T message, Schema<T> schema)
{
final LinkedBuffer buffer = localBuffer.get();
try
{
return ProtostuffIOUtil.toByteArray(message, schema, buffer);
}
finally
{
buffer.clear();
}
}
public void testFooSizeLimited() throws Exception
{
final Foo fooCompare = SerializableObjects.newFoo(
new Integer[] { 90210, -90210, 0 },
new String[] { "ab", "cd" },
new Bar[] { SerializableObjects.bar, SerializableObjects.negativeBar,
SerializableObjects.bar, SerializableObjects.negativeBar,
SerializableObjects.bar, SerializableObjects.negativeBar },
new EnumSample[] { EnumSample.TYPE0, EnumSample.TYPE2 },
new ByteString[] { ByteString.copyFromUtf8("ef"), ByteString.copyFromUtf8("gh") },
new Boolean[] { true, false },
new Float[] { 1234.4321f, -1234.4321f, 0f },
new Double[] { 12345678.87654321d, -12345678.87654321d, 0d },
new Long[] { 7060504030201l, -7060504030201l, 0l });
ByteArrayOutputStream out = new ByteArrayOutputStream();
final LinkedBuffer buffer = LinkedBuffer.allocate(256);
try
{
ProtostuffIOUtil.writeDelimitedTo(out, fooCompare, fooCompare.cachedSchema(),
buffer);
}
finally
{
buffer.clear();
}
byte[] data = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(data);
Foo foo = new Foo();
boolean hasException = true;
try
{
ProtostuffIOUtil.mergeDelimitedFrom(in, foo, foo.cachedSchema(), buffer);
hasException = false;
}
catch (ProtostuffException e)
{
assertTrue(e.getMessage().startsWith("size limit exceeded."));
}
assertTrue(hasException);
}
}
| 1,547 |
854 | __________________________________________________________________________________________________
sample 152 ms submission
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = set()
def add(self, key):
self.data.add(key)
def remove(self, key):
if self.contains(key):
self.data.remove(key)
def contains(self, key):
return key in self.data
__________________________________________________________________________________________________
sample 17004 kb submission
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.capacity = 8
self.size = 0
self.s = [None]*8
self.lf = float(2)/3
def myhash(self, key): # can be modified to hash other hashable objects like built in python hash function
return key%self.capacity
def add(self, key):
"""
:type key: int
:rtype: void
"""
if float(self.size)/self.capacity >= self.lf:
self.capacity <<= 1
ns = [None]*self.capacity
for i in range(self.capacity >> 1):
if self.s[i] and self.s[i] != "==TOMBSTONE==":
n = self.myhash(self.s[i])
while ns[n] is not None:
n = (5*n+1)%self.capacity
ns[n] = self.s[i]
self.s = ns
h = self.myhash(key)
while self.s[h] is not None:
if self.s[h] == key:
return
h = (5*h + 1) % self.capacity
if self.s[h] == "==TOMBSTONE==":
break
self.s[h] = key
self.size += 1
def remove(self, key):
"""
:type key: int
:rtype: void
"""
h = self.myhash(key)
while self.s[h]:
if self.s[h] == key:
self.s[h] = "==TOMBSTONE=="
self.size -= 1
return
h = (5*h+1)%self.capacity
def contains(self, key):
"""
Returns true if this set contains the specified element
:type key: int
:rtype: bool
"""
h = self.myhash(key)
while self.s[h] is not None:
if self.s[h] == key:
return True
h = (5*h + 1)%self.capacity
return False
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
__________________________________________________________________________________________________
| 1,328 |
348 | {"nom":"Bolazec","circ":"6ème circonscription","dpt":"Finistère","inscrits":156,"abs":76,"votants":80,"blancs":17,"nuls":7,"exp":56,"res":[{"nuance":"REM","nom":"<NAME>","voix":32},{"nuance":"LR","nom":"<NAME>","voix":24}]} | 90 |
782 | /*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.feature.detect.intensity;
import boofcv.BoofTesting;
import boofcv.alg.feature.detect.intensity.impl.ImplIntegralImageFeatureIntensity;
import boofcv.alg.misc.GImageMiscOps;
import boofcv.alg.transform.ii.IntegralImageOps;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.GrayS32;
import boofcv.testing.BoofStandardJUnit;
import org.junit.jupiter.api.Test;
/**
* @author <NAME>
*/
public class TestIntegralImageFeatureIntensity extends BoofStandardJUnit {
int width = 60;
int height = 70;
/**
* Compares hessian intensity against a naive implementation
*/
@Test void hessian_F32() {
GrayF32 original = new GrayF32(width,height);
GrayF32 integral = new GrayF32(width,height);
GrayF32 found = new GrayF32(width,height);
GrayF32 expected = new GrayF32(width,height);
GImageMiscOps.fillUniform(original, rand, 0, 50);
IntegralImageOps.transform(original,integral);
int size = 9;
for( int skip = 1; skip <= 4; skip++ ) {
found.reshape(width/skip,height/skip);
expected.reshape(width/skip,height/skip);
ImplIntegralImageFeatureIntensity.hessianNaive(integral,skip,size,expected);
IntegralImageFeatureIntensity.hessian(integral,skip,size,found);
BoofTesting.assertEquals(expected,found, 1e-4f);
}
}
/**
* Compares hessian intensity against a naive implementation
*/
@Test void hessian_S32() {
GrayS32 original = new GrayS32(width,height);
GrayS32 integral = new GrayS32(width,height);
GrayF32 found = new GrayF32(width,height);
GrayF32 expected = new GrayF32(width,height);
GImageMiscOps.fillUniform(original, rand, 0, 50);
IntegralImageOps.transform(original,integral);
int size = 9;
for( int skip = 1; skip <= 4; skip++ ) {
found.reshape(width/skip,height/skip);
expected.reshape(width/skip,height/skip);
ImplIntegralImageFeatureIntensity.hessianNaive(integral,skip,size,expected);
IntegralImageFeatureIntensity.hessian(integral,skip,size,found);
BoofTesting.assertEquals(expected,found, 1e-4f);
}
}
}
| 914 |
1,110 | from contextlib import contextmanager
from unittest import skipIf, skipUnless
import os
import io
import socket
import sys
from sphinx.application import Sphinx
from sphinx.errors import SphinxWarning
try:
import enchant
except ImportError:
enchant = None
import cms
from cms.test_utils.testcases import CMSTestCase
from cms.test_utils.util.context_managers import TemporaryDirectory
ROOT_DIR = os.path.dirname(cms.__file__)
DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'docs'))
def has_no_internet():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(5)
s.connect(('4.4.4.2', 80))
s.send(b"hello")
except socket.error: # no internet
return True
return False
@contextmanager
def tmp_list_append(lst, x):
lst.append(x)
try:
yield
finally:
if x in lst:
lst.remove(x)
class DocsTestCase(CMSTestCase):
"""
Test docs building correctly for HTML
"""
@skipIf(has_no_internet(), "No internet")
def test_html(self):
status = io.StringIO()
with TemporaryDirectory() as OUT_DIR:
app = Sphinx(
srcdir=DOCS_DIR,
confdir=DOCS_DIR,
outdir=OUT_DIR,
doctreedir=OUT_DIR,
buildername="html",
warningiserror=True,
status=status,
)
try:
app.build()
except: # noqa: E722
print(status.getvalue())
raise
@skipIf(has_no_internet(), "No internet")
@skipIf(enchant is None, "Enchant not installed")
@skipUnless(os.environ.get('TEST_DOCS') == '1', 'Skipping for simplicity')
def test_spelling(self):
status = io.StringIO()
with TemporaryDirectory() as OUT_DIR:
with tmp_list_append(sys.argv, 'spelling'):
try:
app = Sphinx(
srcdir=DOCS_DIR,
confdir=DOCS_DIR,
outdir=OUT_DIR,
doctreedir=OUT_DIR,
buildername="spelling",
warningiserror=True,
status=status,
confoverrides={
'extensions': [
'djangocms',
'sphinx.ext.intersphinx',
'sphinxcontrib.spelling'
]
}
)
app.build()
self.assertEqual(app.statuscode, 0, status.getvalue())
except SphinxWarning:
# while normally harmless, causes a test failure
pass
except: # noqa: E722
print(status.getvalue())
raise
| 1,625 |
852 | #ifndef TkDetLayers_Phase2EndcapRing_h
#define TkDetLayers_Phase2EndcapRing_h
#include "TrackingTools/DetLayers/interface/GeometricSearchDet.h"
#include "Utilities/BinningTools/interface/PeriodicBinFinderInPhi.h"
#include "SubLayerCrossings.h"
#include "DataFormats/GeometrySurface/interface/BoundDisk.h"
/** A concrete implementation for TID rings
*/
#pragma GCC visibility push(hidden)
class Phase2EndcapRing final : public GeometricSearchDet {
public:
Phase2EndcapRing(std::vector<const GeomDet*>& innerDets,
std::vector<const GeomDet*>& outerDets,
const std::vector<const GeomDet*>& innerDetBrothers = std::vector<const GeomDet*>(),
const std::vector<const GeomDet*>& outerDetBrothers = std::vector<const GeomDet*>());
~Phase2EndcapRing() override;
// GeometricSearchDet interface
const BoundSurface& surface() const override { return *theDisk; }
const std::vector<const GeomDet*>& basicComponents() const override { return theDets; }
const std::vector<const GeometricSearchDet*>& components() const override __attribute__((cold));
std::pair<bool, TrajectoryStateOnSurface> compatible(const TrajectoryStateOnSurface&,
const Propagator&,
const MeasurementEstimator&) const override;
void groupedCompatibleDetsV(const TrajectoryStateOnSurface& tsos,
const Propagator& prop,
const MeasurementEstimator& est,
std::vector<DetGroup>& result) const override __attribute__((hot));
//Extension of interface
virtual const BoundDisk& specificSurface() const { return *theDisk; }
private:
// private methods for the implementation of groupedCompatibleDets()
SubLayerCrossings computeCrossings(const TrajectoryStateOnSurface& tsos, PropagationDirection propDir) const
__attribute__((hot));
bool addClosest(const TrajectoryStateOnSurface& tsos,
const Propagator& prop,
const MeasurementEstimator& est,
const SubLayerCrossing& crossing,
std::vector<DetGroup>& result,
std::vector<DetGroup>& brotherresult) const __attribute__((hot));
void searchNeighbors(const TrajectoryStateOnSurface& tsos,
const Propagator& prop,
const MeasurementEstimator& est,
const SubLayerCrossing& crossing,
float window,
std::vector<DetGroup>& result,
std::vector<DetGroup>& brotherresult,
bool checkClosest) const __attribute__((hot));
const std::vector<const GeomDet*>& subLayer(int ind) const { return (ind == 0 ? theFrontDets : theBackDets); }
const std::vector<const GeomDet*>& subLayerBrothers(int ind) const {
return (ind == 0 ? theFrontDetBrothers : theBackDetBrothers);
}
private:
std::vector<const GeomDet*> theDets;
std::vector<const GeomDet*> theFrontDets;
std::vector<const GeomDet*> theBackDets;
std::vector<const GeomDet*> theFrontDetBrothers;
std::vector<const GeomDet*> theBackDetBrothers;
ReferenceCountingPointer<BoundDisk> theDisk;
ReferenceCountingPointer<BoundDisk> theFrontDisk;
ReferenceCountingPointer<BoundDisk> theBackDisk;
typedef PeriodicBinFinderInPhi<float> BinFinderType;
BinFinderType theFrontBinFinder;
BinFinderType theBackBinFinder;
};
#pragma GCC visibility pop
#endif
| 1,471 |
2,195 | from aim.sdk import Repo
from aim.web.api.runs.utils import get_run_props
from performance_tests.utils import timing
@timing()
def collect_runs_data(query):
repo = Repo.default_repo()
runs = repo.query_runs(query)
runs_dict = {}
for run_trace_collection in runs.iter_runs():
run = run_trace_collection.run
runs_dict[run.hash] = {
'params': run[...],
'traces': run.collect_sequence_info(sequence_types='metric'),
'props': get_run_props(run)
}
@timing()
def collect_metrics_data(query):
repo = Repo.default_repo()
runs_dict = {}
runs = repo.query_metrics(query=query)
for run_trace_collection in runs.iter_runs():
run = None
traces_list = []
for trace in run_trace_collection.iter():
if not run:
run = run_trace_collection.run
iters, values = trace.values.sparse_numpy()
traces_list.append({
'name': trace.name,
'context': trace.context.to_dict(),
'values': values,
'iters': iters,
'epochs': trace.epochs.values_numpy(),
'timestamps': trace.timestamps.values_numpy()
})
if run:
runs_dict[run.hash] = {
'traces': traces_list,
'params': run[...],
'props': get_run_props(run),
}
@timing()
def query_runs(query):
repo = Repo.default_repo()
runs = list(repo.query_runs(query=query).iter_runs())
@timing()
def query_metrics(query):
repo = Repo.default_repo()
metrics = list(repo.query_metrics(query=query).iter())
| 823 |
11,496 | <gh_stars>1000+
{
"title": "Launcher",
"description": "Launcher settings.",
"jupyter.lab.shortcuts": [
{
"command": "launcher:create",
"keys": [""],
"selector": "body"
}
],
"properties": {},
"additionalProperties": false,
"type": "object"
}
| 122 |
739 | <gh_stars>100-1000
package org.fxmisc.richtext.keyboard.navigation;
import javafx.stage.Stage;
import org.fxmisc.richtext.InlineCssTextAreaAppTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import static javafx.scene.input.KeyCode.DOWN;
import static javafx.scene.input.KeyCode.UP;
import static org.junit.Assert.assertEquals;
public class MultiLineJaggedTextTests extends InlineCssTextAreaAppTest {
@Rule
public Timeout globalTimeout = Timeout.seconds(10);
String threeLinesOfText = "Some long amount of text to take up a lot of space in the given area.";
@Override
public void start(Stage stage) throws Exception {
super.start(stage);
stage.setWidth(200);
area.replaceText(threeLinesOfText);
area.setWrapText(true);
}
@Test
public void pressing_down_moves_caret_to_next_line() {
area.moveTo(0);
assertEquals(0, area.getCaretSelectionBind().getLineIndex().getAsInt());
push(DOWN);
assertEquals(1, area.getCaretSelectionBind().getLineIndex().getAsInt());
}
@Test
public void pressing_up_moves_caret_to_previous_line() {
area.moveTo(area.getLength());
int lastLineIndex = area.getParagraphLinesCount(0) - 1;
assertEquals(lastLineIndex, area.getCaretSelectionBind().getLineIndex().getAsInt());
push(UP);
assertEquals(lastLineIndex - 1, area.getCaretSelectionBind().getLineIndex().getAsInt());
}
}
| 584 |
879 | package org.zstack.utils.logging;
/**
* Goals:
* 1. log4j interface
* 2. two category logs: (1) ordinary log outputting to primary log file (2) supporting log that should be present to
* customer or support team saves to another file
* 3. use gson to attach parameters to log
* 4. cooperate with EventKit system, supporting log should be able to be published as event
* @author frank
*
*/
public interface CLogger {
void trace(String msg, Throwable e);
void trace(String msg);
void debug(String msg, Throwable e);
void debug(String msg);
void info(String msg, Throwable e);
void info(String msg);
void warn(String msg, Throwable e);
void warn(String msg);
void error(String msg, Throwable e);
void error(String msg);
void fatal(String msg, Throwable e);
void fatal(String msg);
boolean isTraceEnabled();
}
| 279 |
435 | {
"copyright_text": null,
"description": "GPUs are typically used to accelerate deep learning models, but they haven't been widely deployed for traditional machine learning. This talk will cover cuML's GPU based implementation of Decision Trees and Random Forest algorithms, aimed to provide 10x-50x speedup and a new library called Forest Inference Library (FIL), which allows GPU accelerated inference of different pretrained forest models",
"duration": 2056,
"language": "eng",
"recorded": "2019-12-07",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://pydata.org/austin2019/schedule/"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"GPU",
"GPUComputing",
"machine learning"
],
"thumbnail_url": "https://i.ytimg.com/vi/B4meXLSq3hQ/maxresdefault.jpg",
"title": "Speeding up Machine Learning tasks using GPUs in Python",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=B4meXLSq3hQ"
}
]
}
| 351 |
1,442 | <reponame>VersiraSec/epsilon-cfw
#include <stddef.h>
#include <string.h>
/* See the "Run-time ABI for the ARM Architecture", Section 4.3.4 */
void __aeabi_memcpy(void * dest, const void * src, size_t n) {
memcpy(dest, src, n);
}
// TODO: optimize aeabi_memcpy4 to take advantage of the 4-byte alignment
void __aeabi_memcpy4(void * dest, const void * src, size_t n) {
memcpy(dest, src, n);
}
| 161 |
1,197 | <reponame>Plutonian/controlsfx
/**
* Copyright (c) 2018 ControlsFX
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of ControlsFX, any associated website, nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CONTROLSFX BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.controlsfx.control;
import impl.org.controlsfx.skin.ListActionViewSkin;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.control.Cell;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Skin;
import javafx.util.Callback;
import org.controlsfx.control.action.Action;
import java.util.function.Consumer;
/**
* A control used to perform actions on a ListView. Actions can be
* added by accessing the {@link #getActions() action list}. These actions are
* represented as buttons on the control. These buttons can be moved to any side
* of the ListView using the {@link #sideProperty()}.
*
* <h3>Screenshot</h3>
*
* <center><img src="list-action-view.png" alt="Screenshot of ListActionView"></center>
*
* <h3>Code Example</h3>
*
* <pre>
* ListActionView<String> view = new ListActionView<>();
* view.getItems().add("One", "Two", "Three");
* view.getActions().add(new ListActionView.ListAction<String>() {
* {
* setGraphic(new FontAwesome().create(FontAwesome.Glyph.BOLT));
* }
*
* {@literal @}Override
* public void initialize(ListView<String> listView) {
* setEventHandler(e -> System.out.println("Action fired!"));
* }
* });
* view.getActions().add(ActionUtils.ACTION_SEPARATOR);
* </pre>
*
* @param <T> Type of ListActionView.
*/
public class ListActionView<T> extends ControlsFXControl {
private static final String DEFAULT_STYLE = "list-action-view";
public ListActionView() {
getStyleClass().add(DEFAULT_STYLE);
}
// -- items
private final ObservableList<T> items = FXCollections.observableArrayList();
/**
* The list of items for the list view.
*
* @return An ObservableList of T.
*/
public final ObservableList<T> getItems() {
return items;
}
// -- actions
private final ObservableList<Action> actions = FXCollections.observableArrayList();
/**
* The list of actions shown on one of the sides of the ListView.
* All actions except, {@link org.controlsfx.control.action.ActionUtils#ACTION_SEPARATOR}
* and {@link org.controlsfx.control.action.ActionUtils#ACTION_SPAN}, are represented as buttons.
*
* <p>For actions dependent on the internal ListView, an instance of {@link ListAction} should
* be used.</p>
*
* @return An ObservableList of actions.
*/
public final ObservableList<Action> getActions() {
return actions;
}
// -- side
private ObjectProperty<Side> side;
/**
* The current position of the action buttons in the ListActionView.
*
* @defaultValue {@link Side#LEFT}
* @return The current position of the action buttons in the ListActionView.
*/
public Side getSide() {
return side == null ? null : side.get();
}
/**
* The position of the action buttons in the ListActionView.
*/
public ObjectProperty<Side> sideProperty() {
if (side == null) {
side = new SimpleObjectProperty<>(this, "side", Side.LEFT);
}
return side;
}
/**
* The position to place the action buttons in this ListActionView.
* Whenever this changes the ListActionView will immediately update the
* location of the action buttons to reflect the same.
*
* @param side The side to place the action buttons.
*/
public void setSide(Side side) {
this.side.set(side);
}
// -- Cell Factory
private ObjectProperty<Callback<ListView<T>, ListCell<T>>> cellFactory;
/**
* Sets a new cell factory for the list view. This forces all old
* {@link ListCell}'s to be thrown away, and new ListCell's created with the
* new cell factory.
*/
public final void setCellFactory(Callback<ListView<T>, ListCell<T>> value) {
cellFactoryProperty().set(value);
}
/**
* Returns the current cell factory.
*/
public final Callback<ListView<T>, ListCell<T>> getCellFactory() {
return cellFactory == null ? null : cellFactory.get();
}
/**
* Setting a custom cell factory has the effect of deferring all cell
* creation, allowing for total customization of the cell. Internally, the
* ListView is responsible for reusing ListCells - all that is necessary is
* for the custom cell factory to return from this function a ListCell which
* might be usable for representing any item in the ListView.
*
* <p>Refer to the {@link Cell} class documentation for more detail.</p>
*/
public final ObjectProperty<Callback<ListView<T>, ListCell<T>>> cellFactoryProperty() {
if (cellFactory == null) {
cellFactory = new SimpleObjectProperty<>(this, "cellFactory");
}
return cellFactory;
}
@Override
protected Skin<?> createDefaultSkin() {
return new ListActionViewSkin<>(this);
}
@Override
public String getUserAgentStylesheet() {
return getUserAgentStylesheet(ListActionView.class, "listactionview.css");
}
/**
* Specialized actions for ListActionView which get access to the internal ListView. A user can add a custom action to the
* control by extending this class and adding its instance to the {@link ListActionView#getActions() action list}.
*
* @param <T> Type of ListActionView to which this ListAction will be added.
*/
public static abstract class ListAction<T> extends Action {
/**
* Creates a new instance of ListAction with the graphic node.
* @param graphic Graphic to be shown in relation to this action.
*/
public ListAction(Node graphic) {
this(graphic, "");
}
/**
* Creates a new instance of ListAction with the provided graphic and text.
* @param graphic Graphic to be shown in relation to this action.
* @param text The text for the Action.
*/
public ListAction(Node graphic, String text) {
super(text);
setGraphic(graphic);
}
/**
* Can be used to define properties or bindings for actions
* which are directly dependent on the list view.
* @param listView The list view
*/
public abstract void initialize(ListView<T> listView);
@Override
protected final void setEventHandler(Consumer<ActionEvent> eventHandler) {
super.setEventHandler(eventHandler);
}
}
}
| 2,903 |
367 | <reponame>SAP/cloud-commerce-spartacus-storefront
{
"$schema": "http://json-schema.org/schema",
"$id": "UserSchematics",
"title": "User Schematics",
"description": "Most of the Spartacus features require User Account feature to be properly configured.",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "The name of the project.",
"$default": {
"$source": "projectName"
}
},
"debug": {
"description": "Display additional details during the running process.",
"type": "boolean",
"default": false
},
"lazy": {
"type": "boolean",
"description": "Lazy load the user features.",
"default": true
},
"features": {
"type": "array",
"uniqueItems": true,
"items": {
"enum": ["User-Account", "User-Profile"],
"type": "string"
},
"default": ["User-Account", "User-Profile"],
"x-prompt": "Which features would you like to set up from the User library? Please note that for most Spartacus features to be properly configured, the User-Account feature is required."
}
},
"required": []
}
| 444 |
453 | <filename>python/Microsoftpython/Class 12:loops/class 12:loops.py<gh_stars>100-1000
# python之中僅有兩種循環,for和while
# 以下先從for循環講起,意思為打印出name變量中每一個值
for name in ['Heisenberg', 'White', 'Walter', 'Jesse', 'Gustavo']:
print(name)
print()
# 下面range是代表index變量是從數字0至1
for index in range(0,2):
print(index)
print()
# 下面是while的應用,意思為while(當)index的值小於name變量詞的值數量
# 則打印(name【index數值位】),index加1,(name【index數值位】),index加1
# 如此循環直到while(當)index值大於或等於name值數量,while循環結束
name = ['Heisenebrg', 'White', 'Walter', 'Jesse', 'Gustavo']
index = 0
while index<len(name):
print(name[index])
index = index + 1
print()
# 同樣的意義用for循環來做就更簡潔,所以可以用for就不用while了
for i in name:
print(i)
# 且for為有限循環,循環完即停止;而while為無限循環,假若條件設錯就會造成無限循環錯誤
| 621 |
999 | import json
import logging
from typing import Any
from typing import Dict
from typing import Set
import botocore
from cloudaux.aws.sts import boto3_cached_conn
from repokid.exceptions import BlocklistError
from repokid.filters import Filter
from repokid.role import RoleList
from repokid.types import RepokidFilterConfig
LOGGER = logging.getLogger("repokid")
def get_blocklist_from_bucket(bucket_config: Dict[str, Any]) -> Dict[str, Any]:
blocklist_json: Dict[str, Any]
try:
s3_resource = boto3_cached_conn(
"s3",
service_type="resource",
account_number=bucket_config.get("account_number"),
assume_role=bucket_config.get("assume_role", None),
session_name="repokid",
region=bucket_config.get("region", "us-west-2"),
)
s3_obj = s3_resource.Object(
bucket_name=bucket_config["bucket_name"], key=bucket_config["key"]
)
blocklist = s3_obj.get()["Body"].read().decode("utf-8")
blocklist_json = json.loads(blocklist)
# Blocklist problems are really bad and we should quit rather than silently continue
except (botocore.exceptions.ClientError, AttributeError):
LOGGER.critical(
"S3 blocklist config was set but unable to connect retrieve object, quitting"
)
raise BlocklistError("Could not retrieve blocklist")
except ValueError:
LOGGER.critical(
"S3 blocklist config was set but the returned file is bad, quitting"
)
raise BlocklistError("Could not parse blocklist")
if set(blocklist_json.keys()) != {"arns", "names"}:
LOGGER.critical("S3 blocklist file is malformed, quitting")
raise BlocklistError("Could not parse blocklist")
return blocklist_json
class BlocklistFilter(Filter):
blocklist_json: Dict[str, Any] = {}
def __init__(self, config: RepokidFilterConfig = None) -> None:
super().__init__(config=config)
if not config:
LOGGER.error(
"No configuration provided, cannot initialize Blocklist Filter"
)
return
current_account = config.get("current_account") or ""
if not current_account:
LOGGER.error("Unable to get current account for Blocklist Filter")
blocklisted_role_names = set()
blocklisted_role_names.update(
[rolename.lower() for rolename in config.get(current_account, [])]
)
blocklisted_role_names.update(
[rolename.lower() for rolename in config.get("all", [])]
)
if BlocklistFilter.blocklist_json:
blocklisted_role_names.update(
[
name.lower()
for name, accounts in BlocklistFilter.blocklist_json[
"names"
].items()
if ("all" in accounts or config.get("current_account") in accounts)
]
)
self.blocklisted_arns: Set[str] = (
set()
if not BlocklistFilter.blocklist_json
else set(BlocklistFilter.blocklist_json.get("arns", []))
)
self.blocklisted_role_names = blocklisted_role_names
@classmethod
def init_blocklist(cls, config: RepokidFilterConfig) -> None:
if not config:
LOGGER.error("No config provided for blocklist filter")
raise BlocklistError("No config provided for blocklist filter")
if not cls.blocklist_json:
bucket_config = config.get(
"blocklist_bucket", config.get("blacklist_bucket", {})
)
if bucket_config:
cls.blocklist_json = get_blocklist_from_bucket(bucket_config)
def apply(self, input_list: RoleList) -> RoleList:
blocklisted_roles = RoleList([])
for role in input_list:
if (
role.role_name.lower() in self.blocklisted_role_names
or role.arn in self.blocklisted_arns
):
blocklisted_roles.append(role)
return blocklisted_roles
| 1,829 |
977 | <gh_stars>100-1000
package io.leangen.graphql.execution;
import io.leangen.graphql.metadata.Operation;
import io.leangen.graphql.metadata.Resolver;
import java.util.function.Consumer;
public class InvocationContext {
private final Operation operation;
private final Resolver resolver;
private final ResolutionEnvironment resolutionEnvironment;
private final Object[] arguments;
InvocationContext(Operation operation, Resolver resolver, ResolutionEnvironment resolutionEnvironment, Object[] arguments) {
this.operation = operation;
this.resolver = resolver;
this.resolutionEnvironment = resolutionEnvironment;
this.arguments = arguments;
}
public Operation getOperation() {
return operation;
}
public Resolver getResolver() {
return resolver;
}
public ResolutionEnvironment getResolutionEnvironment() {
return resolutionEnvironment;
}
public Object[] getArguments() {
return arguments;
}
public static Builder builder() {
return new Builder();
}
public InvocationContext transform(Consumer<Builder> builderConsumer) {
Builder builder = new Builder()
.withOperation(this.operation)
.withResolver(this.resolver)
.withResolutionEnvironment(this.resolutionEnvironment)
.withArguments(this.arguments);
builderConsumer.accept(builder);
return builder.build();
}
@SuppressWarnings("WeakerAccess")
public static class Builder {
private Operation operation;
private Resolver resolver;
private ResolutionEnvironment resolutionEnvironment;
private Object[] arguments;
public Builder withOperation(Operation operation) {
this.operation = operation;
return this;
}
public Builder withResolver(Resolver resolver) {
this.resolver = resolver;
return this;
}
public Builder withResolutionEnvironment(ResolutionEnvironment resolutionEnvironment) {
this.resolutionEnvironment = resolutionEnvironment;
return this;
}
public Builder withArguments(Object[] arguments) {
this.arguments = arguments;
return this;
}
public InvocationContext build() {
return new InvocationContext(operation, resolver, resolutionEnvironment, arguments);
}
}
}
| 902 |
887 | <gh_stars>100-1000
/*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* 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 <functional>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Quaternion.hh>
#include <ignition/math/Vector3.hh>
#include "gazebo/rendering/Visual.hh"
#include "gazebo/gui/Conversions.hh"
#include "gazebo/gui/building/BuildingEditorEvents.hh"
#include "gazebo/gui/building/BuildingMaker.hh"
#include "gazebo/gui/building/BuildingModelManip.hh"
#include "gazebo/gui/building/BuildingModelManipPrivate.hh"
using namespace gazebo;
using namespace gui;
/////////////////////////////////////////////////
BuildingModelManip::BuildingModelManip()
: dataPtr(new BuildingModelManipPrivate)
{
this->dataPtr->level = 0;
this->dataPtr->connections.push_back(
gui::editor::Events::ConnectChangeBuildingLevel(
std::bind(&BuildingModelManip::OnChangeLevel, this,
std::placeholders::_1)));
}
/////////////////////////////////////////////////
BuildingModelManip::~BuildingModelManip()
{
}
/////////////////////////////////////////////////
void BuildingModelManip::SetName(const std::string &_name)
{
this->dataPtr->name = _name;
}
/////////////////////////////////////////////////
void BuildingModelManip::SetVisual(const rendering::VisualPtr &_visual)
{
this->dataPtr->visual = _visual;
}
/////////////////////////////////////////////////
std::string BuildingModelManip::Name() const
{
return this->dataPtr->name;
}
/////////////////////////////////////////////////
rendering::VisualPtr BuildingModelManip::Visual() const
{
return this->dataPtr->visual;
}
/////////////////////////////////////////////////
double BuildingModelManip::Transparency() const
{
return this->dataPtr->transparency;
}
/////////////////////////////////////////////////
ignition::math::Color BuildingModelManip::Color() const
{
return this->dataPtr->color;
}
/////////////////////////////////////////////////
std::string BuildingModelManip::Texture() const
{
return this->dataPtr->texture;
}
/////////////////////////////////////////////////
void BuildingModelManip::SetMaker(BuildingMaker *_maker)
{
this->dataPtr->maker = _maker;
}
/////////////////////////////////////////////////
void BuildingModelManip::OnSizeChanged(double _width, double _depth,
double _height)
{
this->dataPtr->size =
BuildingMaker::ConvertSize(_width, _depth, _height);
double dScaleZ = this->dataPtr->visual->Scale().Z() - this->dataPtr->size.Z();
this->dataPtr->visual->SetScale(this->dataPtr->size);
auto originalPos = this->dataPtr->visual->Position();
auto newPos = originalPos - ignition::math::Vector3d(0, 0, dScaleZ/2.0);
this->dataPtr->visual->SetPosition(newPos);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnPoseChanged(double _x, double _y, double _z,
double _roll, double _pitch, double _yaw)
{
this->SetPose(_x, _y, _z, _roll, _pitch, _yaw);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnPoseOriginTransformed(double _x, double _y,
double _z, double _roll, double _pitch, double _yaw)
{
// Handle translations, currently used by polylines
auto trans = BuildingMaker::ConvertPose(_x, -_y, _z, _roll, _pitch,
_yaw);
auto oldPose = this->dataPtr->visual->GetParent()->WorldPose();
this->dataPtr->visual->GetParent()->SetWorldPose(oldPose + trans);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnPositionChanged(double _x, double _y, double _z)
{
double scaledX = BuildingMaker::Convert(_x);
double scaledY = BuildingMaker::Convert(-_y);
double scaledZ = BuildingMaker::Convert(_z);
this->dataPtr->visual->GetParent()->SetWorldPosition(ignition::math::Vector3d(
scaledX, scaledY, scaledZ));
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnWidthChanged(double _width)
{
double scaledWidth = BuildingMaker::Convert(_width);
this->dataPtr->size = this->dataPtr->visual->Scale();
this->dataPtr->size.X(scaledWidth);
this->dataPtr->visual->SetScale(this->dataPtr->size);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnDepthChanged(double _depth)
{
double scaledDepth = BuildingMaker::Convert(_depth);
this->dataPtr->size = this->dataPtr->visual->Scale();
this->dataPtr->size.Y(scaledDepth);
this->dataPtr->visual->SetScale(this->dataPtr->size);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnHeightChanged(double _height)
{
double scaledHeight = BuildingMaker::Convert(_height);
this->dataPtr->size = this->dataPtr->visual->Scale();
this->dataPtr->size.Z(scaledHeight);
auto dScale = this->dataPtr->visual->Scale() - this->dataPtr->size;
auto originalPos = this->dataPtr->visual->Position();
this->dataPtr->visual->SetScale(this->dataPtr->size);
auto newPos = originalPos - ignition::math::Vector3d(0, 0, dScale.Z()/2.0);
this->dataPtr->visual->SetPosition(newPos);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnPosXChanged(double _posX)
{
auto visualPose = this->dataPtr->visual->GetParent()->WorldPose();
double scaledX = BuildingMaker::Convert(_posX);
visualPose.Pos().X(scaledX);
this->dataPtr->visual->GetParent()->SetWorldPosition(visualPose.Pos());
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnPosYChanged(double _posY)
{
auto visualPose = this->dataPtr->visual->GetParent()->WorldPose();
double scaledY = BuildingMaker::Convert(_posY);
visualPose.Pos().Y(-scaledY);
this->dataPtr->visual->GetParent()->SetWorldPosition(visualPose.Pos());
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnPosZChanged(double _posZ)
{
auto visualPose = this->dataPtr->visual->GetParent()->WorldPose();
double scaledZ = BuildingMaker::Convert(_posZ);
visualPose.Pos().Z(scaledZ);
this->dataPtr->visual->GetParent()->SetWorldPosition(visualPose.Pos());
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnYawChanged(double _yaw)
{
double newYaw = BuildingMaker::ConvertAngle(_yaw);
auto angles = this->dataPtr->visual->Rotation().Euler();
angles.Z(-newYaw);
this->dataPtr->visual->GetParent()->SetRotation(
ignition::math::Quaterniond(angles));
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnRotationChanged(double _roll, double _pitch,
double _yaw)
{
this->SetRotation(_roll, _pitch, _yaw);
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnLevelChanged(int _level)
{
this->SetLevel(_level);
}
/////////////////////////////////////////////////
void BuildingModelManip::OnColorChanged(const ignition::math::Color &_color)
{
this->SetColor(Conversions::Convert(_color));
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnTextureChanged(const std::string &_texture)
{
this->SetTexture(QString::fromStdString(_texture));
this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnTransparencyChanged(float _transparency)
{
this->SetTransparency(_transparency);
// For now transparency is used only to aid in the preview and doesn't affect
// the saved building
// this->dataPtr->maker->BuildingChanged();
}
/////////////////////////////////////////////////
void BuildingModelManip::OnDeleted()
{
this->dataPtr->maker->RemovePart(this->dataPtr->name);
}
/////////////////////////////////////////////////
void BuildingModelManip::SetPose(double _x, double _y, double _z,
double _roll, double _pitch, double _yaw)
{
this->SetPosition(_x, _y, _z);
this->SetRotation(_roll, _pitch, _yaw);
}
/////////////////////////////////////////////////
void BuildingModelManip::SetPosition(double _x, double _y, double _z)
{
double scaledX = BuildingMaker::Convert(_x);
double scaledY = BuildingMaker::Convert(-_y);
double scaledZ = BuildingMaker::Convert(_z);
this->dataPtr->visual->GetParent()->SetWorldPosition(
ignition::math::Vector3d(scaledX, scaledY, scaledZ));
}
/////////////////////////////////////////////////
void BuildingModelManip::SetRotation(double _roll, double _pitch, double _yaw)
{
double rollRad = BuildingMaker::ConvertAngle(_roll);
double pitchRad = BuildingMaker::ConvertAngle(_pitch);
double yawRad = BuildingMaker::ConvertAngle(_yaw);
this->dataPtr->visual->GetParent()->SetRotation(
ignition::math::Quaterniond(rollRad, pitchRad, -yawRad));
}
/////////////////////////////////////////////////
void BuildingModelManip::SetSize(double _width, double _depth, double _height)
{
this->dataPtr->size = BuildingMaker::ConvertSize(_width, _depth, _height);
auto dScale = this->dataPtr->visual->Scale() - this->dataPtr->size;
auto originalPos = this->dataPtr->visual->Position();
this->dataPtr->visual->SetPosition(ignition::math::Vector3d(0, 0, 0));
this->dataPtr->visual->SetScale(this->dataPtr->size);
// adjust position due to difference in pivot points
auto newPos = originalPos - dScale/2.0;
this->dataPtr->visual->SetPosition(newPos);
}
/////////////////////////////////////////////////
void BuildingModelManip::SetColor(QColor _color)
{
ignition::math::Color newColor(_color.red(), _color.green(), _color.blue(),
1.0f);
this->dataPtr->color = newColor;
this->dataPtr->visual->SetAmbient(this->dataPtr->color);
this->dataPtr->maker->BuildingChanged();
emit ColorChanged(Conversions::Convert(_color));
}
/////////////////////////////////////////////////
void BuildingModelManip::SetTexture(QString _texture)
{
// TODO For now setting existing material scripts.
// Add support for custom textures.
this->dataPtr->texture = "Gazebo/Grey";
if (_texture == ":wood.jpg")
this->dataPtr->texture = "Gazebo/Wood";
else if (_texture == ":tiles.jpg")
this->dataPtr->texture = "Gazebo/CeilingTiled";
else if (_texture == ":bricks.png")
this->dataPtr->texture = "Gazebo/Bricks";
// BuildingModelManip and BuildingMaker handle material names,
// Inspectors and palette handle thumbnail uri
this->dataPtr->visual->SetMaterial(this->dataPtr->texture);
// Must set color after texture otherwise it gets overwritten
this->dataPtr->visual->SetAmbient(this->dataPtr->color);
this->dataPtr->maker->BuildingChanged();
emit TextureChanged(_texture.toStdString());
}
/////////////////////////////////////////////////
void BuildingModelManip::SetTransparency(float _transparency)
{
this->dataPtr->transparency = _transparency;
this->dataPtr->visual->SetTransparency(this->dataPtr->transparency);
}
/////////////////////////////////////////////////
void BuildingModelManip::SetVisible(bool _visible)
{
this->dataPtr->visual->SetVisible(_visible);
}
/////////////////////////////////////////////////
void BuildingModelManip::SetLevel(const int _level)
{
this->dataPtr->level = _level;
}
/////////////////////////////////////////////////
int BuildingModelManip::Level() const
{
return this->dataPtr->level;
}
/////////////////////////////////////////////////
void BuildingModelManip::OnChangeLevel(int _level)
{
if (this->dataPtr->level > _level)
this->SetVisible(false);
else if (this->dataPtr->level < _level)
{
this->SetVisible(true);
this->SetTransparency(0.0);
}
else
{
this->SetVisible(true);
this->SetTransparency(0.4);
}
}
| 3,675 |
713 | <reponame>franz1981/infinispan<filename>documentation/src/main/asciidoc/topics/code_examples/ExternalizerRegisterMultiple.java
builder.serialization()
.addAdvancedExternalizer(new Person.PersonExternalizer(),
new Address.AddressExternalizer());
| 75 |
14,668 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/tray/tray_event_filter.h"
#include "ash/capture_mode/capture_mode_util.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/root_window_controller.h"
#include "ash/shelf/shelf.h"
#include "ash/shell.h"
#include "ash/system/message_center/ash_message_popup_collection.h"
#include "ash/system/message_center/unified_message_center_bubble.h"
#include "ash/system/status_area_widget.h"
#include "ash/system/tray/tray_background_view.h"
#include "ash/system/tray/tray_bubble_base.h"
#include "ash/system/unified/unified_system_tray.h"
#include "ash/system/unified/unified_system_tray_bubble.h"
#include "ash/wm/container_finder.h"
#include "ash/wm/tablet_mode/tablet_mode_controller.h"
#include "ui/aura/window.h"
#include "ui/display/screen.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/widget/widget.h"
namespace ash {
TrayEventFilter::TrayEventFilter() = default;
TrayEventFilter::~TrayEventFilter() {
DCHECK(bubbles_.empty());
}
void TrayEventFilter::AddBubble(TrayBubbleBase* bubble) {
bool was_empty = bubbles_.empty();
bubbles_.insert(bubble);
if (was_empty && !bubbles_.empty())
Shell::Get()->AddPreTargetHandler(this);
}
void TrayEventFilter::RemoveBubble(TrayBubbleBase* bubble) {
bubbles_.erase(bubble);
if (bubbles_.empty())
Shell::Get()->RemovePreTargetHandler(this);
}
void TrayEventFilter::OnMouseEvent(ui::MouseEvent* event) {
if (event->type() == ui::ET_MOUSE_PRESSED)
ProcessPressedEvent(*event);
}
void TrayEventFilter::OnTouchEvent(ui::TouchEvent* event) {
if (event->type() == ui::ET_TOUCH_PRESSED)
ProcessPressedEvent(*event);
}
void TrayEventFilter::ProcessPressedEvent(const ui::LocatedEvent& event) {
// Users in a capture session may be trying to capture tray bubble(s).
if (capture_mode_util::IsCaptureModeActive())
return;
// The hit target window for the virtual keyboard isn't the same as its
// views::Widget.
aura::Window* target = static_cast<aura::Window*>(event.target());
const views::Widget* target_widget =
views::Widget::GetTopLevelWidgetForNativeView(target);
const aura::Window* container =
target ? GetContainerForWindow(target) : nullptr;
// TODO(https://crbug.com/1208083): Replace some of this logic with
// bubble_utils::ShouldCloseBubbleForEvent().
if (target && container) {
const int container_id = container->GetId();
// Don't process events that occurred inside an embedded menu, for example
// the right-click menu in a popup notification.
if (container_id == kShellWindowId_MenuContainer)
return;
// Don't process events that occurred inside a popup notification
// from message center.
if (container_id == kShellWindowId_ShelfContainer &&
target->GetType() == aura::client::WINDOW_TYPE_POPUP &&
target_widget->GetName() ==
AshMessagePopupCollection::kMessagePopupWidgetName) {
return;
}
// Don't process events that occurred inside a virtual keyboard.
if (container_id == kShellWindowId_VirtualKeyboardContainer)
return;
}
std::set<TrayBackgroundView*> trays;
// Check the boundary for all bubbles, and do not handle the event if it
// happens inside of any of those bubbles.
const gfx::Point screen_location =
event.target() ? event.target()->GetScreenLocation(event)
: event.root_location();
for (const TrayBubbleBase* bubble : bubbles_) {
const views::Widget* bubble_widget = bubble->GetBubbleWidget();
if (!bubble_widget)
continue;
gfx::Rect bounds = bubble_widget->GetWindowBoundsInScreen();
bounds.Inset(bubble->GetBubbleView()->GetBorderInsets());
// System tray can be dragged to show the bubble if it is in tablet mode.
// During the drag, the bubble's logical bounds can extend outside of the
// work area, but its visual bounds are only within the work area. Restrict
// |bounds| so that events located outside the bubble's visual bounds are
// treated as outside of the bubble.
int bubble_container_id =
GetContainerForWindow(bubble_widget->GetNativeWindow())->GetId();
if (Shell::Get()->tablet_mode_controller()->InTabletMode() &&
bubble_container_id == kShellWindowId_SettingBubbleContainer) {
bounds.Intersect(bubble_widget->GetWorkAreaBoundsInScreen());
}
// The system tray and message center are separate bubbles but they need
// to stay open together. We need to make sure to check if a click falls
// with in both their bounds and not close them both in this case.
if (bubble_container_id == kShellWindowId_SettingBubbleContainer) {
int64_t display_id = display::Screen::GetScreen()
->GetDisplayNearestPoint(screen_location)
.id();
UnifiedSystemTray* tray =
Shell::GetRootWindowControllerWithDisplayId(display_id)
->shelf()
->GetStatusAreaWidget()
->unified_system_tray();
TrayBubbleBase* system_tray_bubble = tray->bubble();
if (tray->IsBubbleShown() && system_tray_bubble != bubble) {
bounds.Union(
system_tray_bubble->GetBubbleWidget()->GetWindowBoundsInScreen());
} else if (tray->IsMessageCenterBubbleShown()) {
TrayBubbleBase* message_center_bubble = tray->message_center_bubble();
bounds.Union(message_center_bubble->GetBubbleWidget()
->GetWindowBoundsInScreen());
}
}
if (bounds.Contains(screen_location))
continue;
if (bubble->GetTray()) {
// If the user clicks on the parent tray, don't process the event here,
// let the tray logic handle the event and determine show/hide behavior.
bounds = bubble->GetTray()->GetBoundsInScreen();
if (bubble->GetTray()->GetVisible() && bounds.Contains(screen_location))
continue;
}
trays.insert(bubble->GetTray());
}
// Close all bubbles other than the one that the user clicked on.
for (TrayBackgroundView* tray_background_view : trays)
tray_background_view->ClickedOutsideBubble();
}
} // namespace ash
| 2,271 |
19,529 | <filename>vnpy/api/nst/generator/nst_typedef.py
T_UFT_BYTE = "unsigned char"
T_UFT_WORD = "unsigned short"
T_UFT_DWORD = "unsigned long"
T_UFT_INT1 = "char"
T_UFT_INT2 = "short"
T_UFT_INT4 = "int"
T_UFT_UINT4 = "unsigned int"
T_UFT_REAL4 = "float"
T_UFT_REAL8 = "double"
T_UFT_CHAR = "char"
T_UFT_FtdcErrorIDType = "int"
T_UFT_FtdcPriorityType = "int"
T_UFT_FtdcSettlementIDType = "int"
T_UFT_FtdcMonthCountType = "int"
T_UFT_FtdcTradingSegmentSNType = "int"
T_UFT_FtdcPeriodIDType = "int"
T_UFT_FtdcVolumeType = "int"
T_UFT_FtdcTimeSortIDType = "int"
T_UFT_FtdcFrontIDType = "int"
T_UFT_FtdcSessionIDType = "int"
T_UFT_FtdcSequenceNoType = "int"
T_UFT_FtdcBulletinIDType = "int"
T_UFT_FtdcInformationIDType = "int"
T_UFT_FtdcMillisecType = "int"
T_UFT_FtdcVolumeMultipleType = "int"
T_UFT_FtdcImplyLevelType = "int"
T_UFT_FtdcStartPosType = "int"
T_UFT_FtdcDataCenterIDType = "int"
T_UFT_FtdcCommFluxType = "int"
T_UFT_FtdcAliasType = "string"
T_UFT_FtdcOriginalTextType = "string"
T_UFT_FtdcParticipantIDType = "string"
T_UFT_FtdcParticipantNameType = "string"
T_UFT_FtdcParticipantAbbrType = "string"
T_UFT_FtdcUserIDType = "string"
T_UFT_FtdcPasswordType = "string"
T_UFT_FtdcClientIDType = "string"
T_UFT_FtdcInstrumentIDType = "string"
T_UFT_FtdcProductIDType = "string"
T_UFT_FtdcProductNameType = "string"
T_UFT_FtdcExchangeIDType = "string"
T_UFT_FtdcDateType = "string"
T_UFT_FtdcTimeType = "string"
T_UFT_FtdcInstrumentNameType = "string"
T_UFT_FtdcProductGroupIDType = "string"
T_UFT_FtdcProductGroupNameType = "string"
T_UFT_FtdcMarketIDType = "string"
T_UFT_FtdcSettlementGroupIDType = "string"
T_UFT_FtdcOrderSysIDType = "string"
T_UFT_FtdcOTCOrderSysIDType = "string"
T_UFT_FtdcExecOrderSysIDType = "string"
T_UFT_FtdcQuoteSysIDType = "string"
T_UFT_FtdcTradeIDType = "string"
T_UFT_FtdcOrderLocalIDType = "string"
T_UFT_FtdcComeFromType = "string"
T_UFT_FtdcAccountIDType = "string"
T_UFT_FtdcNewsTypeType = "string"
T_UFT_FtdcAdvanceMonthType = "string"
T_UFT_FtdcCommodityIDType = "string"
T_UFT_FtdcIPAddressType = "string"
T_UFT_FtdcProductInfoType = "string"
T_UFT_FtdcProtocolInfoType = "string"
T_UFT_FtdcBusinessUnitType = "string"
T_UFT_FtdcTradingSystemNameType = "string"
T_UFT_FtdcDeliveryModeType = "char"
T_UFT_FtdcTradingRoleType = "char"
T_UFT_FtdcUserTypeType = "char"
T_UFT_FtdcProductClassType = "char"
T_UFT_FtdcOptionsTypeType = "char"
T_UFT_FtdcInstrumentStatusType = "char"
T_UFT_FtdcDirectionType = "char"
T_UFT_FtdcPositionTypeType = "char"
T_UFT_FtdcPosiDirectionType = "char"
T_UFT_FtdcExchangeDataSyncStatusType = "char"
T_UFT_FtdcSGDataSyncStatusType = "char"
T_UFT_FtdcHedgeFlagType = "char"
T_UFT_FtdcClientTypeType = "char"
T_UFT_FtdcInstStatusEnterReasonType = "char"
T_UFT_FtdcOrderBs = "char"
T_UFT_FtdcOrderPriceTypeType = "char"
T_UFT_FtdcOffsetFlagType = "char"
T_UFT_FtdcForceCloseReasonType = "char"
T_UFT_FtdcOrderStatusType = "char"
T_UFT_FtdcOrderTypeType = "char"
T_UFT_FtdcOTCOrderStatusType = "char"
T_UFT_FtdcTimeConditionType = "char"
T_UFT_FtdcVolumeConditionType = "char"
T_UFT_FtdcContingentConditionType = "char"
T_UFT_FtdcActionFlagType = "char"
T_UFT_FtdcOrderSourceType = "char"
T_UFT_FtdcTradeTypeType = "char"
T_UFT_FtdcPriceSourceType = "char"
T_UFT_FtdcAccountStatusType = "char"
T_UFT_FtdcMemberTypeType = "char"
T_UFT_FtdcExecResultType = "char"
T_UFT_FtdcYearType = "int"
T_UFT_FtdcMonthType = "int"
T_UFT_FtdcLegMultipleType = "int"
T_UFT_FtdcLegIDType = "int"
T_UFT_FtdcBoolType = "int"
T_UFT_FtdcUserActiveType = "int"
T_UFT_FtdcPriceType = "double"
T_UFT_FtdcUnderlyingMultipleType = "double"
T_UFT_FtdcCombOffsetFlagType = "string"
T_UFT_FtdcCombHedgeFlagType = "string"
T_UFT_FtdcRatioType = "double"
T_UFT_FtdcMoneyType = "double"
T_UFT_FtdcLargeVolumeType = "double"
T_UFT_FtdcNewsUrgencyType = "char"
T_UFT_FtdcSequenceSeriesType = "short"
T_UFT_FtdcCommPhaseNoType = "short"
T_UFT_FtdcContentLengthType = "int"
T_UFT_FtdcErrorMsgType = "string"
T_UFT_FtdcAbstractType = "string"
T_UFT_FtdcContentType = "string"
T_UFT_FtdcURLLinkType = "string"
T_UFT_FtdcIdentifiedCardNoType = "string"
T_UFT_FtdcIdentifiedCardNoV1Type = "string"
T_UFT_FtdcPartyNameType = "string"
T_UFT_FtdcIdCardTypeType = "string"
T_UFT_FtdcAdminOrderCommandFlagType = "char"
T_UFT_FtdcCurrencyIDType = "string"
T_UFT_FtdcBusinessLocalIDType = "int"
T_UFT_FtdcSessionTypeType = "char"
T_UFT_FtdcRateUnitType = "int"
T_UFT_FtdcExRatePriceType = "double"
T_UFT_FtdcMeasureSecType = "int"
T_UFT_FtdcMeasureUsecType = "int"
T_UFT_FtdcDepthType = "int"
T_UFT_FtdcSessionStatusType = "char"
T_UFT_FtdcExecOrderPositionFlagType = "char"
T_UFT_FtdcExecOrderCloseFlagType = "char"
T_UFT_ErrorIDType = "int"
T_UFT_ErrorMsgType = "string"
T_UFT_ORDERREF_TYPE = "uint64_t"
T_UFT_TRADEDATE_TYPE = "int"
| 2,229 |
4,054 | <gh_stars>1000+
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "inspector.h"
namespace vespalib::slime {
class Symbol;
/**
* Interface used when traversing all the fields of an object value
* tagged with symbol id.
**/
struct ObjectSymbolTraverser {
virtual void field(const Symbol &symbol, const Inspector &inspector) = 0;
virtual ~ObjectSymbolTraverser() {}
};
/**
* Interface used when traversing all the fields of an object value
* tagged with symbol name.
**/
struct ObjectTraverser {
virtual void field(const Memory &symbol, const Inspector &inspector) = 0;
virtual ~ObjectTraverser() {}
};
} // namespace vespalib::slime
| 228 |
1,306 | <gh_stars>1000+
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Coin.h"
#include "HexCoding.h"
#include "Base64.h"
#include "proto/Cosmos.pb.h"
#include "Cosmos/Address.h"
#include "Cosmos/Signer.h"
#include <gtest/gtest.h>
using namespace TW;
using namespace TW::Cosmos;
TEST(CosmosStaking, Staking) {
auto input = Proto::SigningInput();
input.set_account_number(1037);
input.set_chain_id("gaia-13003");
input.set_memo("");
input.set_sequence(7);
auto msg = input.add_messages();
auto& message = *msg->mutable_stake_message();
message.set_delegator_address("cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02");
message.set_validator_address("cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp");
auto& amountOfTx = *message.mutable_amount();
amountOfTx.set_denom("muon");
amountOfTx.set_amount(10);
auto &fee = *input.mutable_fee();
fee.set_gas(101721);
auto amountOfFee = fee.add_amounts();
amountOfFee->set_denom("muon");
amountOfFee->set_amount(1018);
auto privateKey = parse_hex("80e81ea269e66a0a05b11236df7919fb7fbeedba87452d667489d7403a02f005");
input.set_private_key(privateKey.data(), privateKey.size());
auto output = Signer::sign(input);
ASSERT_EQ(output.json(), "{\"mode\":\"block\",\"tx\":{\"fee\":{\"amount\":[{\"amount\":\"1018\",\"denom\":\"muon\"}],\"gas\":\"101721\"},\"memo\":\"\",\"msg\":[{\"type\":\"cosmos-sdk/MsgDelegate\",\"value\":{\"amount\":{\"amount\":\"10\",\"denom\":\"muon\"},\"delegator_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\",\"validator_address\":\"cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp\"}}],\"signatures\":[{\"pub_key\":{\"type\":\"tendermint/PubKeySecp256k1\",\"value\":\"<KEY>},\"signature\":\"wIvfbCsLRCjzeXXoXTKfHLGXRbAAmUp0O134HVfVc6pfdVNJvvzISMHRUHgYcjsSiFlLyR32heia/yLgMDtIYQ==\"}]}}");
ASSERT_EQ(hex(output.signature()), "c08bdf6c2b0b4428f37975e85d329f1cb19745b000994a743b5df81d57d573aa5f755349befcc848c1d1507818723b1288594bc91df685e89aff22e0303b4861");
}
TEST(CosmosStaking, Unstaking) {
auto input = Proto::SigningInput();
input.set_account_number(1037);
input.set_chain_id("gaia-13003");
input.set_memo("");
input.set_sequence(7);
auto msg = input.add_messages();
auto& message = *msg->mutable_unstake_message();
message.set_delegator_address("cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02");
message.set_validator_address("cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp");
auto& amountOfTx = *message.mutable_amount();
amountOfTx.set_denom("muon");
amountOfTx.set_amount(10);
auto &fee = *input.mutable_fee();
fee.set_gas(101721);
auto amountOfFee = fee.add_amounts();
amountOfFee->set_denom("muon");
amountOfFee->set_amount(1018);
auto privateKey = parse_hex("80e81ea269e66a0a05b11236df7919fb7fbeedba87452d667489d7403a02f005");
input.set_private_key(privateKey.data(), privateKey.size());
auto output = Signer::sign(input);
ASSERT_EQ(output.json(), "{\"mode\":\"block\",\"tx\":{\"fee\":{\"amount\":[{\"amount\":\"1018\",\"denom\":\"muon\"}],\"gas\":\"101721\"},\"memo\":\"\",\"msg\":[{\"type\":\"cosmos-sdk/MsgUndelegate\",\"value\":{\"amount\":{\"amount\":\"10\",\"denom\":\"muon\"},\"delegator_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\",\"validator_address\":\"cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp\"}}],\"signatures\":[{\"pub_key\":{\"type\":\"tendermint/PubKeySecp256k1\",\"value\":\"<KEY>},\"signature\":\"j4WpUVohGIHa6/s0bCvuyjq1wtQGqbOtQCz92qPQjisTN44Tz++Ozx1lAP6F0M4+eTA03XerqQ8hZCeAfL/3nw==\"}]}}");
ASSERT_EQ(hex(output.signature()), "8f85a9515a211881daebfb346c2beeca3ab5c2d406a9b3ad402cfddaa3d08e2b13378e13cfef8ecf1d6500fe85d0ce3e793034dd77aba90f216427807cbff79f");
}
TEST(CosmosStaking, Restaking) {
auto input = Proto::SigningInput();
input.set_account_number(1037);
input.set_chain_id("gaia-13003");
input.set_memo("");
input.set_sequence(7);
auto msg = input.add_messages();
auto& message = *msg->mutable_restake_message();
message.set_delegator_address("cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02");
message.set_validator_dst_address("cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02");
message.set_validator_src_address("cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp");
auto& amountOfTx = *message.mutable_amount();
amountOfTx.set_denom("muon");
amountOfTx.set_amount(10);
auto &fee = *input.mutable_fee();
fee.set_gas(101721);
auto amountOfFee = fee.add_amounts();
amountOfFee->set_denom("muon");
amountOfFee->set_amount(1018);
auto privateKey = parse_hex("80e81ea269e66a0a05b11236df7919fb7fbeedba87452d667489d7403a02f005");
input.set_private_key(privateKey.data(), privateKey.size());
auto output = Signer::sign(input);
ASSERT_EQ(output.json(), "{\"mode\":\"block\",\"tx\":{\"fee\":{\"amount\":[{\"amount\":\"1018\",\"denom\":\"muon\"}],\"gas\":\"101721\"},\"memo\":\"\",\"msg\":[{\"type\":\"cosmos-sdk/MsgBeginRedelegate\",\"value\":{\"amount\":{\"amount\":\"10\",\"denom\":\"muon\"},\"delegator_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\",\"validator_dst_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\",\"validator_src_address\":\"cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp\"}}],\"signatures\":[{\"pub_key\":{\"type\":\"tendermint/PubKeySecp256k1\",\"value\":\"<KEY>},\"signature\":\"5k03Yb0loovvzagMCg4gjQJP2woriZVRcOZaXF1FSros6B1X4B8MEm3lpZwrWBJMEJVgyYA9ZaF6FLVI3WxQ2w==\"}]}}");
ASSERT_EQ(hex(output.signature()), "e64d3761bd25a28befcda80c0a0e208d024fdb0a2b89955170e65a5c5d454aba2ce81d57e01f0c126de5a59c2b58124c109560c9803d65a17a14b548dd6c50db");
}
TEST(CosmosStaking, Withdraw) {
auto input = Proto::SigningInput();
input.set_account_number(1037);
input.set_chain_id("gaia-13003");
input.set_memo("");
input.set_sequence(7);
auto msg = input.add_messages();
auto& message = *msg->mutable_withdraw_stake_reward_message();
message.set_delegator_address("cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02");
message.set_validator_address("cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp");
auto &fee = *input.mutable_fee();
fee.set_gas(101721);
auto amountOfFee = fee.add_amounts();
amountOfFee->set_denom("muon");
amountOfFee->set_amount(1018);
auto privateKey = parse_hex("80e81ea269e66a0a05b11236df7919fb7fbeedba87452d667489d7403a02f005");
input.set_private_key(privateKey.data(), privateKey.size());
auto output = Signer::sign(input);
ASSERT_EQ( output.json(), "{\"mode\":\"block\",\"tx\":{\"fee\":{\"amount\":[{\"amount\":\"1018\",\"denom\":\"muon\"}],\"gas\":\"101721\"},\"memo\":\"\",\"msg\":[{\"type\":\"cosmos-sdk/MsgWithdrawDelegationReward\",\"value\":{\"delegator_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\",\"validator_address\":\"cosmosvaloper1zkupr83hrzkn3up5elktzcq3tuft8nxsmwdqgp\"}}],\"signatures\":[{\"pub_key\":{\"type\":\"tendermint/PubKeySecp256k1\",\"value\":\"<KEY>},\"signature\":\"VG8NZzVvavlM+1qyK5dOSZwzEj8sLCkvTw5kh44Oco9GQxBf13FVC+s/I3HwiICqo4+o8jNMEDp3nx2C0tuY1g==\"}]}}");
ASSERT_EQ(hex(output.signature()), "546f0d67356f6af94cfb5ab22b974e499c33123f2c2c292f4f0e64878e0e728f4643105fd771550beb3f2371f08880aaa38fa8f2334c103a779f1d82d2db98d6");
}
TEST(CosmosStaking, WithdrawAllRaw) {
auto input = Proto::SigningInput();
input.set_account_number(1037);
input.set_chain_id("gaia-13003");
input.set_memo("");
input.set_sequence(7);
auto msg = input.add_messages();
auto& message = *msg->mutable_raw_json_message();
message.set_type("cosmos-sdk/MsgWithdrawDelegationRewardsAll");
message.set_value("{\"delegator_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\"}");
auto &fee = *input.mutable_fee();
fee.set_gas(101721);
auto amountOfFee = fee.add_amounts();
amountOfFee->set_denom("muon");
amountOfFee->set_amount(1018);
auto privateKey = parse_hex("80e81ea269e66a0a05b11236df7919fb7fbeedba87452d667489d7403a02f005");
input.set_private_key(privateKey.data(), privateKey.size());
auto output = Signer::sign(input);
ASSERT_EQ(output.json(), "{\"mode\":\"block\",\"tx\":{\"fee\":{\"amount\":[{\"amount\":\"1018\",\"denom\":\"muon\"}],\"gas\":\"101721\"},\"memo\":\"\",\"msg\":[{\"type\":\"cosmos-sdk/MsgWithdrawDelegationRewardsAll\",\"value\":{\"delegator_address\":\"cosmos1hsk6jryyqjfhp5dhc55tc9jtckygx0eph6dd02\"}}],\"signatures\":[{\"pub_key\":{\"type\":\"tendermint/PubKeySecp256k1\",\"value\":\"<KEY>},\"signature\":\"ImvsgnfbjebxzeBCUPeOcMoOJWMV3IhWM1apV20WiS4K11iA50fe0uXr4Xf/RTxUDXTm56cne/OjOr77BG99Aw==\"}]}}");
ASSERT_EQ(hex(output.signature()), "226bec8277db8de6f1cde04250f78e70ca0e256315dc88563356a9576d16892e0ad75880e747ded2e5ebe177ff453c540d74e6e7a7277bf3a33abefb046f7d03");
}
| 4,158 |
9,425 | """
:codeauthor: <NAME> <<EMAIL>>
"""
import os
import salt.modules.oracle as oracle
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class OracleTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.oracle
"""
def setup_loader_modules(self):
return {oracle: {"cx_Oracle": object()}}
def test_run_query(self):
"""
Test for Run SQL query and return result
"""
with patch.object(oracle, "_connect", MagicMock()) as mock_connect:
mock_connect.cursor.execute.fetchall.return_value = True
with patch.object(oracle, "show_dbs", MagicMock()):
self.assertTrue(oracle.run_query("db", "query"))
def test_show_dbs(self):
"""
Test for Show databases configuration from pillar. Filter by `*args`
"""
with patch.dict(oracle.__salt__, {"pillar.get": MagicMock(return_value="a")}):
self.assertDictEqual(oracle.show_dbs("A", "B"), {"A": "a", "B": "a"})
self.assertEqual(oracle.show_dbs(), "a")
def test_version(self):
"""
Test for Server Version (select banner from v$version)
"""
with patch.dict(oracle.__salt__, {"pillar.get": MagicMock(return_value="a")}):
with patch.object(oracle, "run_query", return_value="A"):
self.assertDictEqual(oracle.version(), {})
def test_client_version(self):
"""
Test for Oracle Client Version
"""
with patch.object(oracle, "cx_Oracle", MagicMock(side_effect=MagicMock())):
self.assertEqual(oracle.client_version(), "")
def test_show_pillar(self):
"""
Test for Show Pillar segment oracle.*
"""
with patch.dict(oracle.__salt__, {"pillar.get": MagicMock(return_value="a")}):
self.assertEqual(oracle.show_pillar("item"), "a")
def test_show_env(self):
"""
Test for Show Environment used by Oracle Client
"""
with patch.object(
os,
"environ",
return_value={
"PATH": "PATH",
"ORACLE_HOME": "ORACLE_HOME",
"TNS_ADMIN": "TNS_ADMIN",
"NLS_LANG": "NLS_LANG",
},
):
self.assertDictEqual(oracle.show_env(), {})
| 1,128 |
865 | <gh_stars>100-1000
from django.core.paginator import Paginator
from django.db.models import Func
class Round(Func):
function = "ROUND"
arity = 2
def paginate_list(data=None, page=1, per_page=10, limit=None):
if not data:
data = []
total = len(data)
if per_page != -1:
p = Paginator(data, per_page)
last_page = p.page_range[-1]
page = page if page <= last_page else last_page
data = p.page(page)
total = p.count
else:
if limit:
data = data[:limit]
return data, total
| 260 |
809 | <gh_stars>100-1000
/**
* @file
*
* @date Nov 1, 2013
* @author: <NAME>
*/
#ifndef SOCKET_DESC_H_
#define SOCKET_DESC_H_
extern struct sock *idesc_sock_get(int idx);
#endif /* SOCKET_DESC_H_ */
| 96 |
372 | /* Editor Settings: expandtabs and use 4 spaces for indentation
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
* -*- mode: c, c-basic-offset: 4 -*- */
/*
* Copyright © BeyondTrust Software 2004 - 2019
* 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.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
/*
* Copyright (C) BeyondTrust Software. All rights reserved.
*
* Module Name:
*
* fileutils.c
*
* Abstract:
*
* BeyondTrust IO (LWIO)
*
* Authors: <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*
*/
#include "includes.h"
DWORD
SMBRemoveFile(
PCSTR pszPath
)
{
DWORD dwError = 0;
while (1) {
if (unlink(pszPath) < 0) {
if (errno == EINTR) {
continue;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
} else {
break;
}
}
error:
return dwError;
}
DWORD
SMBCheckFileExists(
PCSTR pszPath,
PBOOLEAN pbFileExists
)
{
DWORD dwError = 0;
struct stat statbuf;
memset(&statbuf, 0, sizeof(struct stat));
while (1) {
if (stat(pszPath, &statbuf) < 0) {
if (errno == EINTR) {
continue;
} else if (errno == ENOENT) {
*pbFileExists = 0;
break;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
} else {
*pbFileExists = 1;
break;
}
}
error:
return dwError;
}
DWORD
SMBCheckSockExists(
PSTR pszPath,
PBOOLEAN pbSockExists
)
{
DWORD dwError = 0;
struct stat statbuf;
memset(&statbuf, 0, sizeof(struct stat));
while (1) {
if (stat(pszPath, &statbuf) < 0) {
if (errno == EINTR) {
continue;
} else if (errno == ENOENT || errno == ENOTDIR) {
*pbSockExists = 0;
break;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
} else {
*pbSockExists = (((statbuf.st_mode & S_IFMT) == S_IFSOCK) ? TRUE : FALSE);
break;
}
}
error:
return dwError;
}
DWORD
SMBMoveFile(
PCSTR pszSrcPath,
PCSTR pszDstPath
)
{
DWORD dwError = 0;
if (rename(pszSrcPath, pszDstPath) < 0) {
dwError = errno;
}
return dwError;
}
DWORD
SMBChangePermissions(
PCSTR pszPath,
mode_t dwFileMode
)
{
DWORD dwError = 0;
while (1) {
if (chmod(pszPath, dwFileMode) < 0) {
if (errno == EINTR) {
continue;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
} else {
break;
}
}
error:
return dwError;
}
DWORD
SMBChangeOwner(
PCSTR pszPath,
uid_t uid,
gid_t gid
)
{
DWORD dwError = 0;
struct stat statbuf = {0};
if (lstat(pszPath, &statbuf) < 0) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
while (1) {
if (S_ISLNK(statbuf.st_mode)) {
if (lchown(pszPath, uid, gid) < 0) {
if (errno == EINTR) {
continue;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
} else {
break;
}
} else {
if (chown(pszPath, uid, gid) < 0) {
if (errno == EINTR) {
continue;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
} else {
break;
}
}
}
error:
return dwError;
}
DWORD
SMBChangeOwnerAndPermissions(
PCSTR pszPath,
uid_t uid,
gid_t gid,
mode_t dwFileMode
)
{
DWORD dwError = 0;
dwError = SMBChangeOwner(pszPath, uid, gid);
BAIL_ON_LWIO_ERROR(dwError);
dwError = SMBChangePermissions(pszPath, dwFileMode);
BAIL_ON_LWIO_ERROR(dwError);
error:
return dwError;
}
DWORD
SMBChangeDirectory(
PSTR pszPath
)
{
if (pszPath == NULL || *pszPath == '\0')
return EINVAL;
if (chdir(pszPath) < 0)
return errno;
return 0;
}
/*
// TODO: Check access and removability before actual deletion
*/
DWORD
SMBRemoveDirectory(
PSTR pszPath
)
{
DWORD dwError = 0;
DIR* pDir = NULL;
struct dirent* pDirEntry = NULL;
struct stat statbuf;
CHAR szBuf[PATH_MAX+1];
if ((pDir = opendir(pszPath)) == NULL) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
while ((pDirEntry = readdir(pDir)) != NULL) {
if (!strcmp(pDirEntry->d_name, "..") ||
!strcmp(pDirEntry->d_name, "."))
continue;
sprintf(szBuf, "%s/%s", pszPath, pDirEntry->d_name);
memset(&statbuf, 0, sizeof(struct stat));
if (stat(szBuf, &statbuf) < 0) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
if ((statbuf.st_mode & S_IFMT) == S_IFDIR) {
dwError = SMBRemoveDirectory(szBuf);
BAIL_ON_LWIO_ERROR(dwError);
if (rmdir(szBuf) < 0) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
} else {
dwError = SMBRemoveFile(szBuf);
BAIL_ON_LWIO_ERROR(dwError);
}
}
error:
if (pDir)
closedir(pDir);
return dwError;
}
DWORD
SMBCheckDirectoryExists(
PCSTR pszPath,
PBOOLEAN pbDirExists
)
{
DWORD dwError = 0;
struct stat statbuf;
while (1) {
memset(&statbuf, 0, sizeof(struct stat));
if (stat(pszPath, &statbuf) < 0) {
if (errno == EINTR) {
continue;
}
else if (errno == ENOENT || errno == ENOTDIR) {
*pbDirExists = FALSE;
break;
}
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
/*
The path exists. Is it a directory?
*/
*pbDirExists = (((statbuf.st_mode & S_IFMT) == S_IFDIR) ? TRUE : FALSE);
break;
}
error:
return dwError;
}
DWORD
SMBGetCurrentDirectoryPath(
PSTR* ppszPath
)
{
DWORD dwError = 0;
CHAR szBuf[PATH_MAX+1];
PSTR pszPath = NULL;
if (getcwd(szBuf, PATH_MAX) == NULL) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
dwError = SMBAllocateString(szBuf, &pszPath);
BAIL_ON_LWIO_ERROR(dwError);
*ppszPath = pszPath;
return dwError;
error:
if (pszPath) {
SMBFreeString(pszPath);
}
return dwError;
}
static
DWORD
SMBCreateDirectoryRecursive(
PSTR pszCurDirPath,
PSTR pszTmpPath,
PSTR *ppszTmp,
DWORD dwFileMode,
DWORD dwWorkingFileMode,
int iPart
)
{
DWORD dwError = 0;
PSTR pszDirPath = NULL;
BOOLEAN bDirCreated = FALSE;
BOOLEAN bDirExists = FALSE;
CHAR szDelimiters[] = "/";
PSTR pszToken = strtok_r((iPart ? NULL : pszTmpPath), szDelimiters, ppszTmp);
if (pszToken != NULL) {
dwError = LwIoAllocateMemory(strlen(pszCurDirPath)+strlen(pszToken)+2,
(PVOID*)&pszDirPath);
BAIL_ON_LWIO_ERROR(dwError);
sprintf(pszDirPath,
"%s/%s",
(!strcmp(pszCurDirPath, "/") ? "" : pszCurDirPath),
pszToken);
dwError = SMBCheckDirectoryExists(pszDirPath, &bDirExists);
BAIL_ON_LWIO_ERROR(dwError);
if (!bDirExists) {
if (mkdir(pszDirPath, dwWorkingFileMode) < 0) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
bDirCreated = TRUE;
}
dwError = SMBChangeDirectory(pszDirPath);
BAIL_ON_LWIO_ERROR(dwError);
dwError = SMBCreateDirectoryRecursive(
pszDirPath,
pszTmpPath,
ppszTmp,
dwFileMode,
dwWorkingFileMode,
iPart+1
);
BAIL_ON_LWIO_ERROR(dwError);
}
if (bDirCreated && (dwFileMode != dwWorkingFileMode)) {
dwError = SMBChangePermissions(pszDirPath, dwFileMode);
BAIL_ON_LWIO_ERROR(dwError);
}
if (pszDirPath) {
LwIoFreeMemory(pszDirPath);
}
return dwError;
error:
if (bDirCreated) {
SMBRemoveDirectory(pszDirPath);
}
if (pszDirPath) {
LwIoFreeMemory(pszDirPath);
}
return dwError;
}
DWORD
SMBCreateDirectory(
PCSTR pszPath,
mode_t dwFileMode
)
{
DWORD dwError = 0;
PSTR pszCurDirPath = NULL;
PSTR pszTmpPath = NULL;
PSTR pszTmp = NULL;
mode_t dwWorkingFileMode;
if (pszPath == NULL || *pszPath == '\0') {
dwError = EINVAL;
BAIL_ON_LWIO_ERROR(dwError);
}
dwWorkingFileMode = dwFileMode;
if (!(dwFileMode & S_IXUSR)) {
/*
* This is so that we can navigate the folders
* when we are creating the subfolders
*/
dwWorkingFileMode |= S_IXUSR;
}
dwError = SMBGetCurrentDirectoryPath(&pszCurDirPath);
BAIL_ON_LWIO_ERROR(dwError);
dwError = SMBAllocateString(pszPath, &pszTmpPath);
BAIL_ON_LWIO_ERROR(dwError);
if (*pszPath == '/') {
dwError = SMBChangeDirectory("/");
BAIL_ON_LWIO_ERROR(dwError);
dwError = SMBCreateDirectoryRecursive("/", pszTmpPath, &pszTmp, dwFileMode, dwWorkingFileMode, 0);
BAIL_ON_LWIO_ERROR(dwError);
} else {
dwError = SMBCreateDirectoryRecursive(pszCurDirPath, pszTmpPath, &pszTmp, dwFileMode, dwWorkingFileMode, 0);
BAIL_ON_LWIO_ERROR(dwError);
}
error:
if (pszCurDirPath) {
SMBChangeDirectory(pszCurDirPath);
LwIoFreeMemory(pszCurDirPath);
}
if (pszTmpPath) {
LwIoFreeMemory(pszTmpPath);
}
return dwError;
}
DWORD
SMBGetOwnerAndPermissions(
PCSTR pszSrcPath,
uid_t * uid,
gid_t * gid,
mode_t * mode
)
{
DWORD dwError = 0;
struct stat statbuf;
memset(&statbuf, 0, sizeof(struct stat));
if (stat(pszSrcPath, &statbuf) < 0) {
dwError = errno;
BAIL_ON_LWIO_ERROR(dwError);
}
*uid = statbuf.st_uid;
*gid = statbuf.st_gid;
*mode = statbuf.st_mode;
error:
return dwError;
}
DWORD
SMBCreateSymlink(
PCSTR pszOldPath,
PCSTR pszNewPath
)
{
return ((symlink(pszOldPath, pszNewPath) < 0) ? errno : 0);
}
| 5,934 |
1,724 | #include <libwidget/Components.h>
#include "settings/pages/Home.h"
#include "settings/windows/MainWindow.h"
namespace Settings
{
MainWindow::MainWindow() : Window(WINDOW_RESIZABLE)
{
size({700, 500});
root()->add(Widget::titlebar(Graphic::Icon::get("cog"), "Settings"));
auto navigation_bar = root()->add(Widget::panel());
navigation_bar->add(Widget::basic_button(Graphic::Icon::get("arrow-left")));
navigation_bar->add(Widget::basic_button(Graphic::Icon::get("arrow-right")));
navigation_bar->add(Widget::basic_button(Graphic::Icon::get("home")));
root()->add<HomePage>();
}
} // namespace Settings
| 224 |
454 | <reponame>zwkjhx/vertx-zero
package io.vertx.up.uca.rs.regular;
import io.vertx.up.atom.Rule;
import io.vertx.up.exception.WebException;
import java.util.Collection;
public interface Ruler {
static Ruler get(final String type) {
return Pool.RULERS.get(type);
}
static WebException verify(final Collection<Rule> rules,
final String field,
final Object value) {
WebException error = null;
for (final Rule rule : rules) {
final Ruler ruler = get(rule.getType());
if (null != ruler) {
error = ruler.verify(field, value, rule);
}
// Error found
if (null != error) {
break;
}
}
return error;
}
/**
* Verify each field for @BodyParam
*
* @param field Input field of the data structure
* @param value The input field reflect value literal
* @param rule The rule that has been defined.
*
* @return WebException that the validated error here.
*/
WebException verify(final String field,
final Object value,
final Rule rule);
}
| 573 |
338 | <filename>ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppSetupImplTest.java
package com.tvd12.ezyfoxserver.testing.command;
import org.testng.annotations.Test;
import com.tvd12.ezyfoxserver.EzySimpleApplication;
import com.tvd12.ezyfoxserver.app.EzyAppRequestController;
import com.tvd12.ezyfoxserver.command.impl.EzyAppSetupImpl;
import com.tvd12.ezyfoxserver.context.EzyAppContext;
import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent;
import com.tvd12.test.base.BaseTest;
public class EzyAppSetupImplTest extends BaseTest {
@Test
public void test() {
EzySimpleApplication app = new EzySimpleApplication();
EzyAppSetupImpl cmd = new EzyAppSetupImpl(app);
cmd.setRequestController(new EzyAppRequestController() {
@Override
public void handle(EzyAppContext ctx, EzyUserRequestAppEvent event) {
}
});
}
}
| 366 |
515 | <reponame>zenglongGH/spresense
/*
* Copyright 2015-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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
#include "aws_iot_jobs_types.h"
const char *JOB_EXECUTION_QUEUED_STR = "QUEUED";
const char *JOB_EXECUTION_IN_PROGRESS_STR = "IN_PROGRESS";
const char *JOB_EXECUTION_FAILED_STR = "FAILED";
const char *JOB_EXECUTION_SUCCEEDED_STR = "SUCCEEDED";
const char *JOB_EXECUTION_CANCELED_STR = "CANCELED";
const char *JOB_EXECUTION_REJECTED_STR = "REJECTED";
JobExecutionStatus aws_iot_jobs_map_string_to_job_status(const char *str) {
if (str == NULL || str[0] == '\0') {
return JOB_EXECUTION_STATUS_NOT_SET;
} else if (strcmp(str, JOB_EXECUTION_QUEUED_STR) == 0) {
return JOB_EXECUTION_QUEUED;
} else if(strcmp(str, JOB_EXECUTION_IN_PROGRESS_STR) == 0) {
return JOB_EXECUTION_IN_PROGRESS;
} else if(strcmp(str, JOB_EXECUTION_FAILED_STR) == 0) {
return JOB_EXECUTION_FAILED;
} else if(strcmp(str, JOB_EXECUTION_SUCCEEDED_STR) == 0) {
return JOB_EXECUTION_SUCCEEDED;
} else if(strcmp(str, JOB_EXECUTION_CANCELED_STR) == 0) {
return JOB_EXECUTION_CANCELED;
} else if(strcmp(str, JOB_EXECUTION_REJECTED_STR) == 0) {
return JOB_EXECUTION_REJECTED;
} else {
return JOB_EXECUTION_UNKNOWN_STATUS;
}
}
const char *aws_iot_jobs_map_status_to_string(JobExecutionStatus status) {
switch(status) {
case JOB_EXECUTION_QUEUED:
return JOB_EXECUTION_QUEUED_STR;
case JOB_EXECUTION_IN_PROGRESS:
return JOB_EXECUTION_IN_PROGRESS_STR;
case JOB_EXECUTION_FAILED:
return JOB_EXECUTION_FAILED_STR;
case JOB_EXECUTION_SUCCEEDED:
return JOB_EXECUTION_SUCCEEDED_STR;
case JOB_EXECUTION_CANCELED:
return JOB_EXECUTION_CANCELED_STR;
case JOB_EXECUTION_REJECTED:
return JOB_EXECUTION_REJECTED_STR;
case JOB_EXECUTION_STATUS_NOT_SET:
case JOB_EXECUTION_UNKNOWN_STATUS:
default:
return NULL;
}
}
#ifdef __cplusplus
}
#endif
| 1,000 |
3,799 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.EdgeEffect;
import androidx.annotation.DoNotInline;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.os.BuildCompat;
/**
* Helper for accessing {@link android.widget.EdgeEffect}.
*
* This class is used to access {@link android.widget.EdgeEffect} on platform versions
* that support it. When running on older platforms it will result in no-ops. It should
* be used by views that wish to use the standard Android visual effects at the edges
* of scrolling containers.
*/
public final class EdgeEffectCompat {
private EdgeEffect mEdgeEffect;
/**
* Construct a new EdgeEffect themed using the given context.
*
* <p>Note: On platform versions that do not support EdgeEffect, all operations
* on the newly constructed object will be mocked/no-ops.</p>
*
* @param context Context to use for theming the effect
*
* @deprecated Use {@link EdgeEffect} constructor directly or
* {@link EdgeEffectCompat#create(Context, AttributeSet)}.
*/
@Deprecated
public EdgeEffectCompat(Context context) {
mEdgeEffect = new EdgeEffect(context);
}
/**
* Constructs and returns a new EdgeEffect themed using the given context, allowing support
* for the view attributes.
*
* @param context Context to use for theming the effect
* @param attrs The attributes of the XML tag that is inflating the view
*/
@NonNull
public static EdgeEffect create(@NonNull Context context, @Nullable AttributeSet attrs) {
if (BuildCompat.isAtLeastS()) {
return Api31Impl.create(context, attrs);
}
return new EdgeEffect(context);
}
/**
* Returns the pull distance needed to be released to remove the showing effect.
* It is determined by the {@link #onPull(float, float)} <code>deltaDistance</code> and
* any animating values, including from {@link #onAbsorb(int)} and {@link #onRelease()}.
*
* This can be used in conjunction with {@link #onPullDistance(EdgeEffect, float, float)} to
* release the currently showing effect.
*
* On {@link Build.VERSION_CODES#R} and earlier, this will return 0.
*
* @return The pull distance that must be released to remove the showing effect or 0 for
* versions {@link Build.VERSION_CODES#R} and earlier.
*/
public static float getDistance(@NonNull EdgeEffect edgeEffect) {
if (BuildCompat.isAtLeastS()) {
return Api31Impl.getDistance(edgeEffect);
}
return 0;
}
/**
* Set the size of this edge effect in pixels.
*
* @param width Effect width in pixels
* @param height Effect height in pixels
*
* @deprecated Use {@link EdgeEffect#setSize(int, int)} directly.
*/
@Deprecated
public void setSize(int width, int height) {
mEdgeEffect.setSize(width, height);
}
/**
* Reports if this EdgeEffectCompat's animation is finished. If this method returns false
* after a call to {@link #draw(Canvas)} the host widget should schedule another
* drawing pass to continue the animation.
*
* @return true if animation is finished, false if drawing should continue on the next frame.
*
* @deprecated Use {@link EdgeEffect#isFinished()} directly.
*/
@Deprecated
public boolean isFinished() {
return mEdgeEffect.isFinished();
}
/**
* Immediately finish the current animation.
* After this call {@link #isFinished()} will return true.
*
* @deprecated Use {@link EdgeEffect#finish()} directly.
*/
@Deprecated
public void finish() {
mEdgeEffect.finish();
}
/**
* A view should call this when content is pulled away from an edge by the user.
* This will update the state of the current visual effect and its associated animation.
* The host view should always {@link android.view.View#invalidate()} if this method
* returns true and draw the results accordingly.
*
* @param deltaDistance Change in distance since the last call. Values may be 0 (no change) to
* 1.f (full length of the view) or negative values to express change
* back toward the edge reached to initiate the effect.
* @return true if the host view should call invalidate, false if it should not.
*
* @deprecated Use {@link #onPull(EdgeEffect, float, float)}.
*/
@Deprecated
public boolean onPull(float deltaDistance) {
mEdgeEffect.onPull(deltaDistance);
return true;
}
/**
* A view should call this when content is pulled away from an edge by the user.
* This will update the state of the current visual effect and its associated animation.
* The host view should always {@link android.view.View#invalidate()} if this method
* returns true and draw the results accordingly.
*
* Views using {@link EdgeEffect} should favor {@link EdgeEffect#onPull(float, float)} when
* the displacement of the pull point is known.
*
* @param deltaDistance Change in distance since the last call. Values may be 0 (no change) to
* 1.f (full length of the view) or negative values to express change
* back toward the edge reached to initiate the effect.
* @param displacement The displacement from the starting side of the effect of the point
* initiating the pull. In the case of touch this is the finger position.
* Values may be from 0-1.
* @return true if the host view should call invalidate, false if it should not.
*
* @deprecated Use {@link EdgeEffect#onPull(float)} directly.
*/
@Deprecated
public boolean onPull(float deltaDistance, float displacement) {
onPull(mEdgeEffect, deltaDistance, displacement);
return true;
}
/**
* A view should call this when content is pulled away from an edge by the user.
* This will update the state of the current visual effect and its associated animation.
* The host view should always {@link android.view.View#invalidate()} after call this method
* and draw the results accordingly.
*
* @param edgeEffect The EdgeEffect that is attached to the view that is getting pulled away
* from an edge by the user.
* @param deltaDistance Change in distance since the last call. Values may be 0 (no change) to
* 1.f (full length of the view) or negative values to express change
* back toward the edge reached to initiate the effect.
* @param displacement The displacement from the starting side of the effect of the point
* initiating the pull. In the case of touch this is the finger position.
* Values may be from 0-1.
*
* @see EdgeEffect#onPull(float, float)
*/
public static void onPull(@NonNull EdgeEffect edgeEffect, float deltaDistance,
float displacement) {
if (Build.VERSION.SDK_INT >= 21) {
edgeEffect.onPull(deltaDistance, displacement);
} else {
edgeEffect.onPull(deltaDistance);
}
}
/**
* A view should call this when content is pulled away from an edge by the user.
* This will update the state of the current visual effect and its associated animation.
* The host view should always {@link android.view.View#invalidate()} after this
* and draw the results accordingly. This works similarly to {@link #onPull(float, float)},
* but returns the amount of <code>deltaDistance</code> that has been consumed. For versions
* {@link Build.VERSION_CODES#S} and above, if the {@link #getDistance(EdgeEffect)} is currently
* 0 and <code>deltaDistance</code> is negative, this function will return 0 and the drawn value
* will remain unchanged. For versions {@link Build.VERSION_CODES#R} and below, this will
* consume all of the provided value and return <code>deltaDistance</code>.
*
* This method can be used to reverse the effect from a pull or absorb and partially consume
* some of a motion:
*
* <pre class="prettyprint">
* if (deltaY < 0 && EdgeEffectCompat.getDistance(edgeEffect) != 0) {
* float displacement = x / getWidth();
* float dist = deltaY / getHeight();
* float consumed = EdgeEffectCompat.onPullDistance(edgeEffect, dist, displacement);
* deltaY -= consumed * getHeight();
* if (edgeEffect.getDistance() == 0f) edgeEffect.onRelease();
* }
* </pre>
*
* @param deltaDistance Change in distance since the last call. Values may be 0 (no change) to
* 1.f (full length of the view) or negative values to express change
* back toward the edge reached to initiate the effect.
* @param displacement The displacement from the starting side of the effect of the point
* initiating the pull. In the case of touch this is the finger position.
* Values may be from 0-1.
* @return The amount of <code>deltaDistance</code> that was consumed, a number between
* 0 and <code>deltaDistance</code>.
*/
public static float onPullDistance(
@NonNull EdgeEffect edgeEffect,
float deltaDistance,
float displacement
) {
if (BuildCompat.isAtLeastS()) {
return Api31Impl.onPullDistance(edgeEffect, deltaDistance, displacement);
}
onPull(edgeEffect, deltaDistance, displacement);
return deltaDistance;
}
/**
* Call when the object is released after being pulled.
* This will begin the "decay" phase of the effect. After calling this method
* the host view should {@link android.view.View#invalidate()} if this method
* returns true and thereby draw the results accordingly.
*
* @return true if the host view should invalidate, false if it should not.
*
* @deprecated Use {@link EdgeEffect#onRelease()} directly.
*/
@Deprecated
public boolean onRelease() {
mEdgeEffect.onRelease();
return mEdgeEffect.isFinished();
}
/**
* Call when the effect absorbs an impact at the given velocity.
* Used when a fling reaches the scroll boundary.
*
* <p>When using a {@link android.widget.Scroller} or {@link android.widget.OverScroller},
* the method <code>getCurrVelocity</code> will provide a reasonable approximation
* to use here.</p>
*
* @param velocity Velocity at impact in pixels per second.
* @return true if the host view should invalidate, false if it should not.
*
* @deprecated Use {@link EdgeEffect#onAbsorb(int)} directly.
*/
@Deprecated
public boolean onAbsorb(int velocity) {
mEdgeEffect.onAbsorb(velocity);
return true;
}
/**
* Draw into the provided canvas. Assumes that the canvas has been rotated
* accordingly and the size has been set. The effect will be drawn the full
* width of X=0 to X=width, beginning from Y=0 and extending to some factor <
* 1.f of height.
*
* @param canvas Canvas to draw into
* @return true if drawing should continue beyond this frame to continue the
* animation
*
* @deprecated Use {@link EdgeEffect#draw(Canvas)} directly.
*/
@Deprecated
public boolean draw(Canvas canvas) {
return mEdgeEffect.draw(canvas);
}
// TODO(b/181171227): This actually requires S, but we don't have a version for S yet.
@RequiresApi(Build.VERSION_CODES.R)
private static class Api31Impl {
private Api31Impl() {}
@DoNotInline
public static EdgeEffect create(Context context, AttributeSet attrs) {
try {
return new EdgeEffect(context, attrs);
} catch (Throwable t) {
return new EdgeEffect(context); // Old preview release
}
}
@DoNotInline
public static float onPullDistance(
EdgeEffect edgeEffect,
float deltaDistance,
float displacement
) {
try {
return edgeEffect.onPullDistance(deltaDistance, displacement);
} catch (Throwable t) {
edgeEffect.onPull(deltaDistance, displacement); // Old preview release
return 0;
}
}
@DoNotInline
public static float getDistance(EdgeEffect edgeEffect) {
try {
return edgeEffect.getDistance();
} catch (Throwable t) {
return 0; // Old preview release
}
}
}
}
| 4,990 |
778 | <filename>applications/SolidMechanicsApplication/custom_conditions/boundary_condition.hpp
//
// Project Name: KratosSolidMechanicsApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: August 2017 $
// Revision: $Revision: 0.0 $
//
//
#if !defined(KRATOS_BOUNDARY_CONDITION_H_INCLUDED)
#define KRATOS_BOUNDARY_CONDITION_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/checks.h"
#include "includes/condition.h"
#include "custom_utilities/solid_mechanics_math_utilities.hpp"
#include "utilities/beam_math_utilities.hpp"
#include "custom_utilities/element_utilities.hpp"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// General Boundary Condition base type for 3D and 2D geometries.
/**
* Implements a General definitions for a boundary neumann or mixed condition.
* This works for arbitrary geometries in 3D and 2D (base class)
*/
class KRATOS_API(SOLID_MECHANICS_APPLICATION) BoundaryCondition
: public Condition
{
public:
///@name Type Definitions
///@{
typedef Variable<array_1d<double,3>> VariableVectorType;
typedef Variable<double> VariableScalarType;
///Type for size
typedef GeometryData::SizeType SizeType;
// Counted pointer of BoundaryCondition
KRATOS_CLASS_INTRUSIVE_POINTER_DEFINITION( BoundaryCondition );
///@}
protected:
/**
* Flags related to the element computation
*/
KRATOS_DEFINE_LOCAL_FLAG( COMPUTE_RHS_VECTOR );
KRATOS_DEFINE_LOCAL_FLAG( COMPUTE_LHS_MATRIX );
/**
* Parameters to be used in the Condition as they are.
*/
struct ConditionVariables
{
private:
//variables including all integration points
const GeometryType::ShapeFunctionsGradientsType* pDN_De;
const Matrix* pNcontainer;
public:
//for axisymmetric use only
double CurrentRadius;
double ReferenceRadius;
//general variables
double GeometrySize;
double Jacobian;
Vector N;
Matrix DN_De;
Matrix DeltaPosition;
//external boundary values
double ExternalScalarValue;
Vector ExternalVectorValue;
//boundary characteristics
Vector Normal;
Vector Tangent1;
Vector Tangent2;
//variables including all integration points
GeometryType::JacobiansType j;
GeometryType::JacobiansType J;
/**
* sets the value of a specified pointer variable
*/
void SetShapeFunctionsGradients(const GeometryType::ShapeFunctionsGradientsType &rDN_De)
{
pDN_De=&rDN_De;
};
void SetShapeFunctions(const Matrix& rNcontainer)
{
pNcontainer=&rNcontainer;
};
/**
* returns the value of a specified pointer variable
*/
const GeometryType::ShapeFunctionsGradientsType& GetShapeFunctionsGradients()
{
return *pDN_De;
};
const Matrix& GetShapeFunctions()
{
return *pNcontainer;
};
void Initialize( const unsigned int& dimension,
const unsigned int& local_dimension,
const unsigned int& number_of_nodes )
{
//doubles
//radius
CurrentRadius = 0;
ReferenceRadius = 0;
//jacobians
GeometrySize = 1;
Jacobian = 1;
//external boundary values
ExternalScalarValue = 0;
ExternalVectorValue.resize(dimension,false);
noalias(ExternalVectorValue) = ZeroVector(dimension);
//vectors
N.resize(number_of_nodes,false);
Normal.resize(dimension,false);
Tangent1.resize(dimension,false);
Tangent2.resize(dimension,false);
noalias(N) = ZeroVector(number_of_nodes);
noalias(Normal) = ZeroVector(dimension);
noalias(Tangent1) = ZeroVector(dimension);
noalias(Tangent2) = ZeroVector(dimension);
//matrices
DN_De.resize(number_of_nodes, local_dimension,false);
noalias(DN_De) = ZeroMatrix(number_of_nodes, local_dimension);
DeltaPosition.resize(number_of_nodes, dimension,false);
noalias(DeltaPosition) = ZeroMatrix(number_of_nodes, dimension);
//others
J.resize(1,false);
j.resize(1,false);
J[0].resize(dimension,dimension,false);
j[0].resize(dimension,dimension,false);
noalias(J[0]) = ZeroMatrix(dimension,dimension);
noalias(j[0]) = ZeroMatrix(dimension,dimension);
//pointers
pDN_De = NULL;
pNcontainer = NULL;
}
};
/**
* This struct is used in the component wise calculation only
* is defined here and is used to declare a member variable in the component wise condition
* private pointers can only be accessed by means of set and get functions
* this allows to set and not copy the local system variables
*/
struct LocalSystemComponents
{
private:
//for calculation local system with compacted LHS and RHS
MatrixType *mpLeftHandSideMatrix;
VectorType *mpRightHandSideVector;
public:
//calculation flags
Flags CalculationFlags;
/**
* sets the value of a specified pointer variable
*/
void SetLeftHandSideMatrix( MatrixType& rLeftHandSideMatrix ) { mpLeftHandSideMatrix = &rLeftHandSideMatrix; };
void SetRightHandSideVector( VectorType& rRightHandSideVector ) { mpRightHandSideVector = &rRightHandSideVector; };
/**
* returns the value of a specified pointer variable
*/
MatrixType& GetLeftHandSideMatrix() { return *mpLeftHandSideMatrix; };
VectorType& GetRightHandSideVector() { return *mpRightHandSideVector; };
};
public:
///@name Life Cycle
///@{
/// Empty constructor needed for serialization
BoundaryCondition();
/// Default constructor.
BoundaryCondition( IndexType NewId, GeometryType::Pointer pGeometry );
BoundaryCondition( IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties );
/// Copy constructor
BoundaryCondition( BoundaryCondition const& rOther);
/// Destructor
~BoundaryCondition() override;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* creates a new condition pointer
* @param NewId: the ID of the new condition
* @param ThisNodes: the nodes of the new condition
* @param pProperties: the properties assigned to the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Create(IndexType NewId,
NodesArrayType const& ThisNodes,
PropertiesType::Pointer pProperties ) const override;
/**
* clones the selected condition variables, creating a new one
* @param NewId: the ID of the new condition
* @param ThisNodes: the nodes of the new condition
* @param pProperties: the properties assigned to the new condition
* @return a Pointer to the new condition
*/
Condition::Pointer Clone(IndexType NewId,
NodesArrayType const& ThisNodes) const override;
//************* STARTING - ENDING METHODS
/**
* Called at the beginning of each solution step
*/
void Initialize(const ProcessInfo& rCurrentProcessInfo) override;
/**
* Called at the beginning of each solution step
*/
void InitializeSolutionStep(const ProcessInfo& rCurrentProcessInfo) override;
/**
* Called at the beginning of each iteration
*/
void InitializeNonLinearIteration(const ProcessInfo& rCurrentProcessInfo) override;
//************* GETTING METHODS
/**
* Sets on rConditionDofList the degrees of freedom of the considered element geometry
*/
void GetDofList(DofsVectorType& rConditionDofList,
const ProcessInfo& rCurrentProcessInfo ) const override;
/**
* Sets on rResult the ID's of the element degrees of freedom
*/
void EquationIdVector(EquationIdVectorType& rResult,
const ProcessInfo& rCurrentProcessInfo ) const override;
/**
* Sets on rValues the nodal displacements
*/
void GetValuesVector(Vector& rValues,
int Step = 0 ) const override;
/**
* Sets on rValues the nodal velocities
*/
void GetFirstDerivativesVector(Vector& rValues,
int Step = 0 ) const override;
/**
* Sets on rValues the nodal accelerations
*/
void GetSecondDerivativesVector(Vector& rValues,
int Step = 0 ) const override;
//************* COMPUTING METHODS
/**
* this is called during the assembling process in order
* to calculate all condition contributions to the global system
* matrix and the right hand side
* @param rLeftHandSideMatrix: the condition left hand side matrix
* @param rRightHandSideVector: the condition right hand side
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateLocalSystem(MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this is called during the assembling process in order
* to calculate the condition right hand side vector only
* @param rRightHandSideVector: the condition right hand side vector
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateRightHandSide(VectorType& rRightHandSideVector,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this is called during the assembling process in order
* to calculate the condition left hand side matrix only
* @param rLeftHandSideMatrix: the condition left hand side matrix
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateLeftHandSide(MatrixType& rLeftHandSideMatrix,
const ProcessInfo& rCurrentProcessInfo) override;
/**
* this is called during the assembling process in order
* to calculate the condition mass matrix
* @param rMassMatrix: the condition mass matrix
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateMassMatrix(MatrixType& rMassMatrix,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this is called during the assembling process in order
* to calculate the condition damping matrix
* @param rDampingMatrix: the condition damping matrix
* @param rCurrentProcessInfo: the current process info instance
*/
void CalculateDampingMatrix(MatrixType& rDampingMatrix,
const ProcessInfo& rCurrentProcessInfo ) override;
/**
* this function is designed to make the element to assemble an rRHS vector
* identified by a variable rRHSVariable by assembling it to the nodes on the variable
* rDestinationVariable.
* @param rRHSVector: input variable containing the RHS vector to be assembled
* @param rRHSVariable: variable describing the type of the RHS vector to be assembled
* @param rDestinationVariable: variable in the database to which the rRHSvector will be assembled
* @param rCurrentProcessInfo: the current process info instance
*/
void AddExplicitContribution(const VectorType& rRHS,
const Variable<VectorType>& rRHSVariable,
const Variable<array_1d<double,3> >& rDestinationVariable,
const ProcessInfo& rCurrentProcessInfo) override;
/**
* Calculate a double Variable
*/
void CalculateOnIntegrationPoints(const Variable<double>& rVariable,
std::vector<double>& rOutput,
const ProcessInfo& rCurrentProcessInfo) override;
//************************************************************************************
//************************************************************************************
/**
* This function provides the place to perform checks on the completeness of the input.
* It is designed to be called only once (or anyway, not often) typically at the beginning
* of the calculations, so to verify that nothing is missing from the input
* or that no common error is found.
* @param rCurrentProcessInfo
*/
int Check( const ProcessInfo& rCurrentProcessInfo ) const override;
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
/**
* Currently selected integration methods
*/
IntegrationMethod mThisIntegrationMethod;
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* Initialize Explicit Contributions
*/
void InitializeExplicitContributions();
/**
* Check dof for a vector variable
*/
virtual bool HasVariableDof(VariableVectorType& rVariable) const;
/**
* Check dof for a double variable
*/
virtual bool HasVariableDof(VariableScalarType& rVariable) const;
/**
* Get condition size from the dofs
*/
virtual unsigned int GetDofsSize() const;
/**
* Initialize System Matrices
*/
virtual void InitializeSystemMatrices(MatrixType& rLeftHandSideMatrix,
VectorType& rRightHandSideVector,
Flags& rCalculationFlags);
/**
* Initialize General Variables
*/
virtual void InitializeConditionVariables(ConditionVariables& rVariables,
const ProcessInfo& rCurrentProcessInfo);
/**
* Calculate Condition Kinematics
*/
virtual void CalculateKinematics(ConditionVariables& rVariables,
const double& rPointNumber);
/**
* Calculates the condition contributions
*/
virtual void CalculateConditionSystem(LocalSystemComponents& rLocalSystem,
const ProcessInfo& rCurrentProcessInfo);
/**
* Calculation and addition of the matrices of the LHS
*/
virtual void CalculateAndAddLHS(LocalSystemComponents& rLocalSystem,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation and addition of the vectors of the RHS
*/
virtual void CalculateAndAddRHS(LocalSystemComponents& rLocalSystem,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation of the Load Stiffness Matrix which usually is subtracted to the global stiffness matrix
*/
virtual void CalculateAndAddKuug(MatrixType& rLeftHandSideMatrix,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation of the External Forces Vector for a force or pressure vector
*/
virtual void CalculateAndAddExternalForces(Vector& rRightHandSideVector,
ConditionVariables& rVariables,
double& rIntegrationWeight);
/**
* Calculation of the External Forces Vector for a force or pressure vector
*/
virtual double& CalculateAndAddExternalEnergy(double& rEnergy,
ConditionVariables& rVariables,
double& rIntegrationWeight,
const ProcessInfo& rCurrentProcessInfo);
/**
* Get Node Movements for energy computation
*/
void GetNodalDeltaMovements(Vector& rValues, const int& rNode);
/**
* Get Current Value, buffer 0 with FastGetSolutionStepValue
*/
Vector& GetNodalCurrentValue(const Variable<array_1d<double,3> >&rVariable, Vector& rValue, const unsigned int& rNode);
/**
* Get Previous Value, buffer 1 with FastGetSolutionStepValue
*/
Vector& GetNodalPreviousValue(const Variable<array_1d<double,3> >&rVariable, Vector& rValue, const unsigned int& rNode);
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Serialization
///@{
friend class Serializer;
void save(Serializer& rSerializer) const override;
void load(Serializer& rSerializer) override;
}; // class BoundaryCondition.
} // namespace Kratos.
#endif // KRATOS_BOUNDARY_CONDITION_H_INCLUDED defined
| 6,154 |
2,260 | """Finger tree implementation and application examples.
A finger tree is a purely functional data structure used in
efficiently implementing other functional data structures. A
finger tree gives amortized constant time access to the "fingers"
(leaves) of the tree, where data is stored, and the internal
nodes are labeled in some way as to provide the functionality of
the particular data structure being implemented.
More information on Wikipedia: http://goo.gl/ppH2nE
"Finger trees: a simple general-purpose data structure": http://goo.gl/jX4DeL
"""
from collections import namedtuple
from fn.uniform import reduce
# data Node a = Node2 a a | Node3 a a a
# data Digit a = One a | Two a a | Three a a a | Four a a a a
# data FingerTree a = Empty
# | Single a
# | Deep (Digit a) (FingerTree (Node a)) (Digit a)
One = namedtuple("One", "a")
Two = namedtuple("Two", "a,b")
Three = namedtuple("Three", "a,b,c")
Four = namedtuple("Four", "a,b,c,d")
class Node2(namedtuple("Node2", "a,b")):
def __iter__(self):
yield self.a
yield self.b
class Node3(namedtuple("Node3", "a,b,c")):
def __iter__(self):
yield self.a
yield self.b
yield self.c
class FingerTree(object):
class Empty(object):
__slots__ = ("measure",)
def __init__(self, measure):
object.__setattr__(self, "measure", measure)
def __setattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be changed".format("Empty"))
def __delattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be deleted".format("Empty"))
def is_empty(self): return True
def head(self): return None
def last(self): return None
def tail(self): return self
def butlast(self): return self
def push_front(self, v):
return FingerTree.Single(self.measure, v)
def push_back(self, v):
return FingerTree.Single(self.measure, v)
def __iter__(self): return iter([])
class Single(object):
__slots__ = ("measure", "elem",)
def __init__(self, measure, elem):
object.__setattr__(self, "measure", measure)
object.__setattr__(self, "elem", elem)
def __setattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be changed".format("Single"))
def __delattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be deleted".format("Single"))
def is_empty(self): return False
def head(self): return self.elem
def last(self): return self.elem
def tail(self): return FingerTree.Empty(self.measure)
def butlast(self): return FingerTree.Empty(self.measure)
def push_front(self, v):
return FingerTree.Deep(self.measure, [v], FingerTree.Empty(self.measure), [self.elem])
def push_back(self, v):
return FingerTree.Deep(self.measure, [self.elem], FingerTree.Empty(self.measure), [v])
def __iter__(self): return iter([self.elem])
class Deep(object):
__slots__ = ("measure", "left", "middle", "right",)
def __init__(self, measure, left, middle, right):
object.__setattr__(self, "measure", measure)
object.__setattr__(self, "left", left)
object.__setattr__(self, "middle", middle)
object.__setattr__(self, "right", right)
def __setattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be changed".format("Deep"))
def __delattr__(self, *args):
raise AttributeError("Attributes of {0} object "
"cannot be deleted".format("Deep"))
def is_empty(self): return False
def head(self): return self.left[0]
def last(self): return self.right[-1]
def tail(self):
if len(self.left) == 1:
if self.middle.is_empty():
return FingerTree.from_iterable(self.measure, list(self.right))
return FingerTree.Deep(self.measure,
[self.middle.head()],
self.middle.tail(),
self.right)
return FingerTree.Deep(self.measure, self.left[1:], self.middle, self.right)
def butlast(self):
if len(self.rigth) == 1:
if self.middle.is_empty():
return FingerTree.from_iterable(self.measure, list(self.left))
return FingerTree.Deep(self.measure,
self.left,
self.middle.butlast(),
[self.middle.last()])
return FingerTree.Deep(self.measure, self.left, self.middle, self.right[:-1])
def push_front(self, v):
if len(self.left) == 4:
return FingerTree.Deep(self.measure,
[v, self.left[0]],
self.middle.push_front(Node3(*self.left[1:])),
self.right)
return FingerTree.Deep(self.measure, [v] + self.left, self.middle, self.right)
def push_back(self, v):
if len(self.right) == 4:
return FingerTree.Deep(self.measure,
self.left,
self.middle.push_back(Node3(*self.right[:3])),
[self.right[-1], v])
return FingerTree.Deep(self.measure, self.left, self.middle, self.right + [v])
def __iter__(self):
for l in self.left: yield l
for m in self.middle:
for mi in m:
yield mi
for r in self.right: yield r
@staticmethod
def from_iterable(measure, it):
tree = FingerTree.Empty(measure)
return reduce(lambda acc, curr: acc.push_front(curr), it, tree)
def __new__(_cls, measure):
return FingerTree.Empty(measure)
#####################################################
# Possible applications of finger tree in practice
#####################################################
class Deque(object):
def __new__(_cls):
return FingerTree.Empty(lambda x: x)
@staticmethod
def from_iterable(it):
return FingerTree.from_iterable(lambda x: x, it)
| 3,244 |
602 | import matplotlib.pyplot as plt
from scipy.stats import beta, poisson, norm
import numpy as np
import pymc3 as pm
import arviz as az
from functools import lru_cache
def plot_betadist_pdf(a, b):
b = beta(a, b)
x = np.linspace(0, 1, 1000)
pdf = b.pdf(x)
plt.plot(x, pdf)
def coin_flip_data():
return np.array([1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1,])
def car_crash_data():
return poisson(3).rvs(25)
def finch_beak_data():
return norm(12, 1).rvs(38)
def car_crash_model_generator():
data = car_crash_data()
with pm.Model() as car_crash_model:
mu = pm.Exponential("mu", lam=1 / 29.0)
like = pm.Poisson("like", mu=mu, observed=data)
return car_crash_model
def car_crash_interpretation():
ans = """
We believe that the rate of car crashes per week
is anywhere from between 2.3 to 3.6 (94% posterior HDI),
with a mean of 2.9.
"""
return ans
def model_inference_answer(model):
with model:
trace = pm.sample(2000)
trace = az.from_pymc3(trace)
return trace
def model_trace_answer(trace):
az.plot_trace(trace)
def model_posterior_answer(trace):
az.plot_posterior(trace)
def finch_beak_model_generator():
data = finch_beak_data()
with pm.Model() as finch_beak_model:
mu = pm.Normal("mu", mu=10, sigma=3)
sigma = pm.Exponential("sigma", lam=1 / 29.0)
like = pm.Normal("like", mu=mu, sigma=sigma, observed=data)
return finch_beak_model
def finch_beak_interpretation():
ans = """
Having seen the data, we believe that finch beak lengths
are expected to be between 11.7 and 12.1 (approx, 94% HDI),
with an average of 11.9.
We also believe that the intrinsic variance of finch beak lengths
across the entire population of finches
is estimated to be around 0.56 to 0.87,
with an average of 0.7.
"""
return ans
| 761 |
948 | /*
* Copyright (c) 2016, Zolertia - http://www.zolertia.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE 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.
*
*/
/*---------------------------------------------------------------------------*/
/**
* \addtogroup zoul-servo
* @{
*
* \file
* Driver for a generic Servo driver
*
* \author
* <NAME> <<EMAIL>>
*/
/*---------------------------------------------------------------------------*/
#include "contiki.h"
#include "dev/pwm.h"
#include "dev/gpio.h"
#include "servo.h"
/*---------------------------------------------------------------------------*/
#define DEBUG 0
#if DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif
/*---------------------------------------------------------------------------*/
int
servo_position(uint16_t gptab, uint8_t port, uint8_t pin, uint16_t pos)
{
uint8_t gpt_num;
uint8_t gpt_ab;
uint32_t count = 0;
if((gptab < SERVO_CHANNEL_1) && (gptab > SERVO_CHANNEL_7)) {
PRINTF("Servo: invalid servo channel\n");
return SERVO_ERROR;
}
/* CC2538 has 4 ports (A-D) and up to 8 pins (0-7) */
if((port > GPIO_D_NUM) || (pin > 7)) {
PRINTF("Servo: Invalid pin/port settings\n");
return SERVO_ERROR;
}
if(pos > SERVO_MAX_DEGREES) {
PRINTF("Servo: invalid position (max %u)\n", SERVO_MAX_DEGREES);
return SERVO_ERROR;
}
count = (SERVO_MAX_VAL - SERVO_MIN_VAL) * pos;
count /= SERVO_MAX_DEGREES;
count += SERVO_MIN_VAL;
gpt_num = (uint8_t)(gptab >> 8);
gpt_ab = (uint8_t)(gptab & 0x00FF);
PRINTF("Servo: F%uHz GPTNUM %u GPTAB %u --> %uº (%lu)\n", SERVO_DEFAULT_FREQ,
gpt_num, gpt_ab,
pos, count);
/* Use count as argument instead of percentage */
if(pwm_enable(SERVO_DEFAULT_FREQ, 0, count, gpt_num,gpt_ab) != PWM_SUCCESS) {
PRINTF("Servo: failed to configure the pwm channel\n");
return SERVO_ERROR;
}
/* Start the PWM as soon as possible, keep the pulses to lock the servo in the
* given position
*/
if(pwm_start(gpt_num, gpt_ab, port, pin) != PWM_SUCCESS) {
PRINTF("Servo: failed to initialize the pwm channel\n");
return SERVO_ERROR;
}
return SERVO_SUCCESS;
}
/*---------------------------------------------------------------------------*/
int
servo_stop(uint16_t gptab, uint8_t port, uint8_t pin)
{
uint8_t gpt_num;
uint8_t gpt_ab;
if((gptab < SERVO_CHANNEL_1) && (gptab > SERVO_CHANNEL_7)) {
PRINTF("Servo: invalid servo channel\n");
return SERVO_ERROR;
}
/* CC2538 has 4 ports (A-D) and up to 8 pins (0-7) */
if((port > GPIO_D_NUM) || (pin > 7)) {
PRINTF("Servo: Invalid pin/port settings\n");
return SERVO_ERROR;
}
gpt_num = (uint8_t)((gptab & 0xFF00) >> 8);
gpt_ab = (uint8_t)(gptab & 0x00FF);
if(pwm_disable(gpt_num, gpt_ab, port, pin) != PWM_SUCCESS) {
PRINTF("Servo: unable to disable the pwm channel\n");
return SERVO_ERROR;
}
return SERVO_SUCCESS;
}
/*---------------------------------------------------------------------------*/
/** @} */
| 1,667 |
1,772 | <filename>dojo/db_migrations/0123_scan_type.py<gh_stars>1000+
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dojo', '0122_cobaltio_product'),
]
operations = [
migrations.AddField(
model_name='test',
name='scan_type',
field=models.TextField(null=True),
),
]
| 181 |
522 | package algs.example.convexhull.imageBound;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Compute convex hull and number of distinct regions for given sample
* ASCII image.
*
* @author <NAME>
* @version 1.0, 6/15/08
* @since 1.0
*/
public class OneMore {
public static void main(String[] args) throws FileNotFoundException {
String loc = "resources" + java.io.File.separatorChar +
"algs" + java.io.File.separatorChar +
"chapter9" + java.io.File.separatorChar;
File f = new File (loc, "sample.3");
char [][]img = CharImageLoad.loadImage(f, ' ');
// convert each contiguous region in to a number. Note that we use ' ' as
// the default EMPTY region.
int numR = CharImageLoad.identifyRegions (img, ' ');
CharImageLoad.output(img);
System.out.println (numR + " regions found.");
}
}
| 302 |
3,102 | <gh_stars>1000+
// RUN: %clang_cc1 -emit-llvm %s -o -
// Test case by <NAME>!
void foo(void)
{
char a[1];
int t = 1;
((char (*)[t]) a)[0][0] = 0;
}
| 79 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-6w2r-x6qc-ch2w",
"modified": "2022-04-30T18:18:11Z",
"published": "2022-04-30T18:18:11Z",
"aliases": [
"CVE-2001-1517"
],
"details": "** DISPUTED ** RunAs (runas.exe) in Windows 2000 stores cleartext authentication information in memory, which could allow attackers to obtain usernames and passwords by executing a process that is allocated the same memory page after termination of a RunAs command. NOTE: the vendor disputes this issue, saying that administrative privileges are already required to exploit it, and the original researcher did not respond to requests for additional information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2001-1517"
},
{
"type": "WEB",
"url": "http://archives.neohapsis.com/archives/vulnwatch/2001-q4/0041.html"
},
{
"type": "WEB",
"url": "http://cert.uni-stuttgart.de/archive/bugtraq/2001/11/msg00100.html"
},
{
"type": "WEB",
"url": "http://www.iss.net/security_center/static/7531.php"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/3184"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "LOW",
"github_reviewed": false
}
} | 553 |
310 | <reponame>dreeves/usesthis
{
"name": "NeatReceipts",
"description": "A portable scanner and digital filing system.",
"url": "http://www.neat.com/products/neatreceipts/"
} | 66 |
4,638 | {
"name": "root",
"author": "<NAME> <<EMAIL>> (https://davidmurdoch.com)",
"private": true,
"engines": {
"node": ">=10.13.0 <=14.16.0",
"npm": ">=6.4.1"
},
"scripts": {
"build": "npm run tsc && cross-env NODE_OPTIONS=--max_old_space_size=4096 lerna run build",
"clean": "npm run tsc.clean && npx lerna clean -y && npx shx rm -rf node_modules",
"create": "ts-node scripts/create",
"docs.build": "shx cp -r src/packages/ganache/dist/web/* docs/assets/js/ganache && lerna run docs.build && ts-node scripts/build-docs/",
"docs.preview": "lerna run docs.preview",
"postinstall": "ts-node scripts/postinstall",
"reinstall": "npm run clean && npm install",
"release": "npm run tsc.clean && npm run tsc && npm test && npm run build && lerna publish --yes --canary --no-git-reset --preid canary --dist-tag canary --force-publish --exact && npm run docs.build",
"prepublishOnly": "ts-node ./scripts/filter-shrinkwrap.ts \"$(lerna list --parseable --scope ganache)\"/npm-shrinkwrap.json",
"start": "lerna exec --loglevel=silent --scope ganache -- npm run start --silent -- ",
"test": "lerna exec --concurrency 1 -- npm run test",
"tsc": "ttsc --build src",
"tsc.clean": "npx lerna exec -- npx shx rm -rf lib dist typings"
},
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "1.0.1",
"@types/fs-extra": "9.0.7",
"@types/mocha": "8.2.2",
"@types/node": "14.14.31",
"@types/prettier": "2.2.1",
"@types/yargs": "16.0.0",
"@zerollup/ts-transform-paths": "1.7.18",
"camelcase": "6.2.0",
"chalk": "4.1.0",
"cli-highlight": "2.1.10",
"comment-json": "4.1.0",
"cross-env": "7.0.2",
"fs-extra": "9.0.1",
"git-user-name": "2.0.0",
"glob": "7.1.6",
"husky": "5.1.1",
"into-stream": "6.0.0",
"lerna": "4.0.0",
"marked": "2.0.0",
"mocha": "8.4.0",
"monaco-editor": "0.22.3",
"nyc": "15.1.0",
"prettier": "2.2.1",
"pretty-quick": "3.1.0",
"shx": "0.3.3",
"ts-node": "9.1.1",
"ts-transformer-inline-file": "0.1.1",
"ttypescript": "1.5.12",
"typescript": "4.1.3",
"validate-npm-package-name": "3.0.0",
"yargs": "16.2.0"
},
"license": "MIT",
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
},
"dependencies": {}
}
| 1,116 |
1,357 | <reponame>JonyFang/MTHawkeye<gh_stars>1000+
//
// Copyright (c) 2014-2016, Flipboard
// All rights reserved.
//
// This source code is licensed under the license found in the LICENSE file in
// the root directory of this source tree.
//
// Created on: 2/10/15
// Created by: <NAME>
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class MTHNetworkTransaction;
@class MTHNetworkTaskAdvice;
@interface MTHNetworkTransactionDetailTableViewController : UITableViewController
@property (nonatomic, strong) MTHNetworkTransaction *transaction;
@property (nonatomic, strong, nullable) NSArray<MTHNetworkTaskAdvice *> *advices;
@end
NS_ASSUME_NONNULL_END
| 218 |
6,224 | <filename>subsys/mgmt/osdp/src/osdp.c
/*
* Copyright (c) 2020 <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr.h>
#include <kernel.h>
#include <init.h>
#include <device.h>
#include <drivers/uart.h>
#include <sys/ring_buffer.h>
#include <logging/log.h>
#include "osdp_common.h"
LOG_MODULE_REGISTER(osdp, CONFIG_OSDP_LOG_LEVEL);
#ifdef CONFIG_OSDP_SC_ENABLED
#ifdef CONFIG_OSDP_MODE_PD
#define OSDP_KEY_STRING CONFIG_OSDP_PD_SCBK
#else
#define OSDP_KEY_STRING CONFIG_OSDP_MASTER_KEY
#endif
#else
#define OSDP_KEY_STRING ""
#endif /* CONFIG_OSDP_SC_ENABLED */
struct osdp_device {
struct ring_buf rx_buf;
struct ring_buf tx_buf;
#ifdef CONFIG_OSDP_MODE_PD
int rx_event_data;
struct k_fifo rx_event_fifo;
#endif
uint8_t rx_fbuf[CONFIG_OSDP_UART_BUFFER_LENGTH];
uint8_t tx_fbuf[CONFIG_OSDP_UART_BUFFER_LENGTH];
struct uart_config dev_config;
const struct device *dev;
int wait_for_mark;
uint8_t last_byte;
};
static struct osdp osdp_ctx;
static struct osdp_cp osdp_cp_ctx;
static struct osdp_pd osdp_pd_ctx[CONFIG_OSDP_NUM_CONNECTED_PD];
static struct osdp_device osdp_device;
static struct k_thread osdp_refresh_thread;
static K_THREAD_STACK_DEFINE(osdp_thread_stack, CONFIG_OSDP_THREAD_STACK_SIZE);
static void osdp_handle_in_byte(struct osdp_device *p, uint8_t *buf, int len)
{
if (p->wait_for_mark) {
/* Check for new packet beginning with [FF,53,...] sequence */
if (p->last_byte == 0xFF && buf[0] == 0x53) {
buf[0] = 0xFF;
ring_buf_put(&p->rx_buf, buf, 1); /* put last byte */
buf[0] = 0x53;
ring_buf_put(&p->rx_buf, buf, len); /* put rest */
p->wait_for_mark = 0; /* Mark found. Clear flag */
}
p->last_byte = buf[0];
return;
}
ring_buf_put(&p->rx_buf, buf, len);
}
static void osdp_uart_isr(const struct device *dev, void *user_data)
{
size_t len;
uint8_t buf[64];
struct osdp_device *p = user_data;
while (uart_irq_update(dev) && uart_irq_is_pending(dev)) {
if (uart_irq_rx_ready(dev)) {
len = uart_fifo_read(dev, buf, sizeof(buf));
if (len > 0) {
osdp_handle_in_byte(p, buf, len);
}
}
if (uart_irq_tx_ready(dev)) {
len = ring_buf_get(&p->tx_buf, buf, 1);
if (!len) {
uart_irq_tx_disable(dev);
} else {
uart_fifo_fill(dev, buf, 1);
}
}
}
#ifdef CONFIG_OSDP_MODE_PD
if (p->wait_for_mark == 0) {
/* wake osdp_refresh thread */
k_fifo_put(&p->rx_event_fifo, &p->rx_event_data);
}
#endif
}
static int osdp_uart_receive(void *data, uint8_t *buf, int len)
{
struct osdp_device *p = data;
return (int)ring_buf_get(&p->rx_buf, buf, len);
}
static int osdp_uart_send(void *data, uint8_t *buf, int len)
{
int sent = 0;
struct osdp_device *p = data;
sent = (int)ring_buf_put(&p->tx_buf, buf, len);
uart_irq_tx_enable(p->dev);
return sent;
}
static void osdp_uart_flush(void *data)
{
struct osdp_device *p = data;
p->wait_for_mark = 1;
ring_buf_reset(&p->tx_buf);
ring_buf_reset(&p->rx_buf);
}
struct osdp *osdp_get_ctx()
{
return &osdp_ctx;
}
static struct osdp *osdp_build_ctx(struct osdp_channel *channel)
{
int i;
struct osdp *ctx;
struct osdp_pd *pd;
int pd_adddres[CONFIG_OSDP_NUM_CONNECTED_PD] = {0};
#ifdef CONFIG_OSDP_MODE_PD
pd_adddres[0] = CONFIG_OSDP_PD_ADDRESS;
#else
if (osdp_extract_address(pd_adddres)) {
return NULL;
}
#endif
ctx = &osdp_ctx;
ctx->cp = &osdp_cp_ctx;
ctx->cp->__parent = ctx;
ctx->cp->num_pd = CONFIG_OSDP_NUM_CONNECTED_PD;
ctx->pd = &osdp_pd_ctx[0];
SET_CURRENT_PD(ctx, 0);
for (i = 0; i < CONFIG_OSDP_NUM_CONNECTED_PD; i++) {
pd = TO_PD(ctx, i);
pd->offset = i;
pd->seq_number = -1;
pd->__parent = ctx;
pd->address = pd_adddres[i];
pd->baud_rate = CONFIG_OSDP_UART_BAUD_RATE;
memcpy(&pd->channel, channel, sizeof(struct osdp_channel));
k_mem_slab_init(&pd->cmd.slab,
pd->cmd.slab_buf, sizeof(struct osdp_cmd),
CONFIG_OSDP_PD_COMMAND_QUEUE_SIZE);
}
return ctx;
}
void osdp_refresh(void *arg1, void *arg2, void *arg3)
{
struct osdp *ctx = osdp_get_ctx();
while (1) {
#ifdef CONFIG_OSDP_MODE_PD
k_fifo_get(&osdp_device.rx_event_fifo, K_FOREVER);
#else
k_msleep(50);
#endif
osdp_update(ctx);
}
}
static int osdp_init(const struct device *arg)
{
ARG_UNUSED(arg);
int len;
uint8_t c, *key = NULL, key_buf[16];
struct osdp *ctx;
struct osdp_device *p = &osdp_device;
struct osdp_channel channel = {
.send = osdp_uart_send,
.recv = osdp_uart_receive,
.flush = osdp_uart_flush,
.data = &osdp_device,
};
#ifdef CONFIG_OSDP_MODE_PD
k_fifo_init(&p->rx_event_fifo);
#endif
ring_buf_init(&p->rx_buf, sizeof(p->rx_fbuf), p->rx_fbuf);
ring_buf_init(&p->tx_buf, sizeof(p->tx_fbuf), p->tx_fbuf);
/* init OSDP uart device */
p->dev = device_get_binding(CONFIG_OSDP_UART_DEV_NAME);
if (p->dev == NULL) {
LOG_ERR("Failed to get UART dev binding");
k_panic();
}
/* configure uart device to 8N1 */
p->dev_config.baudrate = CONFIG_OSDP_UART_BAUD_RATE;
p->dev_config.data_bits = UART_CFG_DATA_BITS_8;
p->dev_config.parity = UART_CFG_PARITY_NONE;
p->dev_config.stop_bits = UART_CFG_STOP_BITS_1;
p->dev_config.flow_ctrl = UART_CFG_FLOW_CTRL_NONE;
uart_configure(p->dev, &p->dev_config);
uart_irq_rx_disable(p->dev);
uart_irq_tx_disable(p->dev);
uart_irq_callback_user_data_set(p->dev, osdp_uart_isr, p);
/* Drain UART fifo and set channel to wait for mark byte */
while (uart_irq_rx_ready(p->dev)) {
uart_fifo_read(p->dev, &c, 1);
}
p->wait_for_mark = 1;
/* Both TX and RX are interrupt driven */
uart_irq_rx_enable(p->dev);
/* setup OSDP */
ctx = osdp_build_ctx(&channel);
if (ctx == NULL) {
LOG_ERR("OSDP build ctx failed!");
k_panic();
}
if (IS_ENABLED(CONFIG_OSDP_SC_ENABLED)) {
if (strcmp(OSDP_KEY_STRING, "NONE") != 0) {
len = strlen(OSDP_KEY_STRING);
if (len != 32) {
LOG_ERR("Key string length must be 32");
k_panic();
}
len = hex2bin(OSDP_KEY_STRING, 32, key_buf, 16);
if (len != 16) {
LOG_ERR("Failed to parse key buffer");
k_panic();
}
key = key_buf;
}
}
if (osdp_setup(ctx, key)) {
LOG_ERR("Failed to setup OSDP device!");
k_panic();
}
LOG_INF("OSDP init okay!");
/* kick off refresh thread */
k_thread_create(&osdp_refresh_thread, osdp_thread_stack,
CONFIG_OSDP_THREAD_STACK_SIZE, osdp_refresh,
NULL, NULL, NULL, K_PRIO_COOP(2), 0, K_NO_WAIT);
return 0;
}
SYS_INIT(osdp_init, POST_KERNEL, 10);
| 2,988 |
4,901 | <filename>third_party/android/platform-libcore/android-platform-libcore/luni/src/main/java/org/xml/sax/ext/LexicalHandler.java<gh_stars>1000+
// LexicalHandler.java - optional handler for lexical parse events.
// http://www.saxproject.org
// Public Domain: no warranty.
// $Id: LexicalHandler.java,v 1.5 2002/01/30 21:00:44 dbrownell Exp $
package org.xml.sax.ext;
import org.xml.sax.SAXException;
/**
* SAX2 extension handler for lexical events.
*
* <blockquote>
* <em>This module, both source code and documentation, is in the
* Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
* See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
* for further information.
* </blockquote>
*
* <p>This is an optional extension handler for SAX2 to provide
* lexical information about an XML document, such as comments
* and CDATA section boundaries.
* XML readers are not required to recognize this handler, and it
* is not part of core-only SAX2 distributions.</p>
*
* <p>The events in the lexical handler apply to the entire document,
* not just to the document element, and all lexical handler events
* must appear between the content handler's startDocument and
* endDocument events.</p>
*
* <p>To set the LexicalHandler for an XML reader, use the
* {@link org.xml.sax.XMLReader#setProperty setProperty} method
* with the property name
* <code>http://xml.org/sax/properties/lexical-handler</code>
* and an object implementing this interface (or null) as the value.
* If the reader does not report lexical events, it will throw a
* {@link org.xml.sax.SAXNotRecognizedException SAXNotRecognizedException}
* when you attempt to register the handler.</p>
*
* @since SAX 2.0 (extensions 1.0)
* @author <NAME>
* @version 2.0.1 (sax2r2)
*/
public interface LexicalHandler
{
/**
* Report the start of DTD declarations, if any.
*
* <p>This method is intended to report the beginning of the
* DOCTYPE declaration; if the document has no DOCTYPE declaration,
* this method will not be invoked.</p>
*
* <p>All declarations reported through
* {@link org.xml.sax.DTDHandler DTDHandler} or
* {@link org.xml.sax.ext.DeclHandler DeclHandler} events must appear
* between the startDTD and {@link #endDTD endDTD} events.
* Declarations are assumed to belong to the internal DTD subset
* unless they appear between {@link #startEntity startEntity}
* and {@link #endEntity endEntity} events. Comments and
* processing instructions from the DTD should also be reported
* between the startDTD and endDTD events, in their original
* order of (logical) occurrence; they are not required to
* appear in their correct locations relative to DTDHandler
* or DeclHandler events, however.</p>
*
* <p>Note that the start/endDTD events will appear within
* the start/endDocument events from ContentHandler and
* before the first
* {@link org.xml.sax.ContentHandler#startElement startElement}
* event.</p>
*
* @param name The document type name.
* @param publicId The declared public identifier for the
* external DTD subset, or null if none was declared.
* @param systemId The declared system identifier for the
* external DTD subset, or null if none was declared.
* (Note that this is not resolved against the document
* base URI.)
* @exception SAXException The application may raise an
* exception.
* @see #endDTD
* @see #startEntity
*/
public abstract void startDTD (String name, String publicId,
String systemId)
throws SAXException;
/**
* Report the end of DTD declarations.
*
* <p>This method is intended to report the end of the
* DOCTYPE declaration; if the document has no DOCTYPE declaration,
* this method will not be invoked.</p>
*
* @exception SAXException The application may raise an exception.
* @see #startDTD
*/
public abstract void endDTD ()
throws SAXException;
/**
* Report the beginning of some internal and external XML entities.
*
* <p>The reporting of parameter entities (including
* the external DTD subset) is optional, and SAX2 drivers that
* report LexicalHandler events may not implement it; you can use the
* <code
* >http://xml.org/sax/features/lexical-handler/parameter-entities</code>
* feature to query or control the reporting of parameter entities.</p>
*
* <p>General entities are reported with their regular names,
* parameter entities have '%' prepended to their names, and
* the external DTD subset has the pseudo-entity name "[dtd]".</p>
*
* <p>When a SAX2 driver is providing these events, all other
* events must be properly nested within start/end entity
* events. There is no additional requirement that events from
* {@link org.xml.sax.ext.DeclHandler DeclHandler} or
* {@link org.xml.sax.DTDHandler DTDHandler} be properly ordered.</p>
*
* <p>Note that skipped entities will be reported through the
* {@link org.xml.sax.ContentHandler#skippedEntity skippedEntity}
* event, which is part of the ContentHandler interface.</p>
*
* <p>Because of the streaming event model that SAX uses, some
* entity boundaries cannot be reported under any
* circumstances:</p>
*
* <ul>
* <li>general entities within attribute values</li>
* <li>parameter entities within declarations</li>
* </ul>
*
* <p>These will be silently expanded, with no indication of where
* the original entity boundaries were.</p>
*
* <p>Note also that the boundaries of character references (which
* are not really entities anyway) are not reported.</p>
*
* <p>All start/endEntity events must be properly nested.
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%', and if it is the
* external DTD subset, it will be "[dtd]".
* @exception SAXException The application may raise an exception.
* @see #endEntity
* @see org.xml.sax.ext.DeclHandler#internalEntityDecl
* @see org.xml.sax.ext.DeclHandler#externalEntityDecl
*/
public abstract void startEntity (String name)
throws SAXException;
/**
* Report the end of an entity.
*
* @param name The name of the entity that is ending.
* @exception SAXException The application may raise an exception.
* @see #startEntity
*/
public abstract void endEntity (String name)
throws SAXException;
/**
* Report the start of a CDATA section.
*
* <p>The contents of the CDATA section will be reported through
* the regular {@link org.xml.sax.ContentHandler#characters
* characters} event; this event is intended only to report
* the boundary.</p>
*
* @exception SAXException The application may raise an exception.
* @see #endCDATA
*/
public abstract void startCDATA ()
throws SAXException;
/**
* Report the end of a CDATA section.
*
* @exception SAXException The application may raise an exception.
* @see #startCDATA
*/
public abstract void endCDATA ()
throws SAXException;
/**
* Report an XML comment anywhere in the document.
*
* <p>This callback will be used for comments inside or outside the
* document element, including comments in the external DTD
* subset (if read). Comments in the DTD must be properly
* nested inside start/endDTD and start/endEntity events (if
* used).</p>
*
* @param ch An array holding the characters in the comment.
* @param start The starting position in the array.
* @param length The number of characters to use from the array.
* @exception SAXException The application may raise an exception.
*/
public abstract void comment (char ch[], int start, int length)
throws SAXException;
}
// end of LexicalHandler.java
| 2,756 |
351 | <reponame>DeathGOD7/Floodgate
/*
* Copyright (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Floodgate
*/
package org.geysermc.floodgate.addon.data;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.util.Random;
import org.geysermc.floodgate.api.handshake.HandshakeData;
import org.geysermc.floodgate.api.handshake.HandshakeHandler;
import org.geysermc.floodgate.api.handshake.HandshakeHandlers;
public class HandshakeHandlersImpl implements HandshakeHandlers {
private final Random random = new Random();
private final Int2ObjectMap<HandshakeHandler> handshakeHandlers = new Int2ObjectOpenHashMap<>();
@Override
public int addHandshakeHandler(HandshakeHandler handshakeHandler) {
if (handshakeHandler == null) {
return -1;
}
int key;
do {
key = random.nextInt(Integer.MAX_VALUE);
} while (handshakeHandlers.putIfAbsent(key, handshakeHandler) != null);
return key;
}
@Override
public void removeHandshakeHandler(int handshakeHandlerId) {
// key is always positive
if (handshakeHandlerId <= 0) {
return;
}
handshakeHandlers.remove(handshakeHandlerId);
}
@Override
public void removeHandshakeHandler(Class<? extends HandshakeHandler> handshakeHandler) {
if (HandshakeHandler.class == handshakeHandler) {
return;
}
handshakeHandlers.values().removeIf(handler -> handler.getClass() == handshakeHandler);
}
public void callHandshakeHandlers(HandshakeData handshakeData) {
for (HandshakeHandler handshakeHandler : handshakeHandlers.values()) {
handshakeHandler.handle(handshakeData);
}
}
}
| 974 |
451 | #include "bool.h"
/*
Big must be set equal to any very large double precision constant.
It's value here is appropriate for the Sun.
*/
#define BIG 1.0e37
/*
stdlib.h - used to define the return value of malloc() and free().
*/
#include <stdlib.h>
void
l1(m, n, a, b, toler, x, e)
int m, n;
double *a, *b, toler, *x, *e;
{
/*
This algorithm uses a modification of the simplex method
to calculate an L1 solution to an over-determined system
of linear equations.
input: n = number of unknowns.
m = number of equations (m >= n).
a = two dimensional double precision array of size
m+2 by n+2. On entry, the coefficients of the
matrix must be stored in the first m rows and
n columns of a.
b = one dimensional double precision array of length
m. On entry, b must contain the right hand
side of the equations.
toler = a small positive tolerance. Empirical
evidence suggests toler=10**(-d*2/3)
where d represents the number of
decimal digits of accuracy available.
Essentially, the routine regards any
quantity as zero unless its magnitude
exceeds toler. In particular, the
routine will not pivot on any number
whose magnitude is less than toler.
output: a = the first m rows and n columns are garbage on
output.
a[m][n] = the minimum sum of the absolute values of
the residuals.
a[m][n+1] = the rank of the matrix of coefficients.
a[m+1][n] = exit code with values:
0 - optimal solution which is probably
non-unique.
1 - unique optimal solution.
2 - calculations terminated prematurely
due to rounding errors.
a[m+1][n+1] = number of simplex iterations performed.
b = garbage on output.
x = one dimensional double precision array of length
n. On exit, this array contains a solution to
the L1 problem.
e = one dimensional double precision array of size n.
On exit, this array contains the residuals in
the equations.
Reference: <NAME> and <NAME>, "Algorithm 478:
Solution of an Overdetermined System of Equations in the
L1 norm," CACM 17, 1974, pp. 319-320.
Programmer: <NAME>
<EMAIL>
(630) 979-1822
Lucent Technologies
2000 Naperville Rd.
Room: 1A-365
Napeville, IL. 60566-7033
*/
double min, max, *ptr, *ptr1, *ptr2, *ptr3;
double fabs(), d, pivot;
long double sum;
int out, *s, m1, n1, m2, n2, i, j, kr, kl, kount, in, k, l;
boolean stage, test;
/* initialization */
m1 = m + 1;
n1 = n + 1;
m2 = m + 2;
n2 = n + 2;
s = (int *)malloc(m*sizeof(int));
for (j=0, ptr=a+m1*n2; j<n; j++, ptr++) {
*ptr = (double)(j+1);
x[j] = 0.0;
}
for (i=0, ptr=a+n1, ptr1=a+n, ptr2=a; i<m; i++, ptr += n2,
ptr1 += n2, ptr2 += n2) {
*ptr = n + i + 1;
*ptr1 = b[i];
if (b[i] <= 0.0)
for (j=0, ptr3=ptr2; j<n2; j++, ptr3++)
*ptr3 *= -1.0;
e[i] = 0.0;
}
/* compute marginal costs */
for (j=0, ptr=a; j<n1; j++, ptr++) {
sum = (long double)0.0;
for (i=0, ptr1=ptr; i<m; i++, ptr1 += n2) {
sum += (long double)(*ptr1);
}
*(a+m*n2+j) = (double)sum;
}
stage = true;
kount = -1;
kr = kl = 0;
loop1: if (stage) {
/*
Stage I:
Determine the vector to enter the basis.
*/
max = -1.0;
for (j=kr, ptr=a+m1*n2+kr, ptr1=a+m*n2+kr; j<n; j++, ptr++,
ptr1++) {
if (fabs(*ptr)<=(double)n && (d=fabs(*ptr1))>max) {
max = d;
in = j;
}
}
if (*(a+m*n2+in) < 0.0)
for (i=0, ptr=a+in; i<m2; i++, ptr += n2)
*ptr *= -1.0;
} else {
/*
Stage II
Determine the vector to enter the basis.
*/
max = -BIG;
for (j=kr, ptr=a+m*n2+kr; j<n; j++, ptr++) {
d = *ptr;
if (d >= 0.0 && d > max) {
max = d;
in = j;
} else if (d <= -2.0) {
d = -d - 2.0;
if (d > max) {
max = d;
in = j;
}
}
}
if (max <= toler) {
l = kl - 1;
for (i=0, ptr=a+n, ptr1=a+kr; i<=l; i++, ptr += n2,
ptr1 += n2)
if (*ptr < 0.0)
for (j=kr, ptr2=ptr1; j<n2; j++, ptr2++)
*ptr2 *= -1.0;
*(a+m1*n2+n) = 0.0;
if (kr == 0) {
for (j=0, ptr=a+m*n2; j<n; j++, ptr++) {
d = fabs(*ptr);
if (d <= toler || 2.0-d <= toler)
goto end;
}
*(a+m1*n2+n) = 1.0;
}
goto end;
} else if (*(a+m*n2+in) <= 0.0) {
for (i=0, ptr=a+in; i<m2; i++, ptr += n2)
*ptr *= -1.0;
*(a+m*n2+in) -= 2.0;
}
}
/* Determine the vector to leave the basis */
for (i=kl, k = -1, ptr=a+kl*n2+in, ptr1=a+kl*n2+n; i<m; i++,
ptr += n2, ptr1 += n2) {
if (*ptr > toler) {
k++;
b[k] = (*ptr1)/(*ptr);
s[k] = i;
test = true;
}
}
loop2: if (k <= -1)
test = false;
else {
min = BIG;
for (i=0; i<=k; i++)
if (b[i] < min) {
j = i;
min = b[i];
out = s[i];
}
b[j] = b[k];
s[j] = s[k];
k--;
}
/* check for linear dependence in stage I */
if (!test && stage) {
for (i=0, ptr=a+kr, ptr1=a+in; i<m2; i++, ptr += n2,
ptr1 += n2) {
d = *ptr;
*ptr = *ptr1;
*ptr1 = d;
}
kr++;
} else if (!test) {
*(a+m1*n2+n) = 2.0;
goto end;
} else {
pivot = *(a+out*n2+in);
if (*(a+m*n2+in) - pivot - pivot > toler) {
for (j=kr, ptr=a+out*n2+kr, ptr1=a+m*n2+kr; j<n1; j++,
ptr++, ptr1++) {
d = *ptr;
*ptr1 -= 2.0*d;
*ptr = -d;
}
*(a+out*n2+n1) *= -1.0;
goto loop2;
} else {
/* pivot on a[out][in]. */
for (j=kr, ptr=a+out*n2+kr; j<n1; j++, ptr++)
if (j != in)
*ptr /= pivot;
for (i=0, ptr=a+in, ptr1=a; i<m1; i++,
ptr += n2, ptr1 += n2)
if (i != out) {
d = *ptr;
for (j=kr, ptr2=ptr1+kr,
ptr3=a+out*n2+kr; j<n1; j++,
ptr2++, ptr3++)
if (j != in)
*ptr2 -= d*(*ptr3);
}
for (i=0, ptr=a+in; i<m1; i++, ptr += n2)
if (i != out)
*ptr /= -pivot;
*(a+out*n2+in) = 1.0/pivot;
d = *(a+out*n2+n1);
*(a+out*n2+n1) = *(a+m1*n2+in);
*(a+m1*n2+in) = d;
kount++;
if (stage) {
/* interchange rows in stage I */
kl++;
for (j=kr,ptr=a+out*n2+kr,ptr1=a+kount*n2+kr;
j<n2; j++, ptr++, ptr1++) {
d = *ptr;
*ptr = *ptr1;
*ptr1 = d;
}
}
}
}
if (kount + kr == n-1)
stage = false;
goto loop1;
/* prepare for final return */
end: for (i=0, ptr=a+n1, ptr1=a+n; i<m; i++, ptr += n2, ptr1 += n2) {
k = (int)(*ptr);
d = *ptr1;
if (k < 0) {
k = -k;
d = -d;
}
k--;
if (i < kl)
x[k] = d;
else {
k -= n;
e[k] = d;
}
}
*(a+m1*n2+n1) = (double)(kount+1);
*(a+m*n2+n1) = (double)(n1-kr -1);
for (i=kl, ptr=a+kl*n2+n, sum=(long double)0.0; i<m; i++, ptr += n2)
sum += (long double)(*ptr);
*(a+m*n2+n) = (long double)sum;
free((char *)s);
}
| 3,515 |
892 | <reponame>westonsteimel/advisory-database-github
{
"schema_version": "1.2.0",
"id": "GHSA-xpj5-4mpq-74xf",
"modified": "2022-02-18T00:01:00Z",
"published": "2022-02-11T00:00:48Z",
"aliases": [
"CVE-2022-22780"
],
"details": "The Zoom Client for Meetings chat functionality was susceptible to Zip bombing attacks in the following product versions: Android before version 5.8.6, iOS before version 5.9.0, Linux before version 5.8.6, macOS before version 5.7.3, and Windows before version 5.6.3. This could lead to availability issues on the client host by exhausting system resources.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2022-22780"
},
{
"type": "WEB",
"url": "https://explore.zoom.us/en/trust/security/security-bulletin"
}
],
"database_specific": {
"cwe_ids": [
"CWE-400"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 409 |
348 | {"nom":"Rébénacq","circ":"4ème circonscription","dpt":"Pyrénées-Atlantiques","inscrits":546,"abs":224,"votants":322,"blancs":36,"nuls":9,"exp":277,"res":[{"nuance":"DVD","nom":"<NAME>","voix":151},{"nuance":"REM","nom":"<NAME>","voix":126}]} | 98 |
836 | /* Copyright (C) 2003 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package cc.mallet.util;
import java.io.*;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Contains static utilities for manipulating files.
*
* Created: Thu Nov 20 15:14:16 2003
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: FileUtils.java,v 1.1 2007/10/22 21:37:40 mccallum Exp $
*/
public class FileUtils {
private FileUtils() {} // All static methods
/**
* Serializes an object to a file, masking out annoying exceptions.
* Any IO exceptions are caught, and printed to standard error.
* Consider using {@link #writeGzippedObject(java.io.File, java.io.Serializable)}
* instead, for that method will compress the serialized file, and it'll still
* be reaoable by {@link #readObject}.
* @param f File to write to
* @param obj Object to serialize
* @see #writeGzippedObject(java.io.File, java.io.Serializable)
*/
public static void writeObject (File f, Serializable obj)
{
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(obj);
oos.close();
}
catch (IOException e) {
System.err.println("Exception writing file " + f + ": " + e);
}
}
/**
* Reads a Serialized object, which may or may not be zipped.
* Guesses from the file name whether to decompress or not.
* @param f File to read data from
* @return A deserialized object.
*/
public static Object readObject (File f)
{
String fname = f.getName ();
if (fname.endsWith (".gz")) {
return readGzippedObject (f);
} else {
return readUnzippedObject (f);
}
}
/**
* Reads a serialized object from a file.
* You probably want to use {@link #readObject} instead, because that method will automatically guess
* from the extension whether the file is compressed, and call this method if necessary.
* @param f File to read object from
* @see #readObject
*/
public static Object readUnzippedObject (File f)
{
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object obj = ois.readObject();
ois.close ();
return obj;
}
catch (IOException e) {
throw new RuntimeException (e);
} catch (ClassNotFoundException e) {
throw new RuntimeException (e);
}
}
/**
* Reads every line from a given text file.
* @param f Input file.
* @return String[] Array containing each line in <code>f</code>.
*/
public static String[] readFile (File f) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader (f));
ArrayList list = new ArrayList ();
String line;
while ((line = in.readLine()) != null)
list.add (line);
return (String[]) list.toArray(new String[0]);
}
/**
* Creates a file, making sure that its name is unique.
* The file will be created as if by <tt>new File(dir, prefix+i+extension)</tt>,
* where i is an integer chosen such that the returned File does not exist.
* @param dir Directory to use for the returned file
* @param prefix Prefix of the file name (before the uniquifying integer)
* @param extension Suffix of the file name (after the uniquifying integer)
*/
public static File uniqueFile (File dir, String prefix, String extension)
throws IOException
{
File f = null;
int i = 0;
boolean wasCreated = false;
while (!wasCreated) {
if (dir != null) {
f = new File (dir, prefix+i+extension);
} else {
f = new File (prefix+i+extension);
}
wasCreated = f.createNewFile ();
i++;
}
return f;
}
/**
* Writes a serialized version of obj to a given file, compressing it using gzip.
* @param f File to write to
* @param obj Object to serialize
*/
public static void writeGzippedObject (File f, Serializable obj)
{
try {
ObjectOutputStream oos = new ObjectOutputStream (new BufferedOutputStream (new GZIPOutputStream (new FileOutputStream(f))));
oos.writeObject(obj);
oos.close();
}
catch (IOException e) {
System.err.println("Exception writing file " + f + ": " + e);
}
}
/**
* Reads a serialized object from a file that has been compressed using gzip.
* You probably want to use {@link #readObject} instead, because it will automatically guess
* from the extension whether the file is compressed, and call this method if necessary.
* @param f Compressed file to read object from
* @see #readObject
*/
public static Object readGzippedObject (File f)
{
try {
ObjectInputStream ois = new ObjectInputStream (new BufferedInputStream (new GZIPInputStream (new FileInputStream(f))));
Object obj = ois.readObject();
ois.close ();
return obj;
}
catch (IOException e) {
throw new RuntimeException (e);
} catch (ClassNotFoundException e) {
throw new RuntimeException (e);
}
}
} // FileUtils
| 1,817 |
4,535 | #include <utility>
#include "base/util/catch.h"
#include "tile/lang/parser.h"
#include "tile/lang/parser.y.h"
#include "tile/lang/parser_lex.h"
#include "tile/lang/type.h"
namespace vertexai {
namespace tile {
namespace lang {
using namespace math; // NOLINT
Context parse_helper(const std::string& code, int64_t start_tmp, const std::string& id = "") {
try {
Context ctx;
ctx.program.next_tmp = start_tmp;
ctx.id = id;
yyscan_t scanner;
yylex_init(&scanner);
YY_BUFFER_STATE state = yy_scan_string(code.c_str(), scanner);
yyparse(scanner, ctx);
yy_delete_buffer(state, scanner);
yylex_destroy(scanner);
return ctx;
} catch (std::invalid_argument& e) {
std::string err = std::string(e.what()) + " : " + code;
LOG(ERROR) << err;
throw std::invalid_argument(err);
}
}
Program Parser::Parse(const std::string& code, const std::string& id) const {
return parse_helper(code, 0, id).program;
}
Program Parser::ParseExpr(const std::string& code, int64_t start_tmp) const {
return parse_helper("expression " + code + ";", start_tmp).program;
}
Polynomial<Rational> Parser::ParsePolynomial(const std::string& code) const {
Bindings empty;
SymbolicPolynomialPtr sp = parse_helper("polynomial " + code + ";", 0).polynomial;
Polynomial<Rational> p = sp->Evaluate(empty);
return p;
}
Contraction Parser::ParseContraction(const std::string& code) const {
Bindings iconsts;
Context ctx = parse_helper("contraction " + code + ";", 0);
for (const auto& op : ctx.program.ops) {
if (op.tag == Op::CONSTANT && op.f.fn == "iconst") {
iconsts.emplace(op.output, Binding(int64_t(std::stoll(op.inputs[0].c_str()))));
}
}
Contraction c = ctx.program.ops[ctx.program.ops.size() - 1].c;
for (auto& ts : c.specs) {
for (auto& ss : ts.sspec) {
ts.spec.push_back(ss->Evaluate(iconsts));
}
ts.sspec.clear();
}
for (auto& con : c.constraints) {
con.bound = RangeConstraint(con.poly->Evaluate(iconsts), iconsts.at(con.range).iconst);
con.poly = SymbolicPolynomialPtr();
con.range = "";
}
IVLOG(1, to_string(c));
return c;
}
} // namespace lang
} // namespace tile
} // namespace vertexai
| 889 |
2,706 | /* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002 Xodnizel
*
* 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
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fceu-types.h"
#include "x6502.h"
#include "fceu.h"
#include "fds.h"
#include "sound.h"
#include "general.h"
#include "state.h"
#include "file.h"
#include "fceu-memory.h"
#include "cart.h"
#include "md5.h"
// TODO: Add code to put a delay in between the time a disk is inserted
// and the when it can be successfully read/written to. This should
// prevent writes to wrong places OR add code to prevent disk ejects
// when the virtual motor is on(mmm...virtual motor).
static DECLFR(FDSRead4030);
static DECLFR(FDSRead4031);
static DECLFR(FDSRead4032);
static DECLFR(FDSRead4033);
static DECLFW(FDSWrite);
static DECLFW(FDSWaveWrite);
static DECLFR(FDSWaveRead);
static DECLFR(FDSSRead);
static DECLFW(FDSSWrite);
static void FDSInit(void);
static void FDSClose(void);
static void FP_FASTAPASS(1) FDSFix(int a);
static uint8 FDSRegs[6];
static int32 IRQLatch, IRQCount;
static uint8 IRQa;
static uint8 *FDSRAM = NULL;
static uint32 FDSRAMSize;
static uint8 *FDSBIOS = NULL;
static uint32 FDSBIOSsize;
static uint8 *CHRRAM = NULL;
static uint32 CHRRAMSize;
/* Original disk data backup, to help in creating save states. */
static uint8 *diskdatao[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
static uint8 *diskdata[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
static uint32 TotalSides;
static uint8 DiskWritten = 0; /* Set to 1 if disk was written to. */
static uint8 writeskip;
static int32 DiskPtr;
static int32 DiskSeekIRQ;
static uint8 SelectDisk, InDisk;
uint32 lastDiskPtrRead, lastDiskPtrWrite;
#define DC_INC 1
void FDSGI(int h) {
switch (h) {
case GI_CLOSE: FDSClose(); break;
case GI_POWER: FDSInit(); break;
}
}
static void FDSStateRestore(int version) {
int x;
setmirror(((FDSRegs[5] & 8) >> 3) ^ 1);
if (version >= 9810)
for (x = 0; x < TotalSides; x++) {
int b;
for (b = 0; b < 65500; b++)
diskdata[x][b] ^= diskdatao[x][b];
}
}
void FDSSound();
void FDSSoundReset(void);
void FDSSoundStateAdd(void);
static void RenderSound(void);
static void RenderSoundHQ(void);
static void FDSInit(void) {
memset(FDSRegs, 0, sizeof(FDSRegs));
lastDiskPtrRead = lastDiskPtrWrite = writeskip = DiskPtr = DiskSeekIRQ = 0;
setmirror(1);
setprg8(0xE000, 0); // BIOS
setprg32r(1, 0x6000, 0); // 32KB RAM
setchr8(0); // 8KB CHR RAM
MapIRQHook = FDSFix;
GameStateRestore = FDSStateRestore;
SetReadHandler(0x4030, 0x4030, FDSRead4030);
SetReadHandler(0x4031, 0x4031, FDSRead4031);
SetReadHandler(0x4032, 0x4032, FDSRead4032);
SetReadHandler(0x4033, 0x4033, FDSRead4033);
SetWriteHandler(0x4020, 0x4025, FDSWrite);
SetWriteHandler(0x6000, 0xDFFF, CartBW);
SetReadHandler(0x6000, 0xFFFF, CartBR);
IRQCount = IRQLatch = IRQa = 0;
FDSSoundReset();
InDisk = 0;
SelectDisk = 0;
}
void FCEU_FDSInsert(int oride) {
if (InDisk == 255) {
FCEU_DispMessage("Disk %d Side %s Inserted", SelectDisk >> 1, (SelectDisk & 1) ? "B" : "A");
InDisk = SelectDisk;
} else {
FCEU_DispMessage("Disk %d Side %s Ejected", SelectDisk >> 1, (SelectDisk & 1) ? "B" : "A");
InDisk = 255;
}
}
void FCEU_FDSEject(void) {
InDisk = 255;
}
void FCEU_FDSSelect(void) {
if (InDisk != 255) {
FCEU_DispMessage("Eject disk before selecting.");
return;
}
SelectDisk = ((SelectDisk + 1) % TotalSides) & 3;
FCEU_DispMessage("Disk %d Side %s Selected", SelectDisk >> 1, (SelectDisk & 1) ? "B" : "A");
}
static void FP_FASTAPASS(1) FDSFix(int a) {
if ((IRQa & 2) && IRQCount) {
IRQCount -= a;
if (IRQCount <= 0) {
if (!(IRQa & 1)) {
IRQa &= ~2;
IRQCount = IRQLatch = 0;
} else
IRQCount = IRQLatch;
X6502_IRQBegin(FCEU_IQEXT);
}
}
if (DiskSeekIRQ > 0) {
DiskSeekIRQ -= a;
if (DiskSeekIRQ <= 0) {
if (FDSRegs[5] & 0x80) {
X6502_IRQBegin(FCEU_IQEXT2);
}
}
}
}
static DECLFR(FDSRead4030) {
uint8 ret = 0;
/* Cheap hack. */
if (X.IRQlow & FCEU_IQEXT) ret |= 1;
if (X.IRQlow & FCEU_IQEXT2) ret |= 2;
#ifdef FCEUDEF_DEBUGGER
if (!fceuindbg)
#endif
{
X6502_IRQEnd(FCEU_IQEXT);
X6502_IRQEnd(FCEU_IQEXT2);
}
return ret;
}
static DECLFR(FDSRead4031) {
static uint8 z = 0;
if (InDisk != 255) {
z = diskdata[InDisk][DiskPtr];
lastDiskPtrRead = DiskPtr;
#ifdef FCEUDEF_DEBUGGER
if (!fceuindbg)
#endif
{
if (DiskPtr < 64999) DiskPtr++;
DiskSeekIRQ = 150;
X6502_IRQEnd(FCEU_IQEXT2);
}
}
return z;
}
static DECLFR(FDSRead4032) {
uint8 ret;
ret = X.DB & ~7;
if (InDisk == 255)
ret |= 5;
if (InDisk == 255 || !(FDSRegs[5] & 1) || (FDSRegs[5] & 2))
ret |= 2;
return ret;
}
static DECLFR(FDSRead4033) {
return 0x80; // battery
}
/* Begin FDS sound */
#define FDSClock (1789772.7272727272727272 / 2)
typedef struct {
int64 cycles; // Cycles per PCM sample
int64 count; // Cycle counter
int64 envcount; // Envelope cycle counter
uint32 b19shiftreg60;
uint32 b24adder66;
uint32 b24latch68;
uint32 b17latch76;
int32 clockcount; // Counter to divide frequency by 8.
uint8 b8shiftreg88; // Modulation register.
uint8 amplitude[2]; // Current amplitudes.
uint8 speedo[2];
uint8 mwcount;
uint8 mwstart;
uint8 mwave[0x20]; // Modulation waveform
uint8 cwave[0x40]; // Game-defined waveform(carrier)
uint8 SPSG[0xB];
} FDSSOUND;
static FDSSOUND fdso;
#define SPSG fdso.SPSG
#define b19shiftreg60 fdso.b19shiftreg60
#define b24adder66 fdso.b24adder66
#define b24latch68 fdso.b24latch68
#define b17latch76 fdso.b17latch76
#define b8shiftreg88 fdso.b8shiftreg88
#define clockcount fdso.clockcount
#define amplitude fdso.amplitude
#define speedo fdso.speedo
void FDSSoundStateAdd(void) {
AddExState(fdso.cwave, 64, 0, "WAVE");
AddExState(fdso.mwave, 32, 0, "MWAV");
AddExState(amplitude, 2, 0, "AMPL");
AddExState(SPSG, 0xB, 0, "SPSG");
AddExState(&b8shiftreg88, 1, 0, "B88");
AddExState(&clockcount, 4, 1, "CLOC");
AddExState(&b19shiftreg60, 4, 1, "B60");
AddExState(&b24adder66, 4, 1, "B66");
AddExState(&b24latch68, 4, 1, "B68");
AddExState(&b17latch76, 4, 1, "B76");
}
static DECLFR(FDSSRead) {
switch (A & 0xF) {
case 0x0: return(amplitude[0] | (X.DB & 0xC0));
case 0x2: return(amplitude[1] | (X.DB & 0xC0));
}
return(X.DB);
}
static DECLFW(FDSSWrite) {
if (FSettings.SndRate) {
if (FSettings.soundq >= 1)
RenderSoundHQ();
else
RenderSound();
}
A -= 0x4080;
switch (A) {
case 0x0:
case 0x4:
if (V & 0x80)
amplitude[(A & 0xF) >> 2] = V & 0x3F;
break;
case 0x7:
b17latch76 = 0;
SPSG[0x5] = 0;
break;
case 0x8:
b17latch76 = 0;
fdso.mwave[SPSG[0x5] & 0x1F] = V & 0x7;
SPSG[0x5] = (SPSG[0x5] + 1) & 0x1F;
break;
}
SPSG[A] = V;
}
// $4080 - Fundamental wave amplitude data register 92
// $4082 - Fundamental wave frequency data register 58
// $4083 - Same as $4082($4083 is the upper 4 bits).
// $4084 - Modulation amplitude data register 78
// $4086 - Modulation frequency data register 72
// $4087 - Same as $4086($4087 is the upper 4 bits)
static void DoEnv() {
int x;
for (x = 0; x < 2; x++)
if (!(SPSG[x << 2] & 0x80) && !(SPSG[0x3] & 0x40)) {
static int counto[2] = { 0, 0 };
if (counto[x] <= 0) {
if (!(SPSG[x << 2] & 0x80)) {
if (SPSG[x << 2] & 0x40) {
if (amplitude[x] < 0x3F)
amplitude[x]++;
} else {
if (amplitude[x] > 0)
amplitude[x]--;
}
}
counto[x] = (SPSG[x << 2] & 0x3F);
} else
counto[x]--;
}
}
static DECLFR(FDSWaveRead) {
return(fdso.cwave[A & 0x3f] | (X.DB & 0xC0));
}
static DECLFW(FDSWaveWrite) {
if (SPSG[0x9] & 0x80)
fdso.cwave[A & 0x3f] = V & 0x3F;
}
static int ta;
static INLINE void ClockRise(void) {
if (!clockcount) {
ta++;
b19shiftreg60 = (SPSG[0x2] | ((SPSG[0x3] & 0xF) << 8));
b17latch76 = (SPSG[0x6] | ((SPSG[0x07] & 0xF) << 8)) + b17latch76;
if (!(SPSG[0x7] & 0x80)) {
int t = fdso.mwave[(b17latch76 >> 13) & 0x1F] & 7;
int t2 = amplitude[1];
int adj = 0;
if ((t & 3)) {
if ((t & 4))
adj -= (t2 * ((4 - (t & 3))));
else
adj += (t2 * ((t & 3)));
}
adj *= 2;
if (adj > 0x7F) adj = 0x7F;
if (adj < -0x80) adj = -0x80;
b8shiftreg88 = 0x80 + adj;
} else {
b8shiftreg88 = 0x80;
}
} else {
b19shiftreg60 <<= 1;
b8shiftreg88 >>= 1;
}
b24adder66 = (b24latch68 + b19shiftreg60) & 0x1FFFFFF;
}
static INLINE void ClockFall(void) {
if ((b8shiftreg88 & 1))
b24latch68 = b24adder66;
clockcount = (clockcount + 1) & 7;
}
static INLINE int32 FDSDoSound(void) {
fdso.count += fdso.cycles;
if (fdso.count >= ((int64)1 << 40)) {
dogk:
fdso.count -= (int64)1 << 40;
ClockRise();
ClockFall();
fdso.envcount--;
if (fdso.envcount <= 0) {
fdso.envcount += SPSG[0xA] * 3;
DoEnv();
}
}
if (fdso.count >= 32768) goto dogk;
// Might need to emulate applying the amplitude to the waveform a bit better...
{
int k = amplitude[0];
if (k > 0x20) k = 0x20;
return (fdso.cwave[b24latch68 >> 19] * k) * 4 / ((SPSG[0x9] & 0x3) + 2);
}
}
static int32 FBC = 0;
static void RenderSound(void) {
int32 end, start;
int32 x;
start = FBC;
end = (SOUNDTS << 16) / soundtsinc;
if (end <= start)
return;
FBC = end;
if (!(SPSG[0x9] & 0x80))
for (x = start; x < end; x++) {
uint32 t = FDSDoSound();
t += t >> 1;
t >>= 4;
Wave[x >> 4] += t; //(t>>2)-(t>>3); //>>3;
}
}
static void RenderSoundHQ(void) {
uint32 x;
if (!(SPSG[0x9] & 0x80))
for (x = FBC; x < SOUNDTS; x++) {
uint32 t = FDSDoSound();
t += t >> 1;
WaveHi[x] += t; //(t<<2)-(t<<1);
}
FBC = SOUNDTS;
}
static void HQSync(int32 ts) {
FBC = ts;
}
void FDSSound(int c) {
RenderSound();
FBC = c;
}
static void FDS_ESI(void) {
if (FSettings.SndRate) {
if (FSettings.soundq >= 1) {
fdso.cycles = (int64)1 << 39;
} else {
fdso.cycles = ((int64)1 << 40) * FDSClock;
fdso.cycles /= FSettings.SndRate * 16;
}
}
SetReadHandler(0x4040, 0x407f, FDSWaveRead);
SetWriteHandler(0x4040, 0x407f, FDSWaveWrite);
SetWriteHandler(0x4080, 0x408A, FDSSWrite);
SetReadHandler(0x4090, 0x4092, FDSSRead);
}
void FDSSoundReset(void) {
memset(&fdso, 0, sizeof(fdso));
FDS_ESI();
GameExpSound.HiSync = HQSync;
GameExpSound.HiFill = RenderSoundHQ;
GameExpSound.Fill = FDSSound;
GameExpSound.RChange = FDS_ESI;
}
static DECLFW(FDSWrite) {
switch (A) {
case 0x4020:
X6502_IRQEnd(FCEU_IQEXT);
IRQLatch &= 0xFF00;
IRQLatch |= V;
break;
case 0x4021:
X6502_IRQEnd(FCEU_IQEXT);
IRQLatch &= 0xFF;
IRQLatch |= V << 8;
break;
case 0x4022:
X6502_IRQEnd(FCEU_IQEXT);
IRQCount = IRQLatch;
IRQa = V & 3;
break;
case 0x4024:
if ((InDisk != 255) && !(FDSRegs[5] & 0x4) && (FDSRegs[3] & 0x1)) {
if (DiskPtr >= 0 && DiskPtr < 65500) {
if (writeskip)
writeskip--;
else if (DiskPtr >= 2) {
DiskWritten = 1;
diskdata[InDisk][DiskPtr - 2] = V;
lastDiskPtrWrite = DiskPtr - 2;
}
}
}
break;
case 0x4025:
X6502_IRQEnd(FCEU_IQEXT2);
if (InDisk != 255) {
if (!(V & 0x40)) {
if ((FDSRegs[5] & 0x40) && !(V & 0x10)) {
DiskSeekIRQ = 200;
DiskPtr -= 2;
}
if (DiskPtr < 0) DiskPtr = 0;
}
if (!(V & 0x4)) writeskip = 2;
if (V & 2) {
DiskPtr = 0; DiskSeekIRQ = 200;
}
if (V & 0x40) DiskSeekIRQ = 200;
}
setmirror(((V >> 3) & 1) ^ 1);
break;
}
FDSRegs[A & 7] = V;
}
static void FreeFDSMemory(void) {
int x;
for (x = 0; x < TotalSides; x++)
if (diskdata[x]) {
free(diskdata[x]);
diskdata[x] = 0;
}
}
static int SubLoad(FCEUFILE *fp) {
struct md5_context md5;
uint8 header[16];
int x;
FCEU_fread(header, 16, 1, fp);
if (memcmp(header, "FDS\x1a", 4)) {
if (!(memcmp(header + 1, "*NINTENDO-HVC*", 14))) {
long t;
t = FCEU_fgetsize(fp);
if (t < 65500)
t = 65500;
TotalSides = t / 65500;
FCEU_fseek(fp, 0, SEEK_SET);
} else
return(0);
} else
TotalSides = header[4];
md5_starts(&md5);
if (TotalSides > 8) TotalSides = 8;
if (TotalSides < 1) TotalSides = 1;
for (x = 0; x < TotalSides; x++) {
diskdata[x] = (uint8*)FCEU_malloc(65500);
if (!diskdata[x]) {
int zol;
for (zol = 0; zol < x; zol++)
free(diskdata[zol]);
return 0;
}
FCEU_fread(diskdata[x], 1, 65500, fp);
md5_update(&md5, diskdata[x], 65500);
}
md5_finish(&md5, GameInfo->MD5);
return(1);
}
static void PreSave(void) {
int x;
for (x = 0; x < TotalSides; x++) {
int b;
for (b = 0; b < 65500; b++)
diskdata[x][b] ^= diskdatao[x][b];
}
}
static void PostSave(void) {
int x;
for (x = 0; x < TotalSides; x++) {
int b;
for (b = 0; b < 65500; b++)
diskdata[x][b] ^= diskdatao[x][b];
}
}
int FDSLoad(const char *name, FCEUFILE *fp) {
FCEUFILE *zp;
int x;
char *fn = FCEU_MakeFName(FCEUMKF_FDSROM, 0, 0);
if (!(zp = FCEU_fopen(fn, 0, "rb", 0, NULL, 0))) {
FCEU_PrintError("FDS BIOS ROM image missing!\n");
free(fn);
return 0;
}
free(fn);
ResetCartMapping();
if (FDSBIOS)
free(FDSBIOS);
FDSBIOS = NULL;
if (FDSRAM)
free(FDSRAM);
FDSRAM = NULL;
if (CHRRAM)
free(CHRRAM);
CHRRAM = NULL;
FDSBIOSsize = 8192;
FDSBIOS = (uint8*)FCEU_gmalloc(FDSBIOSsize);
SetupCartPRGMapping(0, FDSBIOS, FDSBIOSsize, 0);
if (FCEU_fread(FDSBIOS, 1, FDSBIOSsize, zp) != FDSBIOSsize) {
if (FDSBIOS)
free(FDSBIOS);
FDSBIOS = NULL;
FCEU_fclose(zp);
FCEU_PrintError("Error reading FDS BIOS ROM image.\n");
return 0;
}
FCEU_fclose(zp);
FCEU_fseek(fp, 0, SEEK_SET);
FreeFDSMemory();
if (!SubLoad(fp)) {
if (FDSBIOS)
free(FDSBIOS);
FDSBIOS = NULL;
return(0);
}
{
FCEUFILE *tp;
char *fn = FCEU_MakeFName(FCEUMKF_FDS, 0, 0);
int x;
for (x = 0; x < TotalSides; x++) {
diskdatao[x] = (uint8*)FCEU_malloc(65500);
memcpy(diskdatao[x], diskdata[x], 65500);
}
if ((tp = FCEU_fopen(fn, 0, "rb", 0, NULL, 0))) {
FCEU_printf("Disk was written. Auxillary FDS file open \"%s\".\n", fn);
FreeFDSMemory();
if (!SubLoad(tp)) {
FCEU_PrintError("Error reading auxillary FDS file.\n");
if (FDSBIOS)
free(FDSBIOS);
FDSBIOS = NULL;
free(fn);
return(0);
}
FCEU_fclose(tp);
DiskWritten = 1; /* For save state handling. */
}
free(fn);
}
GameInfo->type = GIT_FDS;
GameInterface = FDSGI;
SelectDisk = 0;
InDisk = 255;
ResetExState(PreSave, PostSave);
FDSSoundStateAdd();
for (x = 0; x < TotalSides; x++) {
char temp[5];
sprintf(temp, "DDT%d", x);
AddExState(diskdata[x], 65500, 0, temp);
}
AddExState(FDSRegs, sizeof(FDSRegs), 0, "FREG");
AddExState(&IRQCount, 4, 1, "IRQC");
AddExState(&IRQLatch, 4, 1, "IQL1");
AddExState(&IRQa, 1, 0, "IRQA");
AddExState(&writeskip, 1, 0, "WSKI");
AddExState(&DiskPtr, 4, 1, "DPTR");
AddExState(&DiskSeekIRQ, 4, 1, "DSIR");
AddExState(&SelectDisk, 1, 0, "SELD");
AddExState(&InDisk, 1, 0, "INDI");
AddExState(&DiskWritten, 1, 0, "DSKW");
CHRRAMSize = 8192;
CHRRAM = (uint8*)FCEU_gmalloc(CHRRAMSize);
memset(CHRRAM, 0, CHRRAMSize);
SetupCartCHRMapping(0, CHRRAM, CHRRAMSize, 1);
AddExState(CHRRAM, CHRRAMSize, 0, "CHRR");
FDSRAMSize = 32768;
FDSRAM = (uint8*)FCEU_gmalloc(FDSRAMSize);
memset(FDSRAM, 0, FDSRAMSize);
SetupCartPRGMapping(1, FDSRAM, FDSRAMSize, 1);
AddExState(FDSRAM, FDSRAMSize, 0, "FDSR");
SetupCartMirroring(0, 0, 0);
FCEU_printf(" Sides: %d\n\n", TotalSides);
return 1;
}
void FDSClose(void) {
FILE *fp;
int x;
char *fn = FCEU_MakeFName(FCEUMKF_FDS, 0, 0);
if (!DiskWritten) return;
if (!(fp = fopen(fn, "wb"))) {
free(fn);
return;
}
FCEU_printf("FDS Save \"%s\"\n", fn);
free(fn);
for (x = 0; x < TotalSides; x++) {
if (fwrite(diskdata[x], 1, 65500, fp) != 65500) {
FCEU_PrintError("Error saving FDS image!\n");
fclose(fp);
return;
}
}
for (x = 0; x < TotalSides; x++)
if (diskdatao[x]) {
free(diskdatao[x]);
diskdatao[x] = 0;
}
FreeFDSMemory();
if (FDSBIOS)
free(FDSBIOS);
FDSBIOS = NULL;
if (FDSRAM)
free(FDSRAM);
FDSRAM = NULL;
if (CHRRAM)
free(CHRRAM);
CHRRAM = NULL;
fclose(fp);
}
| 7,971 |
665 | """Snow Globe for Adafruit Circuit Playground express with CircuitPython """
import math
import time
from adafruit_circuitplayground.express import cpx
ROLL_THRESHOLD = 30 # Total acceleration
cpx.pixels.brightness = 0.1 # set brightness value
WHITE = (65, 65, 65)
RED = (220, 0, 0)
GREEN = (0, 220, 0)
BLUE = (0, 0, 220)
SKYBLUE = (0, 20, 200)
BLACK = (0, 0, 0)
# Initialize the global states
new_roll = False
rolling = False
# pick from colors defined above, e.g., RED, GREEN, BLUE, WHITE, etc.
def fade_pixels(fade_color):
# fade up
for j in range(25):
pixel_brightness = (j * 0.01)
cpx.pixels.brightness = pixel_brightness
for i in range(10):
cpx.pixels[i] = fade_color
# fade down
for k in range(25):
pixel_brightness = (0.25 - (k * 0.01))
cpx.pixels.brightness = pixel_brightness
for i in range(10):
cpx.pixels[i] = fade_color
# fade in the pixels
fade_pixels(GREEN)
# pylint: disable=too-many-locals
def play_song(song_number):
# 1: Jingle bells
# 2: Let It Snow
# set up time signature
whole_note = 1.5 # adjust this to change tempo of everything
# these notes are fractions of the whole note
half_note = whole_note / 2
quarter_note = whole_note / 4
dotted_quarter_note = quarter_note * 1.5
eighth_note = whole_note / 8
# pylint: disable=unused-variable
# set up note values
A3 = 220
Bb3 = 233
B3 = 247
C4 = 262
Db4 = 277
D4 = 294
Eb4 = 311
E4 = 330
F4 = 349
Gb4 = 370
G4 = 392
Ab4 = 415
A4 = 440
Bb4 = 466
B4 = 494
if song_number == 1:
# jingle bells
jingle_bells_song = [
[E4, quarter_note],
[E4, quarter_note],
[E4, half_note],
[E4, quarter_note],
[E4, quarter_note],
[E4, half_note],
[E4, quarter_note],
[G4, quarter_note],
[C4, dotted_quarter_note],
[D4, eighth_note],
[E4, whole_note],
]
# pylint: disable=consider-using-enumerate
for n in range(len(jingle_bells_song)):
cpx.start_tone(jingle_bells_song[n][0])
time.sleep(jingle_bells_song[n][1])
cpx.stop_tone()
if song_number == 2:
# Let It Snow
let_it_snow_song = [
[B4, dotted_quarter_note],
[A4, eighth_note],
[G4, quarter_note],
[G4, dotted_quarter_note],
[F4, eighth_note],
[E4, quarter_note],
[E4, dotted_quarter_note],
[D4, eighth_note],
[C4, whole_note],
]
for n in range(len(let_it_snow_song)):
cpx.start_tone(let_it_snow_song[n][0])
time.sleep(let_it_snow_song[n][1])
cpx.stop_tone()
play_song(1) # play music on start
# Loop forever
while True:
# check for shaking
# Compute total acceleration
x_total = 0
y_total = 0
z_total = 0
for count in range(10):
x, y, z = cpx.acceleration
x_total = x_total + x
y_total = y_total + y
z_total = z_total + z
time.sleep(0.001)
x_total = x_total / 10
y_total = y_total / 10
z_total = z_total / 10
total_accel = math.sqrt(x_total * x_total + y_total *
y_total + z_total * z_total)
# Check for rolling
if total_accel > ROLL_THRESHOLD:
roll_start_time = time.monotonic()
new_roll = True
rolling = True
print('shaken')
# Rolling momentum
# Keep rolling for a period of time even after shaking stops
if new_roll:
if time.monotonic() - roll_start_time > 2: # seconds to run
rolling = False
# Light show
if rolling:
fade_pixels(SKYBLUE)
fade_pixels(WHITE)
cpx.pixels.brightness = 0.8
cpx.pixels.fill(WHITE)
elif new_roll:
new_roll = False
# play a song!
play_song(2)
# return to resting color
fade_pixels(GREEN)
cpx.pixels.brightness = 0.05
cpx.pixels.fill(GREEN)
| 2,067 |
2,053 | package scouter.agent.proxy;
import scouter.agent.Logger;
import scouter.agent.trace.TraceContext;
public class ElasticSearchTraceFactory {
private static IElasticSearchTracer tracer;
private static Object lock = new Object();
private static final String CLIENT = "scouter.xtra.java8.ElasticSearchTracer";
public static final IElasticSearchTracer dummy = new IElasticSearchTracer() {
@Override
public String getRequestDescription(TraceContext ctx, Object httpRequestBase) {
return "-";
}
@Override
public String getNode(TraceContext ctx, Object hostOrNode) {
return "Unknown-ElasticSearch";
}
@Override
public Throwable getResponseError(Object httpRequestBase0, Object httpResponse0) {
return null;
}
};
public static IElasticSearchTracer create(ClassLoader parent) {
try {
if (tracer == null) {
synchronized (lock) {
if (tracer == null) {
ClassLoader loader = LoaderManager.getOnlyForJava8Plus(parent);
if (loader == null) {
Logger.println("IElasticSearchTracer Client Load Error.. Dummy Loaded");
tracer = dummy;
} else {
Class c = Class.forName(CLIENT, true, loader);
tracer = (IElasticSearchTracer) c.newInstance();
}
}
}
}
return tracer;
} catch (Throwable e) {
e.printStackTrace();
Logger.println("SC-145", "fail to create", e);
return dummy;
}
}
}
| 861 |
679 | <filename>main/connectivity/java/sdbc_postgresql/src/com/sun/star/sdbcx/comp/postgresql/PostgresqlPreparedStatement.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 com.sun.star.sdbcx.comp.postgresql;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertyChangeListener;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.beans.XVetoableChangeListener;
import com.sun.star.io.XInputStream;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lib.uno.helper.ComponentBase;
import com.sun.star.sdbc.SQLException;
import com.sun.star.sdbc.XArray;
import com.sun.star.sdbc.XBlob;
import com.sun.star.sdbc.XClob;
import com.sun.star.sdbc.XCloseable;
import com.sun.star.sdbc.XConnection;
import com.sun.star.sdbc.XMultipleResults;
import com.sun.star.sdbc.XParameters;
import com.sun.star.sdbc.XPreparedBatchExecution;
import com.sun.star.sdbc.XPreparedStatement;
import com.sun.star.sdbc.XRef;
import com.sun.star.sdbc.XResultSet;
import com.sun.star.sdbc.XResultSetMetaData;
import com.sun.star.sdbc.XResultSetMetaDataSupplier;
import com.sun.star.sdbc.XWarningsSupplier;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.Date;
import com.sun.star.util.DateTime;
import com.sun.star.util.Time;
import com.sun.star.util.XCancellable;
public class PostgresqlPreparedStatement extends ComponentBase
implements XPreparedStatement, XCloseable, XPropertySet, XCancellable, XResultSetMetaDataSupplier, XParameters, XPreparedBatchExecution,
XWarningsSupplier, XMultipleResults {
private XPreparedStatement impl;
private XCloseable implCloseable;
private XPropertySet implPropertySet;
private XCancellable implCancellable;
private XResultSetMetaDataSupplier implResultSetMetaDataSupplier;
private XParameters implParameters;
private XPreparedBatchExecution implPreparedBatchExecution;
private XWarningsSupplier implWarningsSupplier;
private XMultipleResults implMultipleResults;
private XConnection connection;
public PostgresqlPreparedStatement(XPreparedStatement impl, XConnection connection) {
this.impl = impl;
this.implCloseable = UnoRuntime.queryInterface(XCloseable.class, impl);
this.implPropertySet = UnoRuntime.queryInterface(XPropertySet.class, impl);
this.implCancellable = UnoRuntime.queryInterface(XCancellable.class, impl);
this.implResultSetMetaDataSupplier = UnoRuntime.queryInterface(XResultSetMetaDataSupplier.class, impl);
this.implParameters = UnoRuntime.queryInterface(XParameters.class, impl);
this.implPreparedBatchExecution = UnoRuntime.queryInterface(XPreparedBatchExecution.class, impl);
this.implWarningsSupplier = UnoRuntime.queryInterface(XWarningsSupplier.class, impl);
this.implMultipleResults = UnoRuntime.queryInterface(XMultipleResults.class, impl);
this.connection = connection;
}
// XComponentBase:
@Override
protected void postDisposing() {
try {
implCloseable.close();
} catch (SQLException sqlException) {
}
}
// XPreparedStatement:
public boolean execute() throws SQLException {
return impl.execute();
}
public XResultSet executeQuery() throws SQLException {
return new PostgresqlResultSet(impl.executeQuery(), this);
}
public int executeUpdate() throws SQLException {
return impl.executeUpdate();
}
public XConnection getConnection() throws SQLException {
return connection;
}
// XCloseable:
public void close() throws SQLException {
dispose();
}
// XPropertySet:
public void addPropertyChangeListener(String arg0, XPropertyChangeListener arg1) throws UnknownPropertyException, WrappedTargetException {
implPropertySet.addPropertyChangeListener(arg0, arg1);
}
public void addVetoableChangeListener(String arg0, XVetoableChangeListener arg1) throws UnknownPropertyException, WrappedTargetException {
implPropertySet.addVetoableChangeListener(arg0, arg1);
}
public XPropertySetInfo getPropertySetInfo() {
return implPropertySet.getPropertySetInfo();
}
public Object getPropertyValue(String arg0) throws UnknownPropertyException, WrappedTargetException {
return implPropertySet.getPropertyValue(arg0);
}
public void removePropertyChangeListener(String arg0, XPropertyChangeListener arg1) throws UnknownPropertyException, WrappedTargetException {
implPropertySet.removePropertyChangeListener(arg0, arg1);
}
public void removeVetoableChangeListener(String arg0, XVetoableChangeListener arg1) throws UnknownPropertyException, WrappedTargetException {
implPropertySet.removeVetoableChangeListener(arg0, arg1);
}
public void setPropertyValue(String arg0, Object arg1)
throws UnknownPropertyException, PropertyVetoException, IllegalArgumentException, WrappedTargetException {
implPropertySet.setPropertyValue(arg0, arg1);
}
// XCancellable:
public void cancel() {
implCancellable.cancel();
}
// XResultSetMetaDataSupplier:
public XResultSetMetaData getMetaData() throws SQLException {
return new PostgresqlResultSetMetaData(implResultSetMetaDataSupplier.getMetaData());
}
// XParameters:
public void clearParameters() throws SQLException {
implParameters.clearParameters();
}
public void setArray(int arg0, XArray arg1) throws SQLException {
implParameters.setArray(arg0, arg1);
}
public void setBinaryStream(int arg0, XInputStream arg1, int arg2) throws SQLException {
implParameters.setBinaryStream(arg0, arg1, arg2);
}
public void setBlob(int arg0, XBlob arg1) throws SQLException {
implParameters.setBlob(arg0, arg1);
}
public void setBoolean(int arg0, boolean arg1) throws SQLException {
implParameters.setBoolean(arg0, arg1);
}
public void setByte(int arg0, byte arg1) throws SQLException {
implParameters.setByte(arg0, arg1);
}
public void setBytes(int arg0, byte[] arg1) throws SQLException {
implParameters.setBytes(arg0, arg1);
}
public void setCharacterStream(int arg0, XInputStream arg1, int arg2) throws SQLException {
implParameters.setCharacterStream(arg0, arg1, arg2);
}
public void setClob(int arg0, XClob arg1) throws SQLException {
implParameters.setClob(arg0, arg1);
}
public void setDate(int arg0, Date arg1) throws SQLException {
implParameters.setDate(arg0, arg1);
}
public void setDouble(int arg0, double arg1) throws SQLException {
implParameters.setDouble(arg0, arg1);
}
public void setFloat(int arg0, float arg1) throws SQLException {
implParameters.setFloat(arg0, arg1);
}
public void setInt(int arg0, int arg1) throws SQLException {
implParameters.setInt(arg0, arg1);
}
public void setLong(int arg0, long arg1) throws SQLException {
implParameters.setLong(arg0, arg1);
}
public void setNull(int arg0, int arg1) throws SQLException {
implParameters.setNull(arg0, arg1);
}
public void setObject(int arg0, Object arg1) throws SQLException {
implParameters.setObject(arg0, arg1);
}
public void setObjectNull(int arg0, int arg1, String arg2) throws SQLException {
implParameters.setObjectNull(arg0, arg1, arg2);
}
public void setObjectWithInfo(int arg0, Object arg1, int arg2, int arg3) throws SQLException {
implParameters.setObjectWithInfo(arg0, arg1, arg2, arg3);
}
public void setRef(int arg0, XRef arg1) throws SQLException {
implParameters.setRef(arg0, arg1);
}
public void setShort(int arg0, short arg1) throws SQLException {
implParameters.setShort(arg0, arg1);
}
public void setString(int arg0, String arg1) throws SQLException {
implParameters.setString(arg0, arg1);
}
public void setTime(int arg0, Time arg1) throws SQLException {
implParameters.setTime(arg0, arg1);
}
public void setTimestamp(int arg0, DateTime arg1) throws SQLException {
implParameters.setTimestamp(arg0, arg1);
}
// XPreparedBatchExecution:
public void addBatch() throws SQLException {
implPreparedBatchExecution.addBatch();
}
public void clearBatch() throws SQLException {
implPreparedBatchExecution.clearBatch();
}
public int[] executeBatch() throws SQLException {
return implPreparedBatchExecution.executeBatch();
}
// XWarningsSupplier:
public void clearWarnings() throws SQLException {
implWarningsSupplier.clearWarnings();
}
public Object getWarnings() throws SQLException {
return implWarningsSupplier.getWarnings();
}
// XMultipleResults:
public boolean getMoreResults() throws SQLException {
return implMultipleResults.getMoreResults();
}
public XResultSet getResultSet() throws SQLException {
return new PostgresqlResultSet(implMultipleResults.getResultSet(), this);
}
public int getUpdateCount() throws SQLException {
return implMultipleResults.getUpdateCount();
}
}
| 3,698 |
627 | /* Copyright 2019 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Intel BASEBOARD-RVP USB MUX specific configuration */
#include "common.h"
#include "anx7440.h"
#include "bb_retimer.h"
#include "timer.h"
#include "usb_mux.h"
#ifdef CONFIG_USBC_RETIMER_INTEL_BB
struct usb_mux usbc0_retimer = {
.usb_port = TYPE_C_PORT_0,
.driver = &bb_usb_retimer,
.i2c_port = I2C_PORT0_BB_RETIMER,
.i2c_addr_flags = I2C_PORT0_BB_RETIMER_ADDR,
};
#ifdef HAS_TASK_PD_C1
struct usb_mux usbc1_retimer = {
.usb_port = TYPE_C_PORT_1,
.driver = &bb_usb_retimer,
.i2c_port = I2C_PORT1_BB_RETIMER,
.i2c_addr_flags = I2C_PORT1_BB_RETIMER_ADDR,
};
#endif /* HAS_TASK_PD_C1 */
#endif
/* USB muxes Configuration */
#ifdef CONFIG_USB_MUX_VIRTUAL
const struct usb_mux usb_muxes[] = {
[TYPE_C_PORT_0] = {
.usb_port = TYPE_C_PORT_0,
.driver = &virtual_usb_mux_driver,
.hpd_update = &virtual_hpd_update,
#ifdef CONFIG_USBC_RETIMER_INTEL_BB
.next_mux = &usbc0_retimer,
#endif
},
#ifdef HAS_TASK_PD_C1
[TYPE_C_PORT_1] = {
.usb_port = TYPE_C_PORT_1,
.driver = &virtual_usb_mux_driver,
.hpd_update = &virtual_hpd_update,
#ifdef CONFIG_USBC_RETIMER_INTEL_BB
.next_mux = &usbc1_retimer,
#endif
},
#endif /* HAS_TASK_PD_C1 */
};
BUILD_ASSERT(ARRAY_SIZE(usb_muxes) == CONFIG_USB_PD_PORT_MAX_COUNT);
#endif /* CONFIG_USB_MUX_VIRTUAL */
#ifdef CONFIG_USB_MUX_ANX7440
const struct usb_mux usb_muxes[] = {
[TYPE_C_PORT_0] = {
.usb_port = TYPE_C_PORT_0,
.i2c_port = I2C_PORT_USB_MUX,
.i2c_addr_flags = I2C_ADDR_USB_MUX0_FLAGS,
.driver = &anx7440_usb_mux_driver,
#ifdef CONFIG_USBC_RETIMER_INTEL_BB
.next_mux = &usbc0_retimer,
#endif
},
#ifdef HAS_TASK_PD_C1
[TYPE_C_PORT_1] = {
.usb_port = TYPE_C_PORT_1,
.i2c_port = I2C_PORT_USB_MUX,
.i2c_addr_flags = I2C_ADDR_USB_MUX1_FLAGS,
.driver = &anx7440_usb_mux_driver,
#ifdef CONFIG_USBC_RETIMER_INTEL_BB
.next_mux = &usbc1_retimer,
#endif
},
#endif /* HAS_TASK_PD_C1 */
};
BUILD_ASSERT(ARRAY_SIZE(usb_muxes) == CONFIG_USB_PD_PORT_MAX_COUNT);
#endif /* CONFIG_USB_MUX_ANX7440 */
| 1,050 |
5,079 | <reponame>kokosing/hue<filename>desktop/core/ext-py/nose-1.3.7/functional_tests/test_issue120/support/some_test.py
def some_test():
pass
| 58 |
3,680 | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
////////////////////////////////////////////////////////////////////////
// This file is generated by a script. Do not edit directly. Edit the
// wrapMatrix3.template.cpp file to make changes.
{% extends "wrapMatrix.template.cpp" %}
{% block customIncludes %}
#include "pxr/base/gf/quat{{ SCL[0] }}.h"
#include "pxr/base/gf/rotation.h"
{% endblock customIncludes %}
{% block customInit %}
.def(init< const GfRotation& >())
.def(init< const GfQuat{{ SCL[0] }}& >())
{% endblock customInit %}
{% block customDefs %}
.def("GetHandedness", &This::GetHandedness)
.def("IsLeftHanded", &This::IsLeftHanded)
.def("IsRightHanded", &This::IsRightHanded)
.def("Orthonormalize", &This::Orthonormalize,
(arg("issueWarning") = true))
.def("GetOrthonormalized", &This::GetOrthonormalized,
(arg("issueWarning") = true))
{% endblock customDefs %}
{% block customXformDefs %}
.def("SetScale", (This & (This::*)( const GfVec3{{ SCL[0] }} & ))&This::SetScale, return_self<>())
.def("SetRotate",
(This & (This::*)( const GfQuat{{ SCL[0] }} & )) &This::SetRotate,
return_self<>())
.def("SetRotate",
(This & (This::*)( const GfRotation & )) &This::SetRotate,
return_self<>())
.def("ExtractRotation", &This::ExtractRotation)
.def("SetScale", (This & (This::*)( {{ SCL }} ))&This::SetScale, return_self<>())
{% endblock customXformDefs %}
| 919 |
419 | <filename>thirdparty/win/miracl/miracl_osmt/source/mrgcd.c
/***************************************************************************
*
Copyright 2013 CertiVox UK Ltd. *
*
This file is part of CertiVox MIRACL Crypto SDK. *
*
The CertiVox MIRACL Crypto SDK provides developers with an *
extensive and efficient set of cryptographic functions. *
For further information about its features and functionalities please *
refer to http://www.certivox.com *
*
* The CertiVox MIRACL Crypto SDK is free software: you can *
redistribute it and/or modify it under the terms of the *
GNU Affero General Public License as published by the *
Free Software Foundation, either version 3 of the License, *
or (at your option) any later version. *
*
* The CertiVox MIRACL Crypto SDK 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 Affero General Public License for more details. *
*
* You should have received a copy of the GNU Affero General Public *
License along with CertiVox MIRACL Crypto SDK. *
If not, see <http://www.gnu.org/licenses/>. *
*
You can be released from the requirements of the license by purchasing *
a commercial license. Buying such a license is mandatory as soon as you *
develop commercial activities involving the CertiVox MIRACL Crypto SDK *
without disclosing the source code of your own applications, or shipping *
the CertiVox MIRACL Crypto SDK with a closed source product. *
*
***************************************************************************/
/*
* MIRACL Greatest Common Divisor module.
* mrgcd.c
*/
#include "miracl.h"
#ifdef MR_FP
#include <math.h>
#endif
int egcd(_MIPD_ big x,big y,big z)
{ /* greatest common divisor z=gcd(x,y) by Euclids *
* method using Lehmers algorithm for big numbers */
int q,r,a,b,c,d,n;
mr_small sr,m,sm;
mr_small u,v,lq,lr;
#ifdef MR_FP
mr_small dres;
#endif
big t;
#ifdef MR_OS_THREADS
miracl *mr_mip=get_mip();
#endif
if (mr_mip->ERNUM) return 0;
MR_IN(12)
copy(x,mr_mip->w1);
copy(y,mr_mip->w2);
insign(PLUS,mr_mip->w1);
insign(PLUS,mr_mip->w2);
a=b=c=d=0;
while (size(mr_mip->w2)!=0)
{
/* printf("a= %d b= %d c= %d d=%d\n",a,b,c,d); */
if (b==0)
{ /* update w1 and w2 */
divide(_MIPP_ mr_mip->w1,mr_mip->w2,mr_mip->w2);
t=mr_mip->w1,mr_mip->w1=mr_mip->w2,mr_mip->w2=t; /* swap(w1,w2) */
}
else
{
premult(_MIPP_ mr_mip->w1,c,z);
premult(_MIPP_ mr_mip->w1,a,mr_mip->w1);
premult(_MIPP_ mr_mip->w2,b,mr_mip->w0);
premult(_MIPP_ mr_mip->w2,d,mr_mip->w2);
add(_MIPP_ mr_mip->w1,mr_mip->w0,mr_mip->w1);
add(_MIPP_ mr_mip->w2,z,mr_mip->w2);
}
if (mr_mip->ERNUM || size(mr_mip->w2)==0) break;
n=(int)mr_mip->w1->len;
if (mr_mip->w2->len==1)
{ /* special case if mr_mip->w2 is now small */
sm=mr_mip->w2->w[0];
#ifdef MR_FP_ROUNDING
sr=mr_sdiv(_MIPP_ mr_mip->w1,sm,mr_invert(sm),mr_mip->w1);
#else
sr=mr_sdiv(_MIPP_ mr_mip->w1,sm,mr_mip->w1);
#endif
if (sr==0)
{
copy(mr_mip->w2,mr_mip->w1);
break;
}
zero(mr_mip->w1);
mr_mip->w1->len=1;
mr_mip->w1->w[0]=sr;
while ((sr=MR_REMAIN(mr_mip->w2->w[0],mr_mip->w1->w[0]))!=0)
mr_mip->w2->w[0]=mr_mip->w1->w[0],mr_mip->w1->w[0]=sr;
break;
}
a=1;
b=0;
c=0;
d=1;
m=mr_mip->w1->w[n-1]+1;
/* printf("m= %d\n",m); */
#ifndef MR_SIMPLE_BASE
if (mr_mip->base==0)
{
#endif
#ifndef MR_NOFULLWIDTH
if (m==0)
{
u=mr_mip->w1->w[n-1];
v=mr_mip->w2->w[n-1];
}
else
{
/* printf("w1[n-1]= %d w1[n-2]= %d\n", mr_mip->w1->w[n-1],mr_mip->w1->w[n-2]);
printf("w2[n-1]= %d w2[n-2]= %d\n", mr_mip->w2->w[n-1],mr_mip->w2->w[n-2]);*/
u=muldvm(mr_mip->w1->w[n-1],mr_mip->w1->w[n-2],m,&sr);
v=muldvm(mr_mip->w2->w[n-1],mr_mip->w2->w[n-2],m,&sr);
}
#endif
#ifndef MR_SIMPLE_BASE
}
else
{
u=muldiv(mr_mip->w1->w[n-1],mr_mip->base,mr_mip->w1->w[n-2],m,&sr);
v=muldiv(mr_mip->w2->w[n-1],mr_mip->base,mr_mip->w2->w[n-2],m,&sr);
}
#endif
/* printf("u= %d v= %d\n",u,v);*/
forever
{ /* work only with most significant piece */
if (((v+c)==0) || ((v+d)==0)) break;
lq=MR_DIV((u+a),(v+c));
if (lq!=MR_DIV((u+b),(v+d))) break;
if (lq>=(mr_small)(MR_TOOBIG/mr_abs(d))) break;
q=(int)lq;
r=a-q*c;
a=c;
c=r;
r=b-q*d;
b=d;
d=r;
lr=u-lq*v;
u=v;
v=lr;
}
}
copy(mr_mip->w1,z);
MR_OUT
return (size(mr_mip->w1));
}
| 3,810 |
1,236 | # Copyright (c) 2017 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
"""
@Author: zhangyuncong
@Date: 2016-03-07 19:58:12
@Last Modified by: zhangyuncong
@Last Modified time: 2016-03-08 10:33:05
"""
from bigflow import pcollection
from bigflow import ptable
def group_by_every_record(pvalue, **options):
"""
group by every record
"""
pipeline = pvalue.pipeline()
node = pvalue.node()
plan = node.plan()
scope = node.scope()
shuffle = plan.shuffle(scope, [node])
shuffle_node = shuffle.node(0).distribute_every()
from bigflow import serde
key_serde = serde.StrSerde()
return ptable.PTable(pcollection.PCollection(shuffle_node, pipeline), key_serde=key_serde)
| 420 |
Subsets and Splits