seq_id
string | text
string | repo_name
string | sub_path
string | file_name
string | file_ext
string | file_size_in_byte
int64 | program_lang
string | lang
string | doc_type
string | stars
int64 | dataset
string | pt
string |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
70262497323
|
// yue-lingshan.c
inherit NPC;
void create()
{
object ob;
set_name("ๅฒณ็ต็", ({ "yue lingshan", "yue", "lingshan" }) );
set("nickname", "ๅฐๅธๅฆน");
set("gender", "ๅฅณๆง" );
set("age", 17);
set("per", 29);
set("str", 16);
set("con", 24);
set("dex", 30);
set("int", 27);
set("attitude", "friendly");
set("max_qi",800);
set("max_jing",500);
set("neili", 1000);
set("max_neili", 1000);
set("jiali", 80);
set("combat_exp", 100000);
set("long", "ๅฒณ็ต็ๆฏๅๅฑฑๆดพๆ้จๅฒณไธ็พค็็ฌ็ๅฅณๅฟใ\n");
create_family("ๅๅฑฑๆดพ", 14, "ๅผๅญ");
set_skill("unarmed", 50);
set_skill("sword", 50);
set_skill("force", 60);
set_skill("parry", 50);
set_skill("dodge", 50);
set_skill("literate", 70);
set_skill("huashan-sword", 50);
set_skill("yunu-sword", 80);
set_skill("chongling-sword", 120);
set_skill("huashan-ken", 50);
set_skill("feiyan-huixiang", 50);
map_skill("sword", "yunu-sword");
map_skill("parry", "yunu-sword");
map_skill("force", "zixia-shengong");
map_skill("unarmed", "huashan-ken");
map_skill("dodge", "feiyan-huixiang");
setup();
if (clonep())
{
ob=new(WEAPON_DIR"treasure/greenwater-sword");
if ( ob->violate_unique())
{
destruct(ob);
ob=new(WEAPON_DIR"changjian");
}
ob->move(this_object());
ob->wield();
}
carry_object("/clone/cloth/cloth")->wear();
}
int accept_fight(object me)
{
command("say ๅฐๅฅณๅญๆไผๆฏไฝ ็ๅฏนๆ?");
return 0;
}
|
mudchina/xkx100
|
d/huashan/npc/yue-lingshan.c
|
yue-lingshan.c
|
c
| 1,743
|
c
|
en
|
code
| 22
|
github-code
|
19
|
15464659721
|
/* $OpenBSD: isa_machdep.c,v 1.31 2020/09/29 03:06:34 guenther Exp $ */
/* $NetBSD: isa_machdep.c,v 1.22 1997/06/12 23:57:32 thorpej Exp $ */
#define ISA_DMA_STATS
/*-
* Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
* NASA Ames Research Center.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
/*-
* Copyright (c) 1993, 1994, 1996, 1997
* Charles M. Hannum. All rights reserved.
* Copyright (c) 1991 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)isa.c 7.2 (Berkeley) 5/13/91
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/syslog.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <uvm/uvm_extern.h>
#include "ioapic.h"
#if NIOAPIC > 0
#include <machine/i82093var.h>
#include <machine/mpbiosvar.h>
#endif
#include <machine/intr.h>
#include <machine/i8259.h>
#include <dev/isa/isavar.h>
#include "isadma.h"
extern paddr_t avail_end;
#if NISADMA > 0
int _isa_bus_dmamap_create(bus_dma_tag_t, bus_size_t, int,
bus_size_t, bus_size_t, int, bus_dmamap_t *);
void _isa_bus_dmamap_destroy(bus_dma_tag_t, bus_dmamap_t);
int _isa_bus_dmamap_load(bus_dma_tag_t, bus_dmamap_t, void *,
bus_size_t, struct proc *, int);
int _isa_bus_dmamap_load_mbuf(bus_dma_tag_t, bus_dmamap_t,
struct mbuf *, int);
int _isa_bus_dmamap_load_uio(bus_dma_tag_t, bus_dmamap_t,
struct uio *, int);
int _isa_bus_dmamap_load_raw(bus_dma_tag_t, bus_dmamap_t,
bus_dma_segment_t *, int, bus_size_t, int);
void _isa_bus_dmamap_unload(bus_dma_tag_t, bus_dmamap_t);
void _isa_bus_dmamap_sync(bus_dma_tag_t, bus_dmamap_t,
bus_addr_t, bus_size_t, int);
int _isa_bus_dmamem_alloc(bus_dma_tag_t, bus_size_t, bus_size_t,
bus_size_t, bus_dma_segment_t *, int, int *, int);
int _isa_dma_check_buffer(void *, bus_size_t, int, bus_size_t,
struct proc *);
int _isa_dma_alloc_bouncebuf(bus_dma_tag_t, bus_dmamap_t,
bus_size_t, int);
void _isa_dma_free_bouncebuf(bus_dma_tag_t, bus_dmamap_t);
/*
* Entry points for ISA DMA. These are mostly wrappers around
* the generic functions that understand how to deal with bounce
* buffers, if necessary.
*/
struct bus_dma_tag isa_bus_dma_tag = {
NULL, /* _cookie */
_isa_bus_dmamap_create,
_isa_bus_dmamap_destroy,
_isa_bus_dmamap_load,
_isa_bus_dmamap_load_mbuf,
_isa_bus_dmamap_load_uio,
_isa_bus_dmamap_load_raw,
_isa_bus_dmamap_unload,
_isa_bus_dmamap_sync,
_isa_bus_dmamem_alloc,
_bus_dmamem_alloc_range,
_bus_dmamem_free,
_bus_dmamem_map,
_bus_dmamem_unmap,
_bus_dmamem_mmap,
};
#endif /* NISADMA > 0 */
int intrtype[ICU_LEN], intrlevel[ICU_LEN];
struct intrhand *intrhand[ICU_LEN];
#define LEGAL_IRQ(x) ((x) >= 0 && (x) < ICU_LEN && (x) != 2)
int
isa_intr_alloc(isa_chipset_tag_t ic, int mask, int type, int *irq)
{
int i, bestirq, count;
int tmp;
struct intrhand **p, *q;
if (type == IST_NONE)
panic("intr_alloc: bogus type");
bestirq = -1;
count = -1;
/* some interrupts should never be dynamically allocated */
mask &= 0xdef8;
/*
* XXX some interrupts will be used later (6 for fdc, 12 for pms).
* the right answer is to do "breadth-first" searching of devices.
*/
mask &= 0xefbf;
for (i = 0; i < ICU_LEN; i++) {
if (LEGAL_IRQ(i) == 0 || (mask & (1<<i)) == 0)
continue;
switch(intrtype[i]) {
case IST_NONE:
/*
* if nothing's using the irq, just return it
*/
*irq = i;
return (0);
case IST_EDGE:
case IST_LEVEL:
if (type != intrtype[i])
continue;
/*
* if the irq is shareable, count the number of other
* handlers, and if it's smaller than the last irq like
* this, remember it
*
* XXX We should probably also consider the
* interrupt level and stick IPL_TTY with other
* IPL_TTY, etc.
*/
for (p = &intrhand[i], tmp = 0; (q = *p) != NULL;
p = &q->ih_next, tmp++)
;
if ((bestirq == -1) || (count > tmp)) {
bestirq = i;
count = tmp;
}
break;
case IST_PULSE:
/* this just isn't shareable */
continue;
}
}
if (bestirq == -1)
return (1);
*irq = bestirq;
return (0);
}
/*
* Just check to see if an IRQ is available/can be shared.
* 0 = interrupt not available
* 1 = interrupt shareable
* 2 = interrupt all to ourself
*/
int
isa_intr_check(isa_chipset_tag_t ic, int irq, int type)
{
if (!LEGAL_IRQ(irq) || type == IST_NONE)
return (0);
switch (intrtype[irq]) {
case IST_NONE:
return (2);
break;
case IST_LEVEL:
if (type != intrtype[irq])
return (0);
return (1);
break;
case IST_EDGE:
case IST_PULSE:
if (type != IST_NONE)
return (0);
}
return (1);
}
/*
* Set up an interrupt handler to start being called.
* XXX PRONE TO RACE CONDITIONS, UGLY, 'INTERESTING' INSERTION ALGORITHM.
*/
void *
isa_intr_establish(isa_chipset_tag_t ic, int irq, int type, int level,
int (*ih_fun)(void *), void *ih_arg, char *ih_what)
{
struct pic *pic = &i8259_pic;
int pin = irq;
#if NIOAPIC > 0
struct mp_intr_map *mip;
if (mp_busses != NULL) {
if (mp_isa_bus == NULL)
panic("no isa bus");
for (mip = mp_isa_bus->mb_intrs; mip != NULL;
mip = mip->next) {
if (mip->bus_pin == pin) {
pin = APIC_IRQ_PIN(mip->ioapic_ih);
pic = &mip->ioapic->sc_pic;
break;
}
}
}
#endif
KASSERT(pic);
return intr_establish(irq, pic, pin, type, level, NULL, ih_fun,
ih_arg, ih_what);
}
/*
* Deregister an interrupt handler.
*/
void
isa_intr_disestablish(isa_chipset_tag_t ic, void *arg)
{
intr_disestablish(arg);
return;
}
void
isa_attach_hook(struct device *parent, struct device *self,
struct isabus_attach_args *iba)
{
extern int isa_has_been_seen;
/*
* Notify others that might need to know that the ISA bus
* has now been attached.
*/
if (isa_has_been_seen)
panic("isaattach: ISA bus already seen!");
isa_has_been_seen = 1;
}
#if NISADMA > 0
/**********************************************************************
* bus.h dma interface entry points
**********************************************************************/
#ifdef ISA_DMA_STATS
#define STAT_INCR(v) (v)++
#define STAT_DECR(v) do { \
if ((v) == 0) \
printf("%s:%d -- Already 0!\n", __FILE__, __LINE__); \
else \
(v)--; \
} while (0)
u_long isa_dma_stats_loads;
u_long isa_dma_stats_bounces;
u_long isa_dma_stats_nbouncebufs;
#else
#define STAT_INCR(v)
#define STAT_DECR(v)
#endif
/*
* Create an ISA DMA map.
*/
int
_isa_bus_dmamap_create(bus_dma_tag_t t, bus_size_t size, int nsegments,
bus_size_t maxsegsz, bus_size_t boundary, int flags, bus_dmamap_t *dmamp)
{
struct isa_dma_cookie *cookie;
bus_dmamap_t map;
int error, cookieflags;
void *cookiestore;
size_t cookiesize;
/* Call common function to create the basic map. */
error = _bus_dmamap_create(t, size, nsegments, maxsegsz, boundary,
flags, dmamp);
if (error)
return (error);
map = *dmamp;
map->_dm_cookie = NULL;
cookiesize = sizeof(struct isa_dma_cookie);
/*
* ISA only has 24-bits of address space. This means
* we can't DMA to pages over 16M. In order to DMA to
* arbitrary buffers, we use "bounce buffers" - pages
* in memory below the 16M boundary. On DMA reads,
* DMA happens to the bounce buffers, and is copied into
* the caller's buffer. On writes, data is copied into
* the bounce buffer, and the DMA happens from those
* pages. To software using the DMA mapping interface,
* this looks simply like a data cache.
*
* If we have more than 16M of RAM in the system, we may
* need bounce buffers. We check and remember that here.
*
* There are exceptions, however. VLB devices can do
* 32-bit DMA, and indicate that here.
*
* ...or, there is an opposite case. The most segments
* a transfer will require is (maxxfer / NBPG) + 1. If
* the caller can't handle that many segments (e.g. the
* ISA DMA controller), we may have to bounce it as well.
*/
cookieflags = 0;
if ((avail_end > ISA_DMA_BOUNCE_THRESHOLD &&
(flags & ISABUS_DMA_32BIT) == 0) ||
((map->_dm_size / NBPG) + 1) > map->_dm_segcnt) {
cookieflags |= ID_MIGHT_NEED_BOUNCE;
cookiesize += (sizeof(bus_dma_segment_t) * map->_dm_segcnt);
}
/*
* Allocate our cookie.
*/
if ((cookiestore = malloc(cookiesize, M_DEVBUF,
(flags & BUS_DMA_NOWAIT) ?
(M_NOWAIT|M_ZERO) : (M_WAITOK|M_ZERO))) == NULL) {
error = ENOMEM;
goto out;
}
cookie = (struct isa_dma_cookie *)cookiestore;
cookie->id_flags = cookieflags;
map->_dm_cookie = cookie;
if (cookieflags & ID_MIGHT_NEED_BOUNCE) {
/*
* Allocate the bounce pages now if the caller
* wishes us to do so.
*/
if ((flags & BUS_DMA_ALLOCNOW) == 0)
goto out;
error = _isa_dma_alloc_bouncebuf(t, map, size, flags);
}
out:
if (error) {
free(map->_dm_cookie, M_DEVBUF, cookiesize);
_bus_dmamap_destroy(t, map);
}
return (error);
}
/*
* Destroy an ISA DMA map.
*/
void
_isa_bus_dmamap_destroy(bus_dma_tag_t t, bus_dmamap_t map)
{
struct isa_dma_cookie *cookie = map->_dm_cookie;
/*
* Free any bounce pages this map might hold.
*/
if (cookie->id_flags & ID_HAS_BOUNCE)
_isa_dma_free_bouncebuf(t, map);
free(cookie, M_DEVBUF, 0);
_bus_dmamap_destroy(t, map);
}
/*
* Load an ISA DMA map with a linear buffer.
*/
int
_isa_bus_dmamap_load(bus_dma_tag_t t, bus_dmamap_t map, void *buf,
bus_size_t buflen, struct proc *p, int flags)
{
struct isa_dma_cookie *cookie = map->_dm_cookie;
int error;
STAT_INCR(isa_dma_stats_loads);
/*
* Check to see if we might need to bounce the transfer.
*/
if (cookie->id_flags & ID_MIGHT_NEED_BOUNCE) {
/*
* Check if all pages are below the bounce
* threshold. If they are, don't bother bouncing.
*/
if (_isa_dma_check_buffer(buf, buflen,
map->_dm_segcnt, map->_dm_boundary, p) == 0)
return (_bus_dmamap_load(t, map, buf, buflen,
p, flags));
STAT_INCR(isa_dma_stats_bounces);
/*
* Allocate bounce pages, if necessary.
*/
if ((cookie->id_flags & ID_HAS_BOUNCE) == 0) {
error = _isa_dma_alloc_bouncebuf(t, map, buflen,
flags);
if (error)
return (error);
}
/*
* Cache a pointer to the caller's buffer and
* load the DMA map with the bounce buffer.
*/
cookie->id_origbuf = buf;
cookie->id_origbuflen = buflen;
error = _bus_dmamap_load(t, map, cookie->id_bouncebuf,
buflen, p, flags);
if (error) {
/*
* Free the bounce pages, unless our resources
* are reserved for our exclusive use.
*/
if ((map->_dm_flags & BUS_DMA_ALLOCNOW) == 0)
_isa_dma_free_bouncebuf(t, map);
}
/* ...so _isa_bus_dmamap_sync() knows we're bouncing */
cookie->id_flags |= ID_IS_BOUNCING;
} else {
/*
* Just use the generic load function.
*/
error = _bus_dmamap_load(t, map, buf, buflen, p, flags);
}
return (error);
}
/*
* Like _isa_bus_dmamap_load(), but for mbufs.
*/
int
_isa_bus_dmamap_load_mbuf(bus_dma_tag_t t, bus_dmamap_t map, struct mbuf *m,
int flags)
{
panic("_isa_bus_dmamap_load_mbuf: not implemented");
}
/*
* Like _isa_bus_dmamap_load(), but for uios.
*/
int
_isa_bus_dmamap_load_uio(bus_dma_tag_t t, bus_dmamap_t map, struct uio *uio,
int flags)
{
panic("_isa_bus_dmamap_load_uio: not implemented");
}
/*
* Like _isa_bus_dmamap_load(), but for raw memory allocated with
* bus_dmamem_alloc().
*/
int
_isa_bus_dmamap_load_raw(bus_dma_tag_t t, bus_dmamap_t map,
bus_dma_segment_t *segs, int nsegs, bus_size_t size, int flags)
{
panic("_isa_bus_dmamap_load_raw: not implemented");
}
/*
* Unload an ISA DMA map.
*/
void
_isa_bus_dmamap_unload(bus_dma_tag_t t, bus_dmamap_t map)
{
struct isa_dma_cookie *cookie = map->_dm_cookie;
/*
* If we have bounce pages, free them, unless they're
* reserved for our exclusive use.
*/
if ((cookie->id_flags & ID_HAS_BOUNCE) &&
(map->_dm_flags & BUS_DMA_ALLOCNOW) == 0)
_isa_dma_free_bouncebuf(t, map);
cookie->id_flags &= ~ID_IS_BOUNCING;
/*
* Do the generic bits of the unload.
*/
_bus_dmamap_unload(t, map);
}
/*
* Synchronize an ISA DMA map.
*/
void
_isa_bus_dmamap_sync(bus_dma_tag_t t, bus_dmamap_t map, bus_addr_t offset,
bus_size_t len, int op)
{
struct isa_dma_cookie *cookie = map->_dm_cookie;
#ifdef DEBUG
if ((op & (BUS_DMASYNC_PREWRITE|BUS_DMASYNC_POSTREAD)) != 0) {
if (offset >= map->dm_mapsize)
panic("_isa_bus_dmamap_sync: bad offset");
if (len == 0 || (offset + len) > map->dm_mapsize)
panic("_isa_bus_dmamap_sync: bad length");
}
#endif
#ifdef DIAGNOSTIC
if ((op & (BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE)) != 0 &&
(op & (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE)) != 0)
panic("_isa_bus_dmamap_sync: mix PRE and POST");
#endif /* DIAGNOSTIC */
/* PREREAD and POSTWRITE are no-ops */
if (op & BUS_DMASYNC_PREWRITE) {
/*
* If we're bouncing this transfer, copy the
* caller's buffer to the bounce buffer.
*/
if (cookie->id_flags & ID_IS_BOUNCING)
memcpy(cookie->id_bouncebuf + offset,
cookie->id_origbuf + offset, len);
}
_bus_dmamap_sync(t, map, offset, len, op);
if (op & BUS_DMASYNC_POSTREAD) {
/*
* If we're bouncing this transfer, copy the
* bounce buffer to the caller's buffer.
*/
if (cookie->id_flags & ID_IS_BOUNCING)
memcpy(cookie->id_origbuf + offset,
cookie->id_bouncebuf + offset, len);
}
}
/*
* Allocate memory safe for ISA DMA.
*/
int
_isa_bus_dmamem_alloc(bus_dma_tag_t t, bus_size_t size, bus_size_t alignment,
bus_size_t boundary, bus_dma_segment_t *segs, int nsegs, int *rsegs,
int flags)
{
int error;
/* Try in ISA addressable region first */
error = _bus_dmamem_alloc_range(t, size, alignment, boundary,
segs, nsegs, rsegs, flags, 0, ISA_DMA_BOUNCE_THRESHOLD);
if (!error)
return (error);
/* Otherwise try anywhere (we'll bounce later) */
error = _bus_dmamem_alloc_range(t, size, alignment, boundary,
segs, nsegs, rsegs, flags, (bus_addr_t)0, (bus_addr_t)-1);
return (error);
}
/**********************************************************************
* ISA DMA utility functions
**********************************************************************/
/*
* Return 0 if all pages in the passed buffer lie within the DMA'able
* range RAM.
*/
int
_isa_dma_check_buffer(void *buf, bus_size_t buflen, int segcnt,
bus_size_t boundary, struct proc *p)
{
vaddr_t vaddr = (vaddr_t)buf;
vaddr_t endva;
paddr_t pa, lastpa;
u_long pagemask = ~(boundary - 1);
pmap_t pmap;
int nsegs;
endva = round_page(vaddr + buflen);
nsegs = 1;
lastpa = 0;
if (p != NULL)
pmap = p->p_vmspace->vm_map.pmap;
else
pmap = pmap_kernel();
for (; vaddr < endva; vaddr += NBPG) {
/*
* Get physical address for this segment.
*/
pmap_extract(pmap, (vaddr_t)vaddr, &pa);
pa = trunc_page(pa);
/*
* Is it below the DMA'able threshold?
*/
if (pa > ISA_DMA_BOUNCE_THRESHOLD)
return (EINVAL);
if (lastpa) {
/*
* Check excessive segment count.
*/
if (lastpa + NBPG != pa) {
if (++nsegs > segcnt)
return (EFBIG);
}
/*
* Check boundary restriction.
*/
if (boundary) {
if ((lastpa ^ pa) & pagemask)
return (EINVAL);
}
}
lastpa = pa;
}
return (0);
}
int
_isa_dma_alloc_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map, bus_size_t size,
int flags)
{
struct isa_dma_cookie *cookie = map->_dm_cookie;
int error = 0;
cookie->id_bouncebuflen = round_page(size);
error = _bus_dmamem_alloc_range(t, cookie->id_bouncebuflen,
NBPG, map->_dm_boundary, cookie->id_bouncesegs,
map->_dm_segcnt, &cookie->id_nbouncesegs, flags,
0, ISA_DMA_BOUNCE_THRESHOLD);
if (error)
goto out;
error = _bus_dmamem_map(t, cookie->id_bouncesegs,
cookie->id_nbouncesegs, cookie->id_bouncebuflen,
(caddr_t *)&cookie->id_bouncebuf, flags);
out:
if (error) {
_bus_dmamem_free(t, cookie->id_bouncesegs,
cookie->id_nbouncesegs);
cookie->id_bouncebuflen = 0;
cookie->id_nbouncesegs = 0;
} else {
cookie->id_flags |= ID_HAS_BOUNCE;
STAT_INCR(isa_dma_stats_nbouncebufs);
}
return (error);
}
void
_isa_dma_free_bouncebuf(bus_dma_tag_t t, bus_dmamap_t map)
{
struct isa_dma_cookie *cookie = map->_dm_cookie;
STAT_DECR(isa_dma_stats_nbouncebufs);
_bus_dmamem_unmap(t, cookie->id_bouncebuf,
cookie->id_bouncebuflen);
_bus_dmamem_free(t, cookie->id_bouncesegs,
cookie->id_nbouncesegs);
cookie->id_bouncebuflen = 0;
cookie->id_nbouncesegs = 0;
cookie->id_flags &= ~ID_HAS_BOUNCE;
}
#endif /* NISADMA > 0 */
|
openbsd/src
|
sys/arch/amd64/isa/isa_machdep.c
|
isa_machdep.c
|
c
| 19,418
|
c
|
en
|
code
| 2,915
|
github-code
|
19
|
41412867699
|
#include "ipclib.h"
#ifndef O_RDONLY
# include <fcntl.h>
#endif
#ifndef O_TRUNC
# define O_TRUNC 0
#endif
#ifndef O_CREAT
# define O_CREAT 0
#endif
#ifndef O_APPEND
# define O_APPEND 0
#endif
#ifdef __GNUG__
#define zapeof(x) ((x)&0377)
#endif
static String // includes trailing slash
dirname_plus(const String& arg)
{
int base = arg.strrchr('/') + 1;
if (base == 0) return "./";
else return arg.chunk(0, base);
}
extern int errno ;
inline void save_errno(int& orig)
{
orig = ::errno ;
::errno = 0 ;
}
inline int restore_errno(int& orig)
{
if ( ::errno == 0 ) ::errno = orig ;
return EOF ;
}
/*
* Open a ipc connection.
* Return: NULL if failure
* this if success
*/
ipcbuf* ipcbuf::open (const String& path, const char* /* param */)
{
int errno_orig ;
save_errno(errno_orig) ;
String name = ipc_fix_name_ATTLC(path);
char* p = new char[name.length()+10]; name.dump(p);
key_t key = ftok(p, ipcstream::ftok_id ? ipcstream::ftok_id : 'z');
delete p;
if (key == key_t(-1)) return 0;
Monitor* sema1 = new Monitor(key,1);
sema1->Open();
sema1->P();
Monitor* sema2 = new Monitor(key+1,1);
sema2->Open();
sema2->V();
int fd;
if ((fd = ::open(String(name+'a'), O_WRONLY)) < 0) {
sema1->V();
delete sema1;
delete sema2;
return 0;
}
if ((p = cuserid(0)) == 0) {
::close(fd);
sema1->V();
delete sema1;
delete sema2;
return 0;
}
errno = 0;
{// note no if
ofstream ofs(fd);
ofs << p << " " << getuid() << " " << getgid() << "\n";
ofs.close();
}
::close(fd);
if ((fd = ::open(String(name+'b'), O_RDONLY)) < 0) {
sema1->V();
delete sema1;
delete sema2;
return 0;
}
{// note no if
ifstream ifs(fd);
String ans;
ifs >> ans;
if (ans == "Accept") {
String temp;
String dir = dirname_plus(name);
ifs >> temp;
String in_pipe = dir + temp;
ifs >> temp;
String out_pipe = dir + temp;
out_xfd = ::open(out_pipe, O_WRONLY);
in_xfd = ::open(in_pipe, O_RDONLY);
if (in_xfd >= 0 && out_xfd >= 0)
opened = 1;
} else if (ans == "Reject") {
ifs >> remote_errno;
remote_reason = sgets(ifs);
} else {
remote_errno = -1;
remote_reason = "Lost synch";
}
ifs.close();
}
::close(fd);
sema1->V();
delete sema1;
delete sema2;
return opened ? this : 0;
}
ipcbuf* ipcbuf::open (const char* path, const char* param)
{
return open(String(path), param);
}
/*
* Empty an output buffer.
* Returns: EOF on error
* 0 on success
*/
int ipcbuf::overflow(int c)
{
int errno_orig ;
save_errno(errno_orig) ;
if ( !opened ) return restore_errno(errno_orig) ;
if ( out_allocate() == EOF ) return restore_errno(errno_orig) ;
register char* p = aux_base() ;
register int count = pptr() - p;
// pptr()==NULL does not imply p < pptr(), so we need separate
// test.
if ( pptr() && count > 0 ) {
if (count != write(out_xfd,p,count))
return restore_errno(errno_orig) ;
}
setp(pbase(),epptr()) ;
// cerr << "OverF:abase=" << (int)aux_base() << " pptr=" << (int)pptr() << endl;
if ( c == EOF ) /* don't do anything */ ;
else if ( pbase() == epptr() ) { // unbuffered
char ch = c;
// cerr << "OverF:pbase=" << (int)pbase() << " epptr=" << (int)epptr() << endl;
// cerr << "OverF:xfdout=" << out_xfd << " errno=" << errno_orig << endl;
if ( write(out_xfd,&ch,1)!=1 ) return restore_errno(errno_orig) ;
}
else {
sputc(c) ;
}
restore_errno(errno_orig) ;
return zapeof(c) ;
}
/*
* Fill an input buffer.
* Returns: EOF on error or end of input
* next character on success
*/
int ipcbuf::underflow()
{
int count;
if ( !opened ) return EOF ;
if ( in_allocate() == EOF ) return EOF ;
int orig_errno ;
save_errno(orig_errno) ;
if ( in_unbuffered() ) {
#ifdef __hpux
count = read(in_xfd,(void*)&lahead[0],1) ;
#else
count = read(in_xfd,&lahead[0],1) ;
#endif
setg(&lahead[0],&lahead[0],&lahead[count]) ;
if ( count <= 0 ) return EOF ;
}
else {
register int rdsize ;
if ( blen() > 2*sizeof(long) ) {
/* gptr must be set greater than base to
* guarantee at least 1 char of pushback.
* putting it farther will tend in many common
* cases to keep things aligned.
*/
in_start = base()+sizeof(long) ;
rdsize = blen()-sizeof(long) ;
} else {
in_start = base()+1 ;
rdsize = blen()-1 ;
}
#ifdef __hpux
count = read(in_xfd,(void*)in_start,rdsize) ;
#else
count = read(in_xfd,in_start,rdsize) ;
#endif
while ( count<=0 && ::errno==EINTR ) {
/*
* Signal caught and returned before any data
* transfered.
*/
::errno = 0 ;
#ifdef __hpux
count = read(in_xfd,(void*)in_start,rdsize) ;
#else
count = read(in_xfd,in_start,rdsize) ;
#endif
}
if ( count <= 0 ) {
setg(0,0,0) ;
return restore_errno(orig_errno) ;
}
setg(base(),in_start,in_start+count) ;
}
restore_errno(orig_errno) ;
return zapeof(*gptr());
}
int ipcbuf::close()
{
int f = in_xfd ;
int g = out_xfd ;
overflow();
setg(0,0,0) ;
setp(0,0) ;
opened = 0 ;
in_xfd = out_xfd = -1 ;
int orig_errno ;
save_errno(orig_errno) ;
int ok = ::close(f) | ::close(g);
restore_errno(orig_errno) ;
return ok ;
}
int ipcbuf::sync()
{
return overflow() ;
}
ipcbuf::ipcbuf()
: in_xfd(-1), out_xfd(-1), opened(0), x_get_unbuf(0), x_put_unbuf(0),
aux_x_base(0), aux_alloc(0), owner(0)
{
}
ipcbuf::ipcbuf(const char* path, const char* param)
: in_xfd(-1), out_xfd(-1), opened(0), x_get_unbuf(0), x_put_unbuf(0),
aux_x_base(0), aux_alloc(0), owner(0)
{
open(String(path), param);
}
ipcbuf::ipcbuf(const String& path, const char* param)
: in_xfd(-1), out_xfd(-1), opened(0), x_get_unbuf(0), x_put_unbuf(0),
aux_x_base(0), aux_alloc(0), owner(0)
{
open(path, param);
}
ipcbuf::ipcbuf(int in_fd, int out_fd)
: in_xfd(in_fd), out_xfd(out_fd), opened(1), x_get_unbuf(0),
x_put_unbuf(0), aux_x_base(0), aux_alloc(0), owner(0)
{
}
ipcbuf::ipcbuf(String in_pipe, String out_pipe)
: opened(1), x_get_unbuf(0),
x_put_unbuf(0), aux_x_base(0), aux_alloc(0), owner(1),
in_pip(in_pipe), out_pip(out_pipe)
{
if ((in_xfd = ::open(in_pipe, O_RDONLY)) < 0 ||
(out_xfd = ::open(out_pipe, O_WRONLY)) < 0)
opened = 0;
}
ipcbuf::~ipcbuf() {
close() ;
if (owner) {
unlink(in_pip);
unlink(out_pip);
}
}
streambuf* ipcbuf::setbuf(char*, int)
{
return 0;
}
streambuf* ipcbuf::set_in_buf(char* p , int len)
{
if ( base() ) return 0 ;
if ( len <= 0 || p == 0 ) {
// make it unbuffered
setb(0,0,0) ;
setg(0,0,0) ;
in_unbuffered(1) ;
}
else {
setb(p,p+len,0) ;
setg(p,p,p) ;
in_unbuffered(0) ;
}
return this;
}
streambuf* ipcbuf::set_out_buf(char* p , int len)
{
if ( aux_base() ) return 0 ;
if ( len <= 0 || p == 0 ) {
// make it unbuffered
aux_setb(0,0,0) ;
setp(0,0) ;
out_unbuffered(1) ;
}
else {
aux_setb(p,p+len,0) ;
setp(p,p+len) ;
out_unbuffered(0) ;
}
return this;
}
/*
Allocate some space for the buffer.
Returns: EOF on error
0 on success
*/
int ipcbuf::do_out_allocate()
{
char *buf = new char[STREAMBUFSIZE] ;
if ( !buf ) return EOF ;
aux_setb(buf,buf+STREAMBUFSIZE,1) ;
return 0;
}
|
seyko2/cfront-3
|
libSC/ipc/ipcbuf.c
|
ipcbuf.c
|
c
| 7,102
|
c
|
en
|
code
| 68
|
github-code
|
19
|
29369417670
|
#ifndef _KDP_H
#define _KDP_H
#ifndef __ASSEMBLY__
#ifndef LINKER_SCRIPT
#include <linux/rkp.h>
#ifdef CONFIG_KDP_NS
#include <linux/mount.h>
#endif
/* uH_RKP Command ID */
/*
Add KDP call IDs
*/
/***************** KDP_CRED *****************/
#define CRED_JAR_RO "cred_jar_ro"
#define TSEC_JAR "tsec_jar"
#define VFSMNT_JAR "vfsmnt_cache"
#define rocred_uc_read(x) atomic_read(x->use_cnt)
#define rocred_uc_inc(x) atomic_inc(x->use_cnt)
#define rocred_uc_dec_and_test(x) atomic_dec_and_test(x->use_cnt)
#define rocred_uc_inc_not_zero(x) atomic_inc_not_zero(x->use_cnt)
#define rocred_uc_set(x,v) atomic_set(x->use_cnt,v)
extern int rkp_cred_enable;
extern char __rkp_ro_start[], __rkp_ro_end[];
extern struct cred init_cred;
extern struct task_security_struct init_sec;
extern int security_integrity_current(void);
struct ro_rcu_head {
/* RCU deletion */
union {
int non_rcu; /* Can we skip RCU deletion? */
struct rcu_head rcu; /* RCU deletion hook */
};
void *bp_cred;
};
struct kdp_usecnt {
atomic_t kdp_use_cnt;
struct ro_rcu_head kdp_rcu_head;
};
#define get_rocred_rcu(cred) ((struct ro_rcu_head *)((atomic_t *)cred->use_cnt + 1))
#define get_usecnt_rcu(use_cnt) ((struct ro_rcu_head *)((atomic_t *)use_cnt + 1))
#ifdef CONFIG_KDP_NS
void rkp_reset_mnt_flags(struct vfsmount *mnt,int flags);
#endif
enum __KDP_CMD_ID{
RKP_KDP_X40 = 0x40,
RKP_KDP_X41 = 0x41,
RKP_KDP_X42 = 0x42,
RKP_KDP_X43 = 0x43,
RKP_KDP_X44 = 0x44,
RKP_KDP_X45 = 0x45,
RKP_KDP_X46 = 0x46,
RKP_KDP_X47 = 0x47,
RKP_KDP_X48 = 0x48,
RKP_KDP_X49 = 0x49,
RKP_KDP_X4A = 0x4A,
RKP_KDP_X4B = 0x4B,
RKP_KDP_X4C = 0x4C,
RKP_KDP_X4D = 0x4D,
RKP_KDP_X4E = 0x4E,
RKP_KDP_X4F = 0x4F,
RKP_KDP_X50 = 0x50,
RKP_KDP_X51 = 0x51,
RKP_KDP_X52 = 0x52,
RKP_KDP_X53 = 0x53,
RKP_KDP_X54 = 0x54,
RKP_KDP_X55 = 0x55,
RKP_KDP_X56 = 0x56,
RKP_KDP_X60 = 0x60,
};
enum __KDP_CRED_TYPE {
KDP_CRED_JAR = 1,
KDP_TSEC_JAR = 2,
KDP_VFSMNT_JAR = 3,
};
typedef struct kdp_init_struct {
#ifdef CONFIG_FASTUH_RKP
u64 _srodata;
u64 _erodata;
#endif
u32 credSize;
u32 sp_size;
u32 pgd_mm;
u32 uid_cred;
u32 euid_cred;
u32 gid_cred;
u32 egid_cred;
u32 bp_pgd_cred;
u32 bp_task_cred;
u32 type_cred;
u32 security_cred;
u32 usage_cred;
u32 cred_task;
u32 mm_task;
u32 pid_task;
u32 rp_task;
u32 comm_task;
u32 bp_cred_secptr;
u32 task_threadinfo;
u64 verifiedbootstate;
struct {
u64 selinux_enforcing_va;
u64 ss_initialized_va;
}selinux;
} kdp_init_t;
#ifndef CONFIG_FASTUH_RKP
/*Check whether the address belong to Cred Area*/
static inline u8 rkp_ro_page(unsigned long addr)
{
if(!rkp_cred_enable)
return (u8)0;
if((addr == ((unsigned long)&init_cred)) ||
(addr == ((unsigned long)&init_sec)))
return (u8)1;
else
return rkp_is_pg_protected(addr);
}
#else
extern u8 rkp_ro_page(unsigned long addr);
#endif
/***************** KDP_NS *****************/
#ifdef CONFIG_KDP_NS
typedef struct ns_param {
u32 ns_buff_size;
u32 ns_size;
u32 bp_offset;
u32 sb_offset;
u32 flag_offset;
u32 data_offset;
}ns_param_t;
#define rkp_ns_fill_params(nsparam,buff_size,size,bp,sb,flag,data) \
do { \
nsparam.ns_buff_size = (u64)buff_size; \
nsparam.ns_size = (u64)size; \
nsparam.bp_offset = (u64)bp; \
nsparam.sb_offset = (u64)sb; \
nsparam.flag_offset = (u64)flag; \
nsparam.data_offset = (u64)data; \
} while(0)
#endif
/***************** KDP_DMAP *****************/
#ifdef CONFIG_KDP_DMAP
static inline void dmap_prot(u64 addr,u64 order,u64 val)
{
if(rkp_cred_enable)
uh_call(UH_APP_KDP, RKP_KDP_X4A, order, val, 0, 0);
}
#endif
#endif // LINKER_SCRIPT
#endif //__ASSEMBLY__
#endif //_KDP_H
|
pascua28/android_kernel_samsung_s20fe
|
include/linux/kdp.h
|
kdp.h
|
h
| 3,632
|
c
|
en
|
code
| 11
|
github-code
|
19
|
27006502928
|
#pragma once
#ifndef PT_D3D9_RENDERING_VIEW_VARIABLES_H
#define PT_D3D9_RENDERING_VIEW_VARIABLES_H
#include "simple_variable_owner.h"
#include "matrix4x4f_setters.h"
#include "vector3f_setters.h"
#include "time_setter.h"
#include "animatable_setter.h"
#include "pt/d3d9/constant.h"
#include "pt/math/plane.h"
namespace pt { namespace d3d9 { namespace rendering {
class view_variables : public simple_variable_owner
{
public:
view_variables(
transformation const& transformation,
projection_matrix& projection,
std::vector<animatable_value<math::plane>> const& clipping_planes)
: m_transformation(transformation)
, m_projection(projection)
, m_clipping_planes(clipping_planes)
{
}
protected: // interface required by simple_variable_owner
std::unique_ptr<constant_setter> on_create_constant(
constant const& constant) const
{
if (constant.name() == "projection")
{
return std::make_unique<projection_setter>(m_projection);
}
else if (constant.name() == "time")
{
return std::make_unique<time_setter>();
}
else if (constant.name() == "world_to_view_clip")
{
return std::make_unique<world_to_view_clip_setter>(m_transformation, m_projection);
}
else if (constant.name() == "world_to_view")
{
return std::make_unique<world_to_view_setter>(m_transformation);
}
else if (constant.name() == "view_in_world")
{
return std::make_unique<view_in_world_setter>(m_transformation);
}
else if (constant.name() == "view_to_world")
{
return std::make_unique<local_to_world_setter>(m_transformation);
}
else if (constant.name() == "clip_planes_in_world")
{
// TODO: Animatable clipping planes
std::vector<pt::vector4f> values;
for (auto const& x : m_clipping_planes)
{
auto plane = x.value_at(0);
values.push_back(plane.as_vector());
}
// Add clipping planes at infinity.
for (size_t i = m_clipping_planes.size(); i < 4; ++i)
{
auto plane = math::make_plane(vector3f(0, -1000000.0f, 0), vector3f(0, 1, 0));
values.push_back(plane.as_vector());
}
return std::make_unique<basic_array_setter<vector4f>>(values);
}
//else if (constant.name() == "world_to_view")
//{
// return std::make_unique<world_to_local_setter>(m_transformation != nullptr ? m_transformation : m_transformer->shared_transformation());
//}
return nullptr;
}
private: // data members
transformation const& m_transformation;
projection_matrix& m_projection;
std::vector<animatable_value<math::plane>> m_clipping_planes;
};
/// frustum light projection for HLSL shader constant.
class view_from_light_variables : public simple_variable_owner
{
public:
view_from_light_variables(
transformation const& transformation,
projection_matrix& projection)
: m_transformation(transformation)
, m_projection(projection)
{
}
protected: // interface required by simple_variable_owner
std::unique_ptr<constant_setter> on_create_constant(
constant const& constant) const
{
if (constant.name() == "light_projection")
{
return std::make_unique<projection_setter>(m_projection);
}
else if (constant.name() == "world_to_light_clip")
{
return std::make_unique<world_to_view_clip_setter>(m_transformation, m_projection);
}
return nullptr;
}
private: // data members
transformation const& m_transformation;
projection_matrix& m_projection;
};
}}} // namespace pt::d3d9::rendering
#endif
|
Codarki/Pyrotech_2016
|
democodebase/pt/d3d9/rendering/view_variables.h
|
view_variables.h
|
h
| 3,920
|
c
|
en
|
code
| 0
|
github-code
|
19
|
24102728634
|
/******************************************************************************
*
* Cisco Systems, Inc.
*
* Copyright (c) 2008 by Cisco Systems, Inc.
* All rights reserved.
*
******************************************************************************
*
* File:
*
* Description: Kernel module basic types.
*
* Documents:
*
*****************************************************************************/
#ifndef __VAM_TYPES_H__
#define __VAM_TYPES_H__
#include <linux/module.h>
#include <asm/byteorder.h>
#include <linux/fcntl.h>
#include <linux/random.h>
#include <linux/in.h>
#include <linux/ctype.h>
#include <linux/un.h>
typedef uint8_t boolean;
typedef uint16_t in_port_t;
typedef uint32_t in_addr_t;
#ifndef USHRT_MAX
#define USHRT_MAX 0xFFFF
#endif
#ifndef RAND_MAX
#define RAND_MAX 0xFFFFFFFF
#endif
#ifndef INET_ADDRSTRLEN
#define INET_ADDRSTRLEN 32
#endif
# ifndef SUCCESS
# define SUCCESS 0
# endif // SUCCESS
# ifndef FAILURE
# define FAILURE -1
# endif // FAILURE
#define TRUE 1
#define FALSE 0
#define VAM_PACKED __attribute__ ((__packed__))
# define ntohll(x) be64_to_cpu(x)
# define htonll(x) cpu_to_be64(x)
#ifndef GETSHORT
#define GETSHORT(p) (ntohs(*(p)))
#endif
#ifndef PUTSHORT
#define PUTSHORT(p,val) ((*p) = htons(val))
#endif
#ifndef GETLONG
#define GETLONG(p) (ntohl(*(p)))
#endif
#ifndef PUTLONG
#define PUTLONG(p,val) ((*p) = htonl(val))
#endif
#ifdef __BIG_ENDIAN
#define __BYTE_ORDER __BIG_ENDIAN
#else
#define __BYTE_ORDER __LITTLE_ENDIAN
#endif
/*
* If CONFIG_BUG [lib/bug.c] is not defined, then BUG() is empty
* and thus ASSERT() will be effectively turned off.
*/
#define ASSERT(exp,...) \
{ \
if (!(exp)) { \
printk("FAILED ASSERTION in %s:%u\n", __FUNCTION__, __LINE__); \
BUG(); \
} \
} \
#define ASSERT_MAX_BUFF 128
extern char g_vqec_assertbuff[ASSERT_MAX_BUFF];
#define ASSERT_FATAL(exp, type,...) \
({ \
if (!(exp)) { \
snprintf(g_vqec_assertbuff, ASSERT_MAX_BUFF, __VA_ARGS__); \
printk("FAILED ASSERTION %s(%d)\n", __FUNCTION__, __LINE__); \
syslog_print(type, g_vqec_assertbuff); \
BUG(); \
} \
})
/*
* Class declaration stuff
*
* DEFCLASS(FOO) expands to
*
* struct FOO_fcns_;
* struct FOO_;
*
* typedef struct FOO_fcns_ {
* __FOO_fcns
*
* } FOO_fcns_t;
*
* typedef struct FOO_ {
* FOO_fcns_t * __func_table;
* __FOO_members
* } FOO_t;
*
* void FOO_set_fcns(FOO_fcns_t * table);
*
*/
#define DEFCLASS(name) \
struct name ## _fcns_ ; \
struct name ## _ ; \
typedef struct name ## _fcns_ { \
__ ## name ## _fcns \
} name ## _fcns_t; \
typedef struct name ## _ { \
name ## _fcns_t * __func_table; \
__ ## name ## _members ; \
} name ## _t; \
void name ## _set_fcns(name ## _fcns_t * table);
/*
* Method call macro
*
*/
#define MCALL(obj,method,args...) (obj)->__func_table->method((obj) , ## args)
/* The following is assumed to have the same layout as a struct iovec. See man readv. */
typedef struct vam_scatter_desc_
{
void * addr;
size_t len;
} vam_scatter_desc_t;
/*
* Memory allocation.
*/
#define VQE_MALLOC_ATOMIC(x) kmalloc((x), GFP_ATOMIC)
#define VQE_MALLOC(x) kmalloc((x), GFP_KERNEL)
#define VQE_FREE(x) kfree((x))
/*
* Time-of-day system call.
*/
/*
* Time-of-day system call.
*/
#define VQE_GET_TIMEOFDAY(x, y) \
({ \
int32_t __result = 0; \
do_gettimeofday((x)); \
__result; \
})
#define VQE_FPRINTF(dev, format,...) \
printk(format, ##__VA_ARGS__)
#define VQE_VFPRINTF(dev, format, ap) \
vprintk(format, ap)
/*
* Mutual exclusion.
*/
typedef
struct vqe_mutex_
{
spinlock_t l;
unsigned long flags;
} vqe_mutex_t;
#define VQE_MUTEX_DEFINE(_name) \
vqe_mutex_t _name = {SPIN_LOCK_UNLOCKED}
#define VQE_MUTEX_LOCK(x) \
spin_lock_irqsave(&((x)->l), (x)->flags)
#define VQE_MUTEX_UNLOCK(x) \
spin_unlock_irqrestore(&((x)->l), (x)->flags)
#define VQE_RAND_R(x) \
({ \
int32_t _randb; \
*(x) = *(x); \
get_random_bytes(&_randb, sizeof(_randb)); \
_randb; \
})
#define VQE_GETENV_SYSCALL(str) NULL
#define VQE_SQRT(x) int_sqrt((int32_t)(x))
#define VQE_SET_ERRNO(x)
#define perror(str)
#define VQE_DIV64(x, y) \
({ \
uint64_t __d = abs((x)); \
uint32_t __v = abs((y)); \
typeof((x)) __x; \
uint32_t __rem; \
__rem = do_div(__d, __v); \
__x = __d; \
if ((((x) > 0) && ((y) < 0)) || \
(((x) < 0) && ((y) > 0))) { \
__x = -1 * __x; \
} \
__x; \
})
/**
* Implementation of bsearch for vam_hist.c - in stdlib.h!
*/
typedef int (*compar_fn_t) (const void *, const void *);
void *bsearch(void *__key, void *__base,
size_t nmemb, size_t size, compar_fn_t compar);
/**
* Stub sendto in inputshim for now - sendto() should be pushed via a
* socket abstraction into vqec_recv_socket.c
*/
static inline ssize_t
sendto(int fd, const void *buf, size_t len, int flags, const struct sockaddr *to, int socklen)
{
return (0);
}
#endif /* __VAM_TYPES_H__ */
|
wmanley/cisco-vqe-client
|
include/utils/kmod/vam_types.kmod.h
|
vam_types.kmod.h
|
h
| 6,749
|
c
|
en
|
code
| 9
|
github-code
|
19
|
70943645485
|
#include "menu.h"
int salvarCliente(cliente **client){
cliente *lst;
FILE *ptArq;
lst = *client;
ptArq = fopen("DadosClientes.csv", "w");
if(ptArq == NULL){
printf("Erro ao salvar Clientes");
pausa();
return 0;
}
while(lst != NULL){
fprintf(ptArq, "%s;", lst->nome);
fprintf(ptArq, "%s;", lst->cpf);
fprintf(ptArq, "%s;", lst->endereco);
fprintf(ptArq, "%s;", lst->bairro);
fprintf(ptArq, "%s;", lst->cidade_estado);
fprintf(ptArq, "%s;\n", lst->telefone);
lst = lst->prox;
}
fclose(ptArq);
return 1;
}
int salvarProduto(produto **prod){
produto *lst;
FILE *ptArq;
lst = *prod;
ptArq = fopen("DadosProdutos.csv", "w");
if(ptArq == NULL){
printf("Erro ao salvar Produtos");
pausa();
return 0;
}
while(lst != NULL){
fprintf(ptArq, "%s;", lst->codigo);
fprintf(ptArq, "%s;", lst->descricao);
fprintf(ptArq, "%s;", lst->data_validade);
fprintf(ptArq, "%s;", lst->fornecedor);
fprintf(ptArq, "%d;", lst->qtd);
fprintf(ptArq, "%lf;\n", lst->preco);
lst = lst->prox;
}
fclose(ptArq);
return 1;
}
int salvarVenda(venda **compras){
venda *lst;
FILE *ptArq;
lst = *compras;
ptArq = fopen("DadosVendas.csv", "w");
if(ptArq == NULL){
printf("erro ao salvar venda");
pausa();
return 0;
}
while(lst != NULL){
fprintf(ptArq, "%s;", lst->codigo_produto);
fprintf(ptArq, "%s;", lst->cpf_cliente);
fprintf(ptArq, "%d;\n", lst->quantidade_venda);
lst = lst->prox;
}
fclose(ptArq);
return 1;
}
int recuperaCliente(cliente **client){
FILE *ptArq;
ptArq = fopen("DadosClientes.csv", "r");
if(ptArq == NULL){
return 0;
}else{
char linha[180];
char *nome;
char *cpf;
char *endereco;
char *bairro;
char *cidade_estado;
char *telefone;
while(fgets(linha,180,ptArq) != NULL){
nome = strtok(linha,";");
cpf = strtok(NULL,";");
endereco = strtok(NULL,";");
bairro = strtok(NULL,";");
cidade_estado = strtok(NULL,";");
telefone = strtok(NULL,";");
criarCliente(nome,cpf,endereco,bairro,cidade_estado,telefone, client);
}
fclose(ptArq);
return 1;
}
}
int recuperaProduto(produto **prod){
FILE *ptArq;
ptArq = fopen("DadosProdutos.csv", "r");
if(ptArq == NULL){
return 0;
}else{
char linha[180];
char *codigo;
char *descricao;
char *data_validade;
char *fornecedor;
char *qtd_str;
char *preco_str;
int qtd;
double preco;
while(fgets(linha,180,ptArq) != NULL){
codigo = strtok(linha,";");
descricao = strtok(NULL,";");
fornecedor = strtok(NULL,";");
data_validade = strtok(NULL,";");
qtd_str = strtok(NULL,";");
preco_str = strtok(NULL,";");
qtd = atoi(qtd_str);
preco = atof(preco_str);
printf(" %d",criarProduto(codigo,descricao, data_validade, fornecedor,qtd,preco, prod));
}
fclose(ptArq);
return 1;
}
}
int recuperaVenda(venda **lst_vendas){
FILE *ptArq;
ptArq= fopen("DadosVendas.csv","r");
if (ptArq == NULL){
return 0;
}else{
char linha[40];
char *codigo_produto;
char *cpf_cliente;
char *qtd_str;
int qtd;
while(fgets(linha,180,ptArq) != NULL){
codigo_produto = strtok(linha,";");
cpf_cliente = strtok(NULL,";");
qtd_str = strtok(NULL,";");
qtd = atoi(qtd_str);
criarVenda(codigo_produto,cpf_cliente,qtd,lst_vendas);
}
fclose(ptArq);
return 1;
}
}
|
augustov7/Trabalho-alg2
|
ioArquivos.c
|
ioArquivos.c
|
c
| 4,246
|
c
|
pt
|
code
| 0
|
github-code
|
19
|
1009420092
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "tagdb.h"
/* TOKENS */
#define NULLTOKEN 0
#define END 1
#define ID 2
#define SEPARATOR 3
#define NL 4
#define EQ 5
static char *infile; /* file being parsed */
static char word[128];
static int lineno;
/* ---------------- private routines ----------------- */
static void spring_clean_text (s,t)
/* parse out normal escape characters bar hex and octal */
char *s;
char *t;
{
while (*s != '\0') {
if (*s == '\\')
switch (*++s) {
case 'a': *t++ = '\a'; s++; break;
case 'b': *t++ = '\b'; s++; break;
case 'f': *t++ = '\f'; s++; break;
case 'n': *t++ = '\n'; s++; break;
case 'r': *t++ = '\r'; s++; break;
case 't': *t++ = '\t'; s++; break;
case 'v': *t++ = '\v'; s++; break;
case '\n':
while (isspace(*++s));
break;
/*
case 'x' :
if (isxdigit(s[1]) && isxdigit(s[2])) {
#define ASCII_TO_HEX(A) (isdigit(A)?(A-'0'):(tolower(A)-'a'+10))
*t++ = ASCII_TO_HEX(s[1])*16 + ASCII_TO_HEX(s[2]);
s++;s++;s++;
}
break;
*/
case '\\':
case '\?':
case '\'':
case '\"':
case '\0': break;
} else *t++ = *s++;
}
*t = '\0';
}
static int next_word(FILE *fp)
/*
** lexical analyser
** Get's the next word from the input stream
*/
{
int a;
int token;
char *s;
token = NULLTOKEN;
s = word;
while (token == NULLTOKEN) {
switch (a = getc(fp)) {
case EOF:
token = END;
break;
case '\n':
lineno++;
token = NL;
break;
case '=':
token = EQ;
break;
case ':':
token = SEPARATOR;
break;
case '#':
/* comment: skip to end of line */
for(a=getc(fp); a!=EOF && a!='\n'; a=getc(fp));
if (a=='\n') lineno++;
if (a==EOF) token = END;
break;
case '\\':
/* back quoted newlines are skipped */
/* back quoted "anything else" is "anything else" */
a = getc(fp);
if (a != EOF && a != '\n') ungetc(a,fp);
break;
case '"':
/* quoted string */
for(a=getc(fp);a!=EOF && a!='"';a=getc(fp)) {
if (a=='\n') lineno++;
*s++ = a;
}
token = ID;
break;
default:
if (isalnum(a)) {
*s++ = a;
for(a=getc(fp);a!=EOF && isalnum(a);a=getc(fp)) *s++ = a;
if (a!=EOF) ungetc(a,fp);
token = ID;
}
break;
}
}
*s = '\0';
spring_clean_text(word,word);
return token;
}
static void parse_error(char *s)
{
fprintf( stderr, "%s on line %d of %s\n", s,lineno,infile);
}
static int snatch(char *s)
{
if (strcmp(s,"id")==0) return TAG_SEARCH_ID;
if (strcmp(s,"fg")==0) return TAG_FG_COLOUR;
if (strcmp(s,"bg")==0) return TAG_BG_COLOUR;
if (strcmp(s,"dt")==0) return TAG_DEFAULT_TEXT;
return TAG_UNKNOWN;
}
static void initTagDBFields(char *type)
{
tag_db[tag_db_count].type = (char *)malloc(strlen(type)+1);
strcpy(tag_db[tag_db_count].type,type);
tag_db[tag_db_count].search_id = NULL;
tag_db[tag_db_count].fg_colour = NULL;
tag_db[tag_db_count].bg_colour = NULL;
tag_db[tag_db_count].default_text = NULL;
}
static void tidyUpTagDBFields()
{
int len;
if (tag_db[tag_db_count].search_id == NULL) {
tag_db[tag_db_count].search_id = tag_db[tag_db_count].type;
}
len = strlen(tag_db[tag_db_count].search_id);
if (len < 4)
strncpy(tag_db[tag_db_count].id," ",4);
else
len = 4;
strncpy(tag_db[tag_db_count].id,tag_db[tag_db_count].search_id,len);
if (tag_db_count < (MAX_TAG_TYPES-1))
tag_db_count++;
}
static int parse_file(FILE *fp)
/*
** Parse file and load info into tag_db[]
*/
{
int at_end_of_file;
int at_end_of_entry;
/* for safe keeping */
int field;
char *WORD;
at_end_of_file = 0;
while (!at_end_of_file) {
switch (next_word(fp)) {
case END:
at_end_of_file = 1;
case NL:
break;
case ID:
/* the big time */
initTagDBFields(word);
switch(next_word(fp)) {
case END:
at_end_of_file = 1;
case NL:
break;
case SEPARATOR:
/* arglist */
at_end_of_entry = 0;
while (!at_end_of_entry) {
switch(next_word(fp)) {
case SEPARATOR:
break;
case ID:
field = snatch(word);
switch(next_word(fp)) {
case EQ:
switch(next_word(fp)) {
case ID:
WORD = (char *)malloc(strlen(word)+1);
strcpy(WORD,word);
switch (field) {
case TAG_SEARCH_ID :
tag_db[tag_db_count].search_id = WORD;
break;
case TAG_FG_COLOUR :
tag_db[tag_db_count].fg_colour = WORD;
break;
case TAG_BG_COLOUR :
tag_db[tag_db_count].bg_colour = WORD;
break;
case TAG_DEFAULT_TEXT :
tag_db[tag_db_count].default_text = WORD;
break;
default:
break;
}
switch(next_word(fp)) {
case END:
at_end_of_file = 1;
case NL:
at_end_of_entry = 1;
case SEPARATOR:
break;
default:
parse_error("Syntax error");
return ( 1 );
}
break;
default:
parse_error("Syntax error");
return ( 1 );
}
break;
case END:
at_end_of_file = 1;
case NL:
at_end_of_entry = 1;
case SEPARATOR:
break;
default:
parse_error("Syntax error");
return ( 1 );
}
break;
case END:
at_end_of_file = 1;
case NL:
at_end_of_entry = 1;
break;
default:
parse_error("Syntax error");
return ( 1 );
}
}
break;
default:
parse_error("Syntax error");
return 1;
}
tidyUpTagDBFields();
break;
default:
parse_error("Syntax error");
return 1;
}
}
return 0;
}
/* ------------------- exported routines ------------------ */
tag_db_struct tag_db[MAX_TAG_TYPES];
int tag_db_count;
void parse(char *file)
{
int parse_failed;
FILE *fp;
char *default_type = "Comment";
char *default_search_id = "DEFC";
char *default_fg_colour = NULL;
char *default_bg_colour = "yellow";
char *default_default_text = "Enter your comment here";
infile = file;
tag_db_count = 0;
if(fp = fopen(file,"r")) {
lineno = 1;
parse_failed = parse_file(fp);
if (parse_failed) {
fprintf (stderr,"Error encountered while parsing tag database\nGiving up\n");
tag_db_count = 0;
}
fclose(fp);
} else
fprintf (stderr,"Error parsing tag database\nFile `%s' does not exist\nGiving up\n",infile);
if (! tag_db_count) {
tag_db[tag_db_count].type = default_type;
tag_db[tag_db_count].search_id = default_search_id;
tag_db[tag_db_count].fg_colour = default_fg_colour;
tag_db[tag_db_count].bg_colour = default_bg_colour;
tag_db[tag_db_count].default_text = default_default_text;
tag_db_count++;
}
}
|
starsareintherose/staden-lg
|
src/staden/tagdbparse.c
|
tagdbparse.c
|
c
| 6,832
|
c
|
en
|
code
| 0
|
github-code
|
19
|
32123689928
|
#include<stdio.h>
// First Fibonacci function
int fib1(int n){
if (n < 2)
return n;
else
return fib1(n-1)+fib1(n-2);
}
main(){
int x;
x = fib1(8);
printf("%d\n",x);
}
|
anoya97/Algorithms
|
Practicas/practica1/function_fib/fib1.c
|
fib1.c
|
c
| 180
|
c
|
uk
|
code
| 0
|
github-code
|
19
|
22861707795
|
#include "lists.h"
/**
* insert_dnodeint_at_index - insert node at index
* @h: linked list
* @idx: posisiton to insert
* @n: data
* Return: address of new node or null if failed
*/
dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)
{
dlistint_t *new_node;
dlistint_t *tmp;
unsigned int i = 1;
if ((*h == NULL && idx != 0) || h == NULL)
return (NULL);
new_node = malloc(sizeof(dlistint_t));
if (!new_node)
return (NULL);
new_node->n = n;
tmp = *h;
new_node->prev = NULL;
if (idx == 0)
{
new_node = add_dnodeint(h, n);
return (new_node);
}
while (tmp)
{
if (i == idx)
{
if (tmp->next != NULL)
tmp->next->prev = new_node;
new_node->next = tmp->next;
new_node->prev = tmp;
tmp->next = new_node;
return (new_node);
}
tmp = tmp->next, i++;
}
free(new_node);
return (NULL);
}
|
sidcarrollworks/holbertonschool-low_level_programming
|
0x16-doubly_linked_lists/7-insert_dnodeint.c
|
7-insert_dnodeint.c
|
c
| 859
|
c
|
en
|
code
| 0
|
github-code
|
19
|
30484858368
|
#include<stdio.h>
#include<math.h>
#include<time.h>
int main(){
int n, massiv[10] ;
printf("son=",n);
scanf("%d",&n);
for(int i=n; i<10; i+=2){
printf("%d\n",n);
}
if(n<=10&&n>=10)
printf("%d",n);
return 0;
}
|
muhammadyusuf05/neyron-tizimi
|
funksiya-19.c
|
funksiya-19.c
|
c
| 230
|
c
|
uk
|
code
| 0
|
github-code
|
19
|
19629067469
|
#ifndef MERGESORT_H
#define MERGESORT_H
#include <stack>
using namespace std;
template<typename T>
class MergeSort
{
private: //private member
stack<T*> pointers;
public: //public methods
void sort(T arr[], int size);
~MergeSort();
private: //private methods
T* merge(T* left, T* right, int sizeLeft, int sizeRight);
T* mergeSort(T* arr, int size);
};
#include "MergeSort.hpp"
#endif
|
lchavez287/eecs_268
|
Lab08/MergeSort.h
|
MergeSort.h
|
h
| 400
|
c
|
en
|
code
| 0
|
github-code
|
19
|
75070506284
|
/*
* libInstPatch
* Copyright (C) 1999-2014 Element Green <element@elementsofsound.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1
* of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA or on the web at http://www.gnu.org.
*/
#ifndef __IPATCH_SF2_FILE_PRIV_H__
#define __IPATCH_SF2_FILE_PRIV_H__
/* SoundFont file preset header */
struct _IpatchSF2Phdr
{
char name[20]; /* preset name */
guint16 program; /* MIDI program number */
guint16 bank; /* MIDI bank number */
guint16 bag_index; /* index into preset bag (#IPFileBag) */
guint32 library; /* Not used (preserved) */
guint32 genre; /* Not used (preserved) */
guint32 morphology; /* Not used (preserved) */
};
/* SoundFont file instrument header */
struct _IpatchSF2Ihdr
{
char name[20]; /* name of instrument */
guint16 bag_index; /* instrument bag index (#IPFileBag) */
};
/* SoundFont file sample header */
struct _IpatchSF2Shdr
{
char name[20]; /* sample name */
guint32 start; /* offset to start of sample */
guint32 end; /* offset to end of sample */
guint32 loop_start; /* offset to start of loop */
guint32 loop_end; /* offset to end of loop */
guint32 rate; /* sample rate recorded at */
guint8 root_note; /* root midi note number */
gint8 fine_tune; /* pitch correction in cents */
guint16 link_index; /* linked sample index for stereo samples */
guint16 type; /* type of sample (see IpatchSF2SampleFlags) */
};
/* SoundFont file bag (zone), indexes for zone's generators and modulators */
struct _IpatchSF2Bag
{
guint16 mod_index; /* index into modulator list */
guint16 gen_index; /* index into generator list */
};
/* RIFF chunk FOURCC guint32 integers */
#define IPATCH_SFONT_FOURCC_SFBK IPATCH_FOURCC ('s','f','b','k')
#define IPATCH_SFONT_FOURCC_INFO IPATCH_FOURCC ('I','N','F','O')
#define IPATCH_SFONT_FOURCC_SDTA IPATCH_FOURCC ('s','d','t','a')
#define IPATCH_SFONT_FOURCC_PDTA IPATCH_FOURCC ('p','d','t','a')
#define IPATCH_SFONT_FOURCC_SMPL IPATCH_FOURCC ('s','m','p','l')
#define IPATCH_SFONT_FOURCC_SM24 IPATCH_FOURCC ('s','m','2','4')
#define IPATCH_SFONT_FOURCC_PHDR IPATCH_FOURCC ('p','h','d','r')
#define IPATCH_SFONT_FOURCC_PBAG IPATCH_FOURCC ('p','b','a','g')
#define IPATCH_SFONT_FOURCC_PMOD IPATCH_FOURCC ('p','m','o','d')
#define IPATCH_SFONT_FOURCC_PGEN IPATCH_FOURCC ('p','g','e','n')
#define IPATCH_SFONT_FOURCC_INST IPATCH_FOURCC ('i','n','s','t')
#define IPATCH_SFONT_FOURCC_IBAG IPATCH_FOURCC ('i','b','a','g')
#define IPATCH_SFONT_FOURCC_IMOD IPATCH_FOURCC ('i','m','o','d')
#define IPATCH_SFONT_FOURCC_IGEN IPATCH_FOURCC ('i','g','e','n')
#define IPATCH_SFONT_FOURCC_SHDR IPATCH_FOURCC ('s','h','d','r')
/* SoundFont file chunk sizes */
#define IPATCH_SFONT_VERSION_SIZE 4 /* file version info size */
#define IPATCH_SFONT_PHDR_SIZE 38 /* file preset header size */
#define IPATCH_SFONT_INST_SIZE 22 /* file instrument header size */
#define IPATCH_SFONT_SHDR_SIZE 46 /* file sample header size */
#define IPATCH_SFONT_BAG_SIZE 4 /* file bag (zone) size */
#define IPATCH_SFONT_MOD_SIZE 10 /* file modulator size */
#define IPATCH_SFONT_GEN_SIZE 4 /* file generator size */
/**
* IpatchSF2FileSampleType:
* @IPATCH_SF2_FILE_SAMPLE_TYPE_MONO: Mono channel
* @IPATCH_SF2_FILE_SAMPLE_TYPE_RIGHT: Right channel of a stereo pair
* @IPATCH_SF2_FILE_SAMPLE_TYPE_LEFT: Left channel of a stereo pair
* @IPATCH_SF2_FILE_SAMPLE_TYPE_LINKED: Linked list of samples (not yet used)
* @IPATCH_SF2_FILE_SAMPLE_TYPE_ROM: A ROM sample
*
* SoundFont file sample channel mode
*/
typedef enum
{
IPATCH_SF2_FILE_SAMPLE_TYPE_MONO = 1 << 0,
IPATCH_SF2_FILE_SAMPLE_TYPE_RIGHT = 1 << 1,
IPATCH_SF2_FILE_SAMPLE_TYPE_LEFT = 1 << 2,
IPATCH_SF2_FILE_SAMPLE_TYPE_LINKED = 1 << 3,
IPATCH_SF2_FILE_SAMPLE_TYPE_ROM = 1 << 15
} IpatchSF2FileSampleType;
#endif
|
deepin-community/libinstpatch
|
libinstpatch/IpatchSF2File_priv.h
|
IpatchSF2File_priv.h
|
h
| 4,538
|
c
|
en
|
code
| 0
|
github-code
|
19
|
30794735611
|
/**
* @file mousewheel.h
*
*/
#ifndef MOUSEWHEEL_H
#define MOUSEWHEEL_H
#ifdef __cplusplus
extern "C" {
#endif
/*********************
* INCLUDES
*********************/
#ifndef LV_DRV_NO_CONF
#ifdef LV_CONF_INCLUDE_SIMPLE
#include "lv_drv_conf.h"
#else
#include "../../lv_drv_conf.h"
#endif
#endif
#if USE_MOUSEWHEEL
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "lvgl/lvgl.h"
#endif
#ifndef MONITOR_SDL_INCLUDE_PATH
#define MONITOR_SDL_INCLUDE_PATH <SDL2/SDL.h>
#endif
#include MONITOR_SDL_INCLUDE_PATH
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* GLOBAL PROTOTYPES
**********************/
/**
* Initialize the encoder
*/
void mousewheel_init(void);
/**
* Get encoder (i.e. mouse wheel) ticks difference and pressed state
* @param indev_drv pointer to the related input device driver
* @param data store the read data here
* @return false: all ticks and button state are handled
*/
bool mousewheel_read(lv_indev_drv_t * indev_drv, lv_indev_data_t * data);
/**
* It is called periodically from the SDL thread to check a key is pressed/released
* @param event describes the event
*/
void mousewheel_handler(SDL_Event *event);
/**********************
* MACROS
**********************/
#endif /*USE_MOUSEWHEEL*/
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /*MOUSEWHEEL_H*/
|
peng-zhihui/HoloCubic
|
3.Software/LvglSimulator/vs2019_proj/lv_drivers/indev/mousewheel.h
|
mousewheel.h
|
h
| 1,451
|
c
|
en
|
code
| 5,621
|
github-code
|
19
|
39265860420
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
/* ULOHA 6.1
int main() {
char riadok[258];
int length = 1;
while (length != 0) {
gets(riadok);
length = strlen(riadok);
for (int i = 0; i < length; i++) {
if (riadok[i] == '*') {
printf("^");
}
if (riadok[i] != '*') {
printf(" ");
}
}
printf("\n");
}
return 0;
}
*/
/* ULOHA 6.2
int lenInit(char *str, int len){
if ( !(*str) ) {
return len;
}
else {
len = lenInit(str + 1, len + 1);
}
}
int main() {
char text[256], end;
int length, maximum = 0;
while(1){
scanf("%s",text);
length = lenInit(text, 0);
printf("%d ", length);
printf(" ");
if (length > maximum){
maximum = length;
}
scanf("%c", &end);
if (end == '\n') {
break;
}
}
printf("\nNajdlhsie slovo ma %d znakov.\n", maximum);
return 0;
}
*/
int CurrentLength(char* character, int hlaska) {
if (!(*character)) {
return hlaska;
}
if (*character == 'a' || *character == 'e' || *character == 'y' || *character == 'i' || *character == 'o' || *character == 'u') {
hlaska = CurrentLength(character + 1, hlaska + 1);
}
else {
hlaska = CurrentLength(character + 1, hlaska);
}
}
int main() {
char text[256], end;
int pocet_hlasok, maximumHlasok = 0;
while (1) {
scanf("%s", text);
pocet_hlasok = CurrentLength(text, 0);
printf("%d ", pocet_hlasok);
printf(" ");
if (pocet_hlasok > maximumHlasok) {
maximumHlasok = pocet_hlasok;
}
scanf("%c", &end);
if (end == '\n') {
break;
}
}
printf("", maximumHlasok);
return 0;
}
////////////////////////
|
Arman148/C-Exercises
|
CV_6/CV_6/Source.c
|
Source.c
|
c
| 1,708
|
c
|
en
|
code
| 0
|
github-code
|
19
|
18339723649
|
#include "Red.h"
///// ยดรยตรยตรญ
CRed::CRed(void)
{
}
CRed::~CRed(void)
{
}
bool CRed::MissionTest(_us (*img)[256]){
return false;
}
TSEND CRed::Missioning(_us (*img)[256], int now){
switch(now){
case 0:
m_send = Step1(img);
break;
case 1:
m_send = Step2(img);
break;
}
return m_send;
}
TSEND CRed::Step1(_us (*img)[256]){
TSEND tsend;
tsend.state = R_GO;
tsend.step = MV_0;
tsend.now = MI_NOW;
//////////////////////////////////////////////////
_us r_temp, g_temp, b_temp;
int i = 0;
int j = 0;
int total_check = 0;
int red_chk = 0;
int red_line = 0;
int max_line = 0;
for(; i < 120; ++i){
red_chk = 0;
for(j = 0; j < 180; ++j)
{
r_temp = img[i][j] & _Red;
g_temp = img[i][j] & _Green;
b_temp = img[i][j] & _Blue;
if(r_temp == _Red && g_temp == 0 && b_temp == 0)
++red_chk;
}
if(red_chk > 100){
max_line = i;
++red_line;
}
}
if(red_line > 7 && max_line > 95){
tsend.now = MI_END;
tsend.state = R_CREEP;
tsend.step = MV_0;
}
else if(red_line > 7){
tsend.state = R_GO;
tsend.step = MV_2;
}
///////////////////////////////
return tsend;
}
TSEND CRed::Step2(_us (*img)[256]){
TSEND tsend;
tsend.state = R_GO;
tsend.step = MV_0;
return tsend;
}
|
JunHyeongJeon/SoCRobotWar
|
Soc_Cam/Red.c
|
Red.c
|
c
| 1,233
|
c
|
en
|
code
| 0
|
github-code
|
19
|
38815527612
|
#include<stdio.h>
main()
{
int intV=0;
char charV='a';
float floatV=3.14;
int *pInt=&intV;
char *pChar=&charV;
float *pFloat=&floatV;
*pInt=13;
printf("%d", intV);
printf("\n%d", pInt);
*pChar='b';
printf("\n%c", charV);
printf("\n%d", pChar);
*pFloat=2.23;
printf("\n%.2f", floatV);
printf("\n%d", pFloat);
}
|
Reikonz/CLearning
|
CECS121/InClass6.c
|
InClass6.c
|
c
| 359
|
c
|
uk
|
code
| 0
|
github-code
|
19
|
2258908955
|
//
// AiyaGPUImageTrackFilter.h
// AiyaCameraSDK
//
// Created by ๆฑชๆด on 2016/10/27.
// Copyright ยฉ 2016ๅนด ๆทฑๅณๅๅ็งๆ. All rights reserved.
//
#import "AYGPUImageFilter.h"
#import "AiyaCameraEffect.h"
@interface AiyaGPUImageTrackFilter : NSObject <AYGPUImageInput>
- (id)initWithAiyaCameraEffect:(AiyaCameraEffect *)cameraEffect;
@end
|
qingcai518/MySceneKit
|
libs/Aiya/AiyaCameraSDK.framework/Headers/AiyaGPUImageTrackFilter.h
|
AiyaGPUImageTrackFilter.h
|
h
| 356
|
c
|
en
|
code
| 1
|
github-code
|
19
|
72217948202
|
//
// Bridge.h
// MoneySplit
//
// Created by Yang Hu on 11/19/15.
// Copyright ยฉ 2015 Aiqi Liu. All rights reserved.
//
#ifndef Bridge_h
#define Bridge_h
#import <EstimoteSDK/EstimoteSDK.h>
#endif /* Bridge_h */
|
yhx189/moneySplit
|
MoneySplit/Bridge.h
|
Bridge.h
|
h
| 220
|
c
|
en
|
code
| 0
|
github-code
|
19
|
4283704307
|
bool isToeplitzMatrix(int** matrix, int matrixRowSize, int *matrixColSizes)
{
int temp[matrixColSizes[0]];
int i,j;
for (i = 1;i < matrixRowSize;i++)
{
for (j = 1;j < matrixColSizes[0];j++)
{
if (matrix[i][j] != matrix[i-1][j-1])
return false;
}
}
return true;
}
|
Merlecmx/leet
|
lc766.c
|
lc766.c
|
c
| 339
|
c
|
en
|
code
| 0
|
github-code
|
19
|
39731071803
|
#pragma once
#include "../B/BSExtraData.h"
#include "../B/BSPointerHandle.h"
#include "../B/BSTArray.h"
#include "../E/ExtraDataTypes.h"
namespace ConsoleRE
{
class ExtraFollower : public BSExtraData
{
public:
static constexpr int TypeID = ExtraDataType<ExtraDataTypes::kFollower>;
struct FollowerInfo
{
ActorHandle actor;
float intendedFollowDistance;
};
static_assert(sizeof(FollowerInfo) == 0x8);
public:
~ExtraFollower();
// override (BSExtraData)
uint32_t GetType() const override;
public:
BSTArray<FollowerInfo> actorFollowers;
};
static_assert(sizeof(ExtraFollower) == 0x20);
}
|
Backporter/OrbisLibBGS-prod
|
CSEL/source/E/ExtraFollower.h
|
ExtraFollower.h
|
h
| 625
|
c
|
en
|
code
| 1
|
github-code
|
19
|
16815601850
|
// Write a program to pass the elements of an array to a function and check how many numbers are prime.
#include <stdio.h>
int prime(int a)
{
for (int i = 2; i <= a / 2; i++)
{
if (a % i == 0)
return 0;
}
return 1;
}
void main()
{
int a, count = 0;
printf("How many array elements do you want?\n");
scanf("%d", &a);
int arr[a];
for (int i = 0; i < a; i++)
{
printf("a[%d]=? \n", i);
scanf("%d", &arr[i]);
if (prime(arr[i]) == 1)
count++;
}
printf("There are %d prime elements in your array", count);
}
|
ShreyasAwankar/Orlando-C-assignments
|
28-Sept-2022/que2.c
|
que2.c
|
c
| 606
|
c
|
en
|
code
| 0
|
github-code
|
19
|
11094092898
|
#include "arch.h"
#ifdef MMX_COEF_SHA512
#ifdef _OPENMP
#include <omp.h>
#if defined __XOP__
#define OMP_SCALE 768 /* AMD */
#else
#define OMP_SCALE 2048 /* Intel */
#endif
#endif
#include <string.h>
#include "stdint.h"
#include "common.h"
#include "formats.h"
#include "sse-intrinsics.h"
#include "johnswap.h"
// This format is easy to test (during developement) of SHA384 and SHA512. We have a single
// #define that if uncommented, will 'morph' this format into sha384. It will not work on
// both hash types at the same time, but it CAN flip back and forth in an instant. The format_label
// IS kept the same (makes for easier running after a change).
//#define TEST_SHA384
#define MMX_LOAD SHA512_BUF_SIZ
//#define REMOVE_TAIL_ADD
#define TAG_LENGTH 8
#define NUMKEYS MMX_COEF_SHA512
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define MAXLEN 111
#define FULL_BINARY_SIZE 64
#ifndef TEST_SHA384
#define CIPHERTEXT_LENGTH 128
#define BINARY_SIZE 64
#define FORMAT_TAG "$SHA512$"
#define FORMAT_NAME ""
#define FORMAT_LABEL "Raw-SHA512-ng-i"
#define ALGORITHM_NAME "SHA512 " SHA512_ALGORITHM_NAME
#else
#define CIPHERTEXT_LENGTH 96
#define BINARY_SIZE 48
#define FORMAT_TAG "$SHA384$"
#define FORMAT_NAME ""
#define FORMAT_LABEL "Raw-SHA384-ng-i"
#define ALGORITHM_NAME "SHA384 " SHA512_ALGORITHM_NAME
#endif
#define BINARY_ALIGN 8
#define SALT_SIZE 0
#define SALT_ALIGN 1
#define MIN_KEYS_PER_CRYPT MMX_COEF_SHA512
#define MAX_KEYS_PER_CRYPT MMX_COEF_SHA512
static struct fmt_tests tests[] = {
#ifdef TEST_SHA384
/* SHA384 */
{"f5260c125dedb0be1f9a1e67072db4fc9f41602827f5d3f7da8487a8821170a237afb9d09c7b3391cdbcabf81d2e04af", "epixoip"},
{"a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"},
{"ab3943891e0e0631853877b5afc66eb39e5ffb08e71842c36dad1b6c2f88159f6527912f940d524305d5c6e9d636966e", "ALLCAPS"},
{"879843fb506ee1034dc88d631df353eec61005d895f01056fc169d41af1dc791d3a373ee176dd746473b86f2773a9181", "TestTESTt3st"},
{FORMAT_TAG "8cafed2235386cc5855e75f0d34f103ccc183912e5f02446b77c66539f776e4bf2bf87339b4518a7cb1c2441c568b0f8", "12345678"},
{FORMAT_TAG "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", ""},
{FORMAT_TAG "156b528027cb6dcc4af116cd69fb4beb3efb9c7ebcc51147debf16550b752c89d842d6ec9ab0a1b40bb69c95c5274ab4", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"},
#else
{"f342aae82952db35b8e02c30115e3deed3d80fdfdadacab336f0ba51ac54e297291fa1d6b201d69a2bd77e2535280f17a54fa1e527abc6e2eddba79ad3be11c0", "epixoip"},
{"b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86", "password"},
{"71ebcb1eccd7ea22bd8cebaec735a43f1f7164d003dacdeb06e0de4a6d9f64d123b00a45227db815081b1008d1a1bbad4c39bde770a2c23308ff1b09418dd7ed", "ALLCAPS"},
{"82244918c2e45fbaa00c7c7d52eb61f309a37e2f33ea1fba78e61b4140efa95731eec849de02ee16aa31c82848b51fb7b7fbae62f50df6e150a8a85e70fa740c", "TestTESTt3st"},
{FORMAT_TAG "fa585d89c851dd338a70dcf535aa2a92fee7836dd6aff1226583e88e0996293f16bc009c652826e0fc5c706695a03cddce372f139eff4d13959da6f1f5d3eabe", "12345678"},
{FORMAT_TAG "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", ""},
{"7aba4411846c61b08b0f2282a8a4600232ace4dd96593c755ba9c9a4e7b780b8bdc437b5c55574b3e8409c7b511032f98ef120e25467678f0458643578eb60ff", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901"},
#endif
{NULL}
};
#ifdef MMX_LOAD
#define GETPOS(i, index) ( (index&(MMX_COEF_SHA512-1))*8 + ((i)&(0xffffffff-7))*MMX_COEF_SHA512 + (7-((i)&7)) + (index>>(MMX_COEF_SHA512>>1))*MMX_LOAD*MMX_COEF_SHA512*8 )
static ARCH_WORD_64 (*saved_key)[SHA512_BUF_SIZ*MMX_COEF_SHA512];
#else
static uint64_t (*saved_key)[16];
#endif
static ARCH_WORD_64 (*crypt_key)[8*MMX_COEF_SHA512];
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
int omp_t;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
#ifdef MMX_LOAD
saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt/MMX_COEF_SHA512, MEM_ALIGN_SIMD);
#else
saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_SIMD);
#endif
crypt_key = mem_calloc_tiny(sizeof(*crypt_key) * (self->params.max_keys_per_crypt/MMX_COEF_SHA512), MEM_ALIGN_SIMD);
}
static int valid (char *ciphertext, struct fmt_main *self)
{
char *p, *q;
p = ciphertext;
if (! strncmp (p, FORMAT_TAG, TAG_LENGTH))
p += TAG_LENGTH;
q = p;
while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++;
return !*q && q - p == CIPHERTEXT_LENGTH;
}
#if FMT_MAIN_VERSION > 9
static char *split (char *ciphertext, int index, struct fmt_main *self)
#else
static char *split (char *ciphertext, int index)
#endif
{
static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1];
if (!strncmp (ciphertext, FORMAT_TAG, TAG_LENGTH))
return ciphertext;
memcpy (out, FORMAT_TAG, TAG_LENGTH);
memcpy (out + TAG_LENGTH, ciphertext, CIPHERTEXT_LENGTH + 1);
strlwr (out + TAG_LENGTH);
return out;
}
static void *get_binary (char *ciphertext)
{
static union {
unsigned char c[FULL_BINARY_SIZE];
uint64_t w[FULL_BINARY_SIZE / sizeof(uint64_t)];
} *out;
int i;
if (!out)
out = mem_alloc_tiny (FULL_BINARY_SIZE, BINARY_ALIGN);
ciphertext += TAG_LENGTH;
for(i=0; i < FULL_BINARY_SIZE; i++)
out->c[i] = atoi16[ARCH_INDEX(ciphertext[i*2])] * 16 +
atoi16[ARCH_INDEX(ciphertext[i*2 + 1])];
alter_endianity_to_BE64 (out->c, (FULL_BINARY_SIZE>>3));
#ifdef REMOVE_TAIL_ADD
#ifdef TEST_SHA384
out->w[0] -= 0xcbbb9d5dc1059ed8ull;
out->w[1] -= 0x629a292a367cd507ull;
out->w[2] -= 0x9159015a3070dd17ull;
out->w[3] -= 0x152fecd8f70e5939ull;
out->w[4] -= 0x67332667ffc00b31ull;
out->w[5] -= 0x8eb44a8768581511ull;
out->w[6] -= 0xdb0c2e0d64f98fa7ull;
out->w[7] -= 0x47b5481dbefa4fa4ull;
#else
out->w[0] -= 0x6a09e667f3bcc908ULL;
out->w[1] -= 0xbb67ae8584caa73bULL;
out->w[2] -= 0x3c6ef372fe94f82bULL;
out->w[3] -= 0xa54ff53a5f1d36f1ULL;
out->w[4] -= 0x510e527fade682d1ULL;
out->w[5] -= 0x9b05688c2b3e6c1fULL;
out->w[6] -= 0x1f83d9abfb41bd6bULL;
out->w[7] -= 0x5be0cd19137e2179ULL;
#endif
#endif
return (void *) out;
}
static int get_hash_0 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xf; }
static int get_hash_1 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xff; }
static int get_hash_2 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xfff; }
static int get_hash_3 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xffff; }
static int get_hash_4 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xfffff; }
static int get_hash_5 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0xffffff; }
static int get_hash_6 (int index) { return crypt_key[index>>(MMX_COEF_SHA512>>1)][index&(MMX_COEF_SHA512-1)] & 0x7ffffff; }
#ifdef MMX_LOAD
static void set_key(char *key, int index) {
const ARCH_WORD_64 *wkey = (ARCH_WORD_64*)key;
ARCH_WORD_64 *keybuffer = &((ARCH_WORD_64 *)saved_key)[(index&(MMX_COEF_SHA512-1)) + (index>>(MMX_COEF_SHA512>>1))*SHA512_BUF_SIZ*MMX_COEF_SHA512];
ARCH_WORD_64 *keybuf_word = keybuffer;
unsigned int len;
ARCH_WORD_64 temp;
len = 0;
while((unsigned char)(temp = *wkey++)) {
if (!(temp & 0xff00))
{
*keybuf_word = JOHNSWAP64((temp & 0xff) | (0x80 << 8));
len++;
goto key_cleaning;
}
if (!(temp & 0xff0000))
{
*keybuf_word = JOHNSWAP64((temp & 0xffff) | (0x80 << 16));
len+=2;
goto key_cleaning;
}
if (!(temp & 0xff000000))
{
*keybuf_word = JOHNSWAP64((temp & 0xffffff) | (0x80ULL << 24));
len+=3;
goto key_cleaning;
}
if (!(temp & 0xff00000000ULL))
{
*keybuf_word = JOHNSWAP64((temp & 0xffffffff) | (0x80ULL << 32));
len+=4;
goto key_cleaning;
}
if (!(temp & 0xff0000000000ULL))
{
*keybuf_word = JOHNSWAP64((temp & 0xffffffffffULL) | (0x80ULL << 40));
len+=5;
goto key_cleaning;
}
if (!(temp & 0xff000000000000ULL))
{
*keybuf_word = JOHNSWAP64((temp & 0xffffffffffffULL) | (0x80ULL << 48));
len+=6;
goto key_cleaning;
}
if (!(temp & 0xff00000000000000ULL))
{
*keybuf_word = JOHNSWAP64((temp & 0xffffffffffffffULL) | (0x80ULL << 56));
len+=7;
goto key_cleaning;
}
*keybuf_word = JOHNSWAP64(temp);
len += 8;
keybuf_word += MMX_COEF_SHA512;
}
*keybuf_word = 0x8000000000000000ULL;
key_cleaning:
keybuf_word += MMX_COEF_SHA512;
while(*keybuf_word) {
*keybuf_word = 0;
keybuf_word += MMX_COEF_SHA512;
}
keybuffer[15*MMX_COEF_SHA512] = len << 3;
}
#else
static void set_key (char *key, int index)
{
uint64_t *buf64 = (uint64_t *) (saved_key[index]);
uint8_t *buf8 = (uint8_t *) buf64;
int len = 0;
while (*key)
buf8[len++] = *key++;
buf64[15] = (len << 3);
buf8[len++] = 0x80;
while (buf8[len] && len <= MAXLEN)
buf8[len++] = 0;
//for (len=0; len<16; ++len)
// printf("%08x ", buf32[len]);
//printf("\n");
}
#endif
#ifdef MMX_LOAD
static char *get_key(int index) {
unsigned i;
uint64_t s;
static char out[MAXLEN + 1];
unsigned char *wucp = (unsigned char*)saved_key;
s = ((ARCH_WORD_64 *)saved_key)[15*MMX_COEF_SHA512 + (index&(MMX_COEF_SHA512-1)) + (index>>((MMX_COEF_SHA512>>1)))*SHA512_BUF_SIZ*MMX_COEF_SHA512] >> 3;
for(i=0;i<(unsigned)s;i++)
out[i] = wucp[ GETPOS(i, index) ];
out[i] = 0;
return (char*) out;
}
#else
static char *get_key (int index)
{
uint64_t *buf64 = (uint64_t *) &saved_key[index];
uint8_t *buf8 = (uint8_t * ) buf64;
static char out[MAXLEN + 1];
int len = (int)(buf64[15] >> 3);
out[len] = 0;
for (len--; len > -1; len--)
out[len] = buf8[len];
return (char *) out;
}
#endif
static int crypt_all (int *pcount, struct db_salt *salt)
{
#if FMT_MAIN_VERSION > 10
int count = *pcount;
#endif
int i = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (i = 0; i < count; i += MMX_COEF_SHA512)
#endif
{
#ifdef REMOVE_TAIL_ADD
#ifdef MMX_LOAD
#ifdef TEST_SHA384
SSESHA512body(&saved_key[i/MMX_COEF_SHA512], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_MIXED_IN|SSEi_CRYPT_SHA384|SSEi_SKIP_FINAL_ADD);
#else
SSESHA512body(&saved_key[i/MMX_COEF_SHA512], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_MIXED_IN|SSEi_SKIP_FINAL_ADD);
#endif
#else
#ifdef TEST_SHA384
SSESHA512body(&saved_key[i], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_FLAT_IN|SSEi_CRYPT_SHA384|SSEi_SKIP_FINAL_ADD);
#else
SSESHA512body(&saved_key[i], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_FLAT_IN|SSEi_SKIP_FINAL_ADD);
#endif
#endif
#else
#ifdef MMX_LOAD
#ifdef TEST_SHA384
SSESHA512body(&saved_key[i/MMX_COEF_SHA512], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_MIXED_IN|SSEi_CRYPT_SHA384);
#else
SSESHA512body(&saved_key[i/MMX_COEF_SHA512], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_MIXED_IN);
#endif
#else
#ifdef TEST_SHA384
SSESHA512body(&saved_key[i], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_FLAT_IN|SSEi_CRYPT_SHA384);
#else
SSESHA512body(&saved_key[i], crypt_key[i/MMX_COEF_SHA512], NULL, SSEi_FLAT_IN);
#endif
#endif
#endif
}
#if FMT_MAIN_VERSION > 10
return count;
#endif
}
static int cmp_all (void *binary, int count)
{
int i;
for (i = 0; i < count; i++)
if (((uint64_t *) binary)[0] == crypt_key[i>>(MMX_COEF_SHA512>>1)][i&(MMX_COEF_SHA512-1)])
return 1;
return 0;
}
static int cmp_one (void *binary, int index)
{
int i;
for (i = 0; i < BINARY_SIZE/sizeof(ARCH_WORD_64); i++)
if (((uint64_t *) binary)[i] != crypt_key[index>>(MMX_COEF_SHA512>>1)][(index&(MMX_COEF_SHA512-1))+i*MMX_COEF_SHA512])
return 0;
return 1;
}
static int cmp_exact (char *source, int index)
{
return 1;
}
struct fmt_main fmt_rawSHA512_ng_i = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
MAXLEN,
BINARY_SIZE,
#if FMT_MAIN_VERSION > 9
BINARY_ALIGN,
#endif
SALT_SIZE,
#if FMT_MAIN_VERSION > 9
SALT_ALIGN,
#endif
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP,
tests
}, {
init,
#if FMT_MAIN_VERSION > 10
fmt_default_done,
fmt_default_reset,
#endif
fmt_default_prepare,
valid,
split,
get_binary,
fmt_default_salt,
#if FMT_MAIN_VERSION > 9
fmt_default_source,
#endif
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
fmt_default_set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
get_hash_0,
get_hash_1,
get_hash_2,
get_hash_3,
get_hash_4,
get_hash_5,
get_hash_6
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif
|
miguelps/JohnTheRipper
|
src/rawSHA512_ng_i_fmt.c
|
rawSHA512_ng_i_fmt.c
|
c
| 14,010
|
c
|
en
|
code
| null |
github-code
|
19
|
14926463437
|
/*
* Syslink-IPC for TI OMAP Processors
*
* Copyright (c) 2008-2010, Texas Instruments Incorporated
* 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 Texas Instruments Incorporated 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.
*/
/** ============================================================================
* @file Atomic_Ops.h
*
* @brief Atomic operations abstraction
*
*
* @ver 2.00.00.06
*
* ============================================================================
*/
#ifndef ATOMIC_OPS_H
#define ATOMIC_OPS_H
/* Standard libc headers */
#include <stdio.h>
#include <pthread.h>
/* =============================================================================
* Typedef
* =============================================================================
*/
/*! @brief Typedef for atomic variable */
typedef UInt32 Atomic;
/* =============================================================================
* Global
* =============================================================================
*/
/* Lock used by atomic operations to create psuedo atomicity */
static pthread_mutex_t Atomic_lock = PTHREAD_MUTEX_INITIALIZER;
/* =============================================================================
* APIs & Macros
* =============================================================================
*/
/*!
* @brief Function to read an variable atomically
*
* @param var Pointer to atomic variable
*/
static inline UInt32 Atomic_read (Atomic * var)
{
UInt32 ret;
pthread_mutex_lock (&Atomic_lock);
ret = *var;
pthread_mutex_unlock (&Atomic_lock);
/*! @retval value Current value of the atomic variable */
return ret;
}
/*!
* @brief Function to set an variable atomically
*
* @param var Pointer to atomic variable
* @param val Value to be set
*/
static inline void Atomic_set (Atomic * var, UInt32 val)
{
pthread_mutex_lock (&Atomic_lock);
*var = val;
pthread_mutex_unlock (&Atomic_lock);
}
/*!
* @brief Function to increment an variable atomically
*
* @param var Pointer to atomic variable
* @param val Value to be set
*/
static inline UInt32 Atomic_inc_return (Atomic * var)
{
UInt32 ret;
pthread_mutex_lock (&Atomic_lock);
*var = *var + 1u;
ret = *var;
pthread_mutex_unlock (&Atomic_lock);
/*! @retval value Current value of the atomic variable */
return ret;
}
/*!
* @brief Function to decrement an variable atomically
*
* @param var Pointer to atomic variable
* @param val Value to be set
*/
static inline UInt32 Atomic_dec_return (Atomic * var)
{
UInt32 ret;
pthread_mutex_lock (&Atomic_lock);
*var = *var - 1u;
ret = *var;
pthread_mutex_unlock (&Atomic_lock);
/*! @retval value Current value of the atomic variable */
return ret;
}
/*!
* @brief Function to compare a mask and set if not equal
*
* @params v Pointer to atomic variable
* @params mask Mask to compare with
* @params val Value to be set if mask does not match.
*/
static inline void Atomic_cmpmask_and_set(Atomic * var, UInt32 mask, UInt32 val)
{
UInt32 ret;
pthread_mutex_lock (&Atomic_lock);
ret = *var;
if ((ret & mask) != mask) {
*var = val;
}
pthread_mutex_unlock (&Atomic_lock);
}
/*!
* @brief Function to compare a mask and then check current value less than
* provided value.
*
* @params v Pointer to atomic variable
* @params mask Mask to compare with
* @params val Value to be set if mask does not match.
*/
static inline Bool Atomic_cmpmask_and_lt(Atomic * var, UInt32 mask, UInt32 val)
{
Bool ret = TRUE;
UInt32 cur = 0;
pthread_mutex_lock (&Atomic_lock);
cur = *var;
if ((cur & mask) == mask) {
if (cur >= val) {
ret = FALSE;
}
}
pthread_mutex_unlock (&Atomic_lock);
/*! @retval TRUE if mask matches and current value is less than given
* value */
/*! @retval FALSE either mask doesnot matches or current value is not less
* than given value */
return ret;
}
/*!
* @brief Function to compare a mask and then check current value greater than
* provided value.
*
* @params v Pointer to atomic variable
* @params mask Mask to compare with
* @params val Value to be set if mask does not match.
*/
static inline Bool Atomic_cmpmask_and_gt(Atomic * var, UInt32 mask, UInt32 val)
{
Bool ret = TRUE;
UInt32 cur = 0;
pthread_mutex_lock (&Atomic_lock);
cur = *var;
if ((cur & mask) == mask) {
if (cur < val) {
ret = FALSE;
}
}
pthread_mutex_unlock (&Atomic_lock);
/*! @retval TRUE if mask matches and current value is less than given
* value */
/*! @retval FALSE either mask doesnot matches or current value is not
* greater than given value */
return ret;
}
#endif /* if !defined(ATOMIC_OPS_H) */
|
tpruvot/android_hardware_ti_omap4
|
syslink/syslink/api/include/Atomic_Ops.h
|
Atomic_Ops.h
|
h
| 6,384
|
c
|
en
|
code
| 7
|
github-code
|
19
|
32771683860
|
//
// BridgingHeader.h
// HipChatStringParser
//
// Created by Sai Tat Lam on 30/04/2016.
// Copyright ยฉ 2016 Sai Tat Lam. All rights reserved.
//
#ifndef BridgingHeader_h
#define BridgingHeader_h
#import "HCConstants.h"
#import "HCObject.h"
#import "HCMessage.h"
#import "HCLink.h"
#import "HCParserFactory.h"
#import "HCParser.h"
#import "HCStringParser.h"
#import "HCStubStringParser.h"
#import "HCURLFetchingStringParser.h"
// Libraries
//#import "GDataXMLNode.h" // For some reason when compiling for real device Xcode fails to locate the GDataXMLNode.h file, but given that we do not use this library in the Swift area, there is no need to import such header into the bridging header. So it's best to leave it out.
//#import <GDataXML-HTML/GDataXMLNode.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import <Reachability/Reachability.h>
#endif /* BridgingHeader_h */
|
lamsaitat/hip-chat-string-parser-ios
|
HipChatStringParser/headers/BridgingHeader.h
|
BridgingHeader.h
|
h
| 886
|
c
|
en
|
code
| 1
|
github-code
|
19
|
44310718789
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <semaphore.h>
#include <unistd.h>
#include <mqueue.h>
#include <fcntl.h>
#include <time.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <limits.h>
#include <features.h>
#define DURATION_MIN 2
#define DURATION_MAX 10
#define Q_MAX_MSGS 10
struct shared {
pthread_mutex_t shared_mutex;
int last_used_job_id;
};
struct msg {
int job_id;
int job_duration;
char shm_name[NAME_MAX];
};
int main(int argc, char** argv)
{
char q_name[NAME_MAX] = { '/' };
mqd_t q;
int shm_d;
struct shared* sm;
int job_id;
int i, j, k;
if (argc != 2) {
printf("call: ./generator J\n");
return 0;
}
struct sched_param param;
param.sched_priority = 50;
sched_setscheduler(0, SCHED_RR, ¶m);
srand(time(NULL));
j = strtol(argv[1], NULL, 10);
strncat(q_name, getenv("SERVER_LAB5"), NAME_MAX - 2);
struct mq_attr attr;
attr.mq_maxmsg = Q_MAX_MSGS;
attr.mq_msgsize = sizeof(struct msg);
q = mq_open(q_name, O_RDWR | O_CREAT, 00600, &attr);
shm_d = shm_open(q_name, O_RDWR | O_CREAT | O_EXCL, 00600);
if (shm_d != -1) {
if (ftruncate(shm_d, sizeof(struct shared)) == -1) {
perror("Error while creating shared memory");
return -1;
}
sm = (struct shared*) mmap(NULL, sizeof(struct shared), PROT_READ | PROT_WRITE, MAP_SHARED, shm_d, 0);
if (sm == MAP_FAILED) {
perror("Error while mapping shared memory");
return -1;
}
pthread_mutex_init(&(sm->shared_mutex), NULL);
} else {
shm_d = shm_open(q_name, O_RDWR, 00600);
sm = (struct shared*) mmap(NULL, sizeof(struct shared), PROT_READ | PROT_WRITE, MAP_SHARED, shm_d, 0);
if (sm == MAP_FAILED) {
perror("Error while mapping shared memory");
return -1;
}
}
pthread_mutex_lock(&(sm->shared_mutex));
job_id = sm->last_used_job_id + 1;
sm->last_used_job_id = job_id + j;
shm_unlink(q_name);
close(shm_d);
for (i = 0; i < j; i++) {
char snum[5];
char shm2_name[NAME_MAX] = { 0 };
int duration;
int shm_d2;
int* sm_job_data;
struct msg m;
snprintf(snum, 5, "%d", job_id);
strcat(strcat(strcat(shm2_name, q_name), "-"), snum); // cba to check with strncat
duration = rand() % DURATION_MAX + DURATION_MIN;
shm_d2 = shm_open(shm2_name, O_RDWR | O_CREAT, 00600);
if (ftruncate(shm_d2, duration * sizeof(int)) == -1) {
perror("Error while creating shared memory");
return -1;
}
sm_job_data = (int *) mmap(NULL, duration * sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shm_d2, 0);
if (sm == NULL) {
perror("Error while mapping shared memory");
return -1;
}
for (k = 0; k < duration; k++) {
sm_job_data[k] = rand() % 10;
}
//shm_unlink(shm2_name);
close(shm_d2);
m.job_id = job_id;
m.job_duration = duration;
strcpy(m.shm_name, shm2_name);
mq_send(q, (const char*) &m, sizeof(struct msg), 0);
printf("G: sent %d %d %s (data: ", m.job_id, m.job_duration, m.shm_name);
for (k = 0; k < duration; k++) {
printf("%d ", sm_job_data[k]);
}
printf(")\n");
job_id++;
}
return 0;
}
|
bobocop/fer
|
szrusv/lab5/generator.c
|
generator.c
|
c
| 3,139
|
c
|
en
|
code
| 0
|
github-code
|
19
|
70294577963
|
/*****************************************************/
/* Author : mosad */
/* Version : v01 */
/* date : 5/9/2020 */
/*****************************************************/
#ifndef OS_PRIVATE_H
#define OS_PRIVATE_H
/* Task data type to hold task information */
typedef struct
{
OS_TaskStates_t taskState ;
u8 RunMe;
u16 priode;
u16 initialDelay ;
void (* func) (void);
}OS_Task_t;
#define NULL ((void *) 0)
/******* Private functions *******/
static void voidScheduler (void);
static void voidGoToSleep(void);
#endif
|
xMosad/STM32-SDK
|
04 - SERVICE/01 - OS/OS_private.h
|
OS_private.h
|
h
| 637
|
c
|
zh
|
code
| 9
|
github-code
|
19
|
22376800329
|
#include <utility>
//
// Created by Thierry Backes on 20/10/18.
//
#ifndef PATHTRACER_HITABLE_LIST_H
#define PATHTRACER_HITABLE_LIST_H
#include <cstdio>
#include <iostream>
#include <vector>
#include "hitable.h"
class hitable_list: public hitable{
public:
hitable_list() = default;
explicit hitable_list(std::vector<std::shared_ptr<hitable>> elements):elements(std::move(elements)){};
std::vector<std::shared_ptr<hitable>> elements;
bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const;
bool bounding_box(float t0, float t1, aabb &box) override;
};
bool hitable_list::hit(const ray &r, float t_min, float t_max, hit_record &rec) const {
hit_record tmp_rec;
bool hit_anything = false;
double closest_so_far = t_max;
for(auto &elem: elements){
if(elem->hit(r,t_min,closest_so_far,tmp_rec)){
hit_anything = true;
closest_so_far = tmp_rec.t;
rec = tmp_rec;
}
}
return hit_anything;
}
bool hitable_list::bounding_box(float t0, float t1, aabb &box) {
if(elements.size() < 1) return false;
aabb tmp;
if (elements.size() == 1) {
bool first_true = elements[0]->bounding_box(t0,t1,tmp);
if(!first_true)
return false;
box = tmp;
return true;
}
bool first = false;
bool second = false;
for(auto &elem: elements){
if(elem->bounding_box(t0,t1,tmp)){
if(!first){
// This is the first box
box = tmp;
}
if(second){
// This is the second or more box
box = surrounding_box(box,tmp);
}
if(first)
second = true;
first = true;
}
}
return first;
}
#endif //PATHTRACER_HITABLE_LIST_H
|
lyinch/pathtracer
|
hitable_list.h
|
hitable_list.h
|
h
| 1,837
|
c
|
en
|
code
| 0
|
github-code
|
19
|
72746853804
|
/**************************************************************/
/* Low Level Register Access Example */
/* */
/* This example uses low level register functions to read the */
/* offset register of a VXI device at logical address 0. The */
/* program uses the viMapAddress function to map a window */
/* to the A16 VXI address space and then uses viPeek to read */
/* the value of this register. */
/* */
/* The general flow of this code is: */
/* Open Resource Manager */
/* Open VISA session to an instrument */
/* Map the desired VXI memory to the local processor's memory */
/* Use viPeek to read the offset register */
/* Unmap the memory */
/* Close the VISA session */
/**************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "visa.h"
#define ADD_OFFSET(addr, offs) (((ViPByte)addr) + (offs))
static ViSession defaultRM;
static ViSession instr;
static ViUInt16 value, access;
static ViBusAddress offset;
static ViAddr mapped_address, address;
static ViBusSize size;
static ViStatus status;
int main (void)
{
/*
* First we must call viOpenDefaultRM to get the manager
* handle. We will store this handle in defaultRM.
*/
status=viOpenDefaultRM (&defaultRM);
if (status < VI_SUCCESS)
{
printf("Could not open a session to the VISA Resource Manager!\n");
exit (EXIT_FAILURE);
}
/*
* Note: at this point it would be proper programming procedure to
* to call viFindRsrc to find available instruments to which we can
* open a session. The viFindRsrc function returns the descriptor
* for the first of these instrument. viFindNext can then be used to
* get descriptors for the other instruments. These descriptors
* are then used to open a session to the desired instrument.
* For simplicity, we will assume there is a controller
* at Logical Address zero and open a session to this address.
*/
/*
* Now we will open a VISA session to the device at logical
* address zero. We must use the resource manager handle
* from viOpenDefaultRM. We must also use a string which will
* indicate which instrument to open. This is called the
* instrument descriptor. The format for this string can
* be found in the NI-VISA User Manual. After opening a session to the
* device, we will get a handle to the instrument which we
* will use in later VISA functions. The remaining two parameters
* in this function are reserved for future functionality.
* They are given the values VI_NULL.
*/
status = viOpen (defaultRM, "VXI0::0::INSTR", VI_NULL, VI_NULL, &instr);
if (status < VI_SUCCESS)
{
printf ("Cannot open a session to the device.\n");
viClose (defaultRM);
exit (EXIT_SUCCESS);
}
/* Now we will map a window to the A16 space containing the
* configuration registers of the device using the viMapAddress
* function. This function will use the session to the
* device we obtained using viOpen.
*/
offset = 0x0; /* read Offset register in A16 */
size = 0x40; /* we will map to all configuration registers */
status = viMapAddress (instr, VI_A16_SPACE, offset, size, VI_FALSE, VI_NULL,&mapped_address);
if (status < VI_SUCCESS)
{
printf ("Error mapping the address to local memory\n");
printf ("Make sure you have a User Window configured in VXIedit\n");
viClose (defaultRM);
exit (EXIT_SUCCESS);
}
/*
* Now we will use the viPeek16 function to read the value
* of the Offset register for the device at LA 0 which we have
* mapped to the A16 space. We will do this using the pointer
* returned from the viMapAddress function. The viPeek function
* basically just dereferences a pointer to the VXI address space.
* The Offset register is at offset 0x6, so we need to increment
* the mapped address.
*/
/*
* Now that we have mapped the window, we can use the pointer
* to read and write to registers. We could do this by directly
* dereferencing the pointer, or by using viPeekXX/viPokeXX. On
* some O/S's you will not be able to directly dereference the pointer,
* so your code is more portable if you use viPeekXX/viPokeXX. To
* find out if you can directly dereference the pointer, you can get
* a VISA Attribute. In the following code, we check to see if we
* can dereference the pointer. If that is permitted we will read
* the Offset register by a direct dereference, otherwise we call
* viPeek16. After this we call viPeek again.
*/
/* Now we will use a macro to manipulate the pointer. This */
/* macro will add the correct value to the pointer to make */
/* it point to the Offset register. */
address = ADD_OFFSET (mapped_address, 6);
viGetAttribute (instr, VI_ATTR_WIN_ACCESS, &access);
if (access == VI_DEREF_ADDR) /* can dereference the pointer directly */
{
printf ("Direct Pointer Dereference was used to read the Offset Register.\n");
value = *(ViPUInt16)address;
}
else /* must use viPeek16 */
{
printf ("viPeek16 was used to read the Offset Register.\n");
viPeek16 (instr, address, &value);
}
printf("The value read from the Offset register is 0x%hX\n", value);
/* Now do viPeek16 again in case you could dereference the pointer in the first access. */
viPeek16 (instr, address, &value);
printf ("The value read from the Offset Register using viPeek16 was 0x%hx", value);
/*
* Now we need to unmap the User Window for completeness of
* code.
*/
status = viUnmapAddress (instr);
/*
* Finally, we need to close all the VISA sessions that we
* opened
*/
viClose (instr);
viClose (defaultRM);
printf("\nHit Enter to continue.");
fflush(stdin);
getchar();
return 0;
}
|
zsimpson/sdkpub
|
VXIPNP/WinNT/NIvisa/Examples/C/Vxi-vme/LowReg.c
|
LowReg.c
|
c
| 6,419
|
c
|
en
|
code
| 13
|
github-code
|
19
|
70151525805
|
//=============================================================================
// "Arduino" example program for Crystalfontz ePaper.
//
// This project is for the CFAP128296C0-0290 :
//
// https://www.crystalfontz.com/product/cfap128296d00290
//=============================================================================
//#include <SPI.h>
#include <stdint.h>
#include "ePaper_CFAP128296D00290.h"
#include "LUTs_for_CFAP128296D00290.h"
#include "stm32l4xx_hal.h"
extern SPI_HandleTypeDef hspi2;
//SPI access macros
#define ePaper_RST_0 (digitalWrite(EPD_RESET, LOW))
#define ePaper_RST_1 (digitalWrite(EPD_RESET, HIGH))
#define ePaper_CS_0 (digitalWrite(EPD_CS, LOW))
#define ePaper_CS_1 (digitalWrite(EPD_CS, HIGH))
#define ePaper_DC_0 (digitalWrite(EPD_DC, LOW))
#define ePaper_DC_1 (digitalWrite(EPD_DC, HIGH))
#define ePaper_BS_0 (digitalWrite(EPD_BUSSEL, LOW))
#define ePaper_BS_1 (digitalWrite(EPD_BUSSEL, HIGH))
void SPI_transfer(uint8_t byte)
{
HAL_SPI_Transmit(&hspi2, &byte, 1, 10000);
}
//=============================================================================
void ePaper_WriteCMD(uint8_t command)
{
//Make sure the dsplay is not busy before starting a new command.
while(0 == HAL_GPIO_ReadPin(GPIOB, EPD_READY));
//Select the controller
ePaper_CS_0;
//Aim at the command register
ePaper_DC_0;
SPI_transfer(command);
//Deselect the controller
ePaper_CS_1;
}
//=============================================================================
// command in data[0]
// parameters in data[1]. . .data[datalen-1]
#define PTR_AND_SIZ(x) x,sizeof(x)
void WriteCMD_StringFlash(const uint8_t *data, uint8_t datalen)
{
//Index into *image, that works with pgm_read_byte()
uint8_t
index;
index=0;
//Make sure the dsplay is not busy before starting a new command.
while(0 == HAL_GPIO_ReadPin(GPIOB, EPD_READY));
//Select the controller
ePaper_CS_0;
//The first byte in the string is the command, aim at the command register
ePaper_DC_0;
SPI_transfer(data[index++]);
//Remember that we wrote the command that was in data[0]
datalen--;
//Remaining bytes are data, aim at the data register
ePaper_DC_1;
for(uint8_t i= 0;i<datalen;i++)
{
SPI_transfer(data[index++]);
}
//Deslect the controller
ePaper_CS_1;
}
//=============================================================================
void Load_Flash_Image_To_Display_RAM(uint16_t width_pixels,
uint16_t height_pixels,
const uint8_t *BW_image,
const uint8_t *red_image)
{
//Index into *image, that works with pgm_read_byte()
uint16_t
index;
index=0;
//Get width_bytes from width_pixel, rounding up
uint8_t
width_bytes;
width_bytes=(width_pixels+7)>>3;
//Make sure the display is not busy before starting a new command.
while(0 == HAL_GPIO_ReadPin(GPIOB, EPD_READY));
//Select the controller
ePaper_CS_0;
//Aim at the command register
ePaper_DC_0;
//Write the command: DATA START TRANSMISSION 1 (DTM1) (R10H)
// Display Start Transmission 1
// (DTM1, White/Black Data)
//
// This command starts transmitting data and write them into SRAM. To complete
// data transmission, command DSP (Data transmission Stop) must be issued. Then
// the chip will start to send data/VCOM for panel.
// * In B/W mode, this command writes โOLDโ data to SRAM.
// * In B/W/Red mode, this command writes โB/Wโ data to SRAM.
SPI_transfer(0x10);
//Pump out the BW data.
ePaper_DC_1;
index=0;
for(uint16_t y=0;y<height_pixels;y++)
{
for(uint8_t x=0;x<width_bytes;x++)
{
SPI_transfer(BW_image[index]);
index++;
}
}
//Aim back to the command register
ePaper_DC_0;
//Write the command: DATA START TRANSMISSION 2 (DTM2) (R13H)
// Display Start transmission 2
// (DTM2, Red Data)
//
// This command starts transmitting data and write them into SRAM. To complete
// data transmission, command DSP (Data transmission Stop) must be issued. Then
// the chip will start to send data/VCOM for panel.
// * In B/W mode, this command writes โNEWโ data to SRAM.
// * In B/W/Red mode, this command writes โREDโ data to SRAM.
SPI_transfer(0x13);
//Pump out the RED data.
ePaper_DC_1;
index=0;
for(uint16_t y=0;y<height_pixels;y++)
{
for(uint8_t x=0;x<width_bytes;x++)
{
SPI_transfer(red_image[index]);
index++;
}
}
//Aim back at the command register
ePaper_DC_0;
//Write the command: DATA STOP (DSP) (R11H)
SPI_transfer(0x11);
//Write the command: Display Refresh (DRF)
SPI_transfer(0x12);
//Deslect the controller
ePaper_CS_1;
}
//=============================================================================
const uint8_t Power_Setting_PWR_On[] =
{0x01,0x03,0x00,0x0A,0x00,0x03};
const uint8_t Booster_Soft_Start_BTST[] =
{0x06,0x17,0x17,0x17};
const uint8_t Power_ON_PON[] =
{0x04};
const uint8_t Panel_Setting_PSR[] =
{0x00,0x83};
// 1000 0011 = Crystalfontz
// RREB ULDR
// |||| ||||-- RST_N *1 = run, 0 for software reset
// |||| |||--- SHD_N *1 = Booster on, 0 = Booster off
// |||| ||---- SHL *1 = scan right, 0 = scan left
// |||| |----- UD 1 = scan up, *0 = scan down
// ||||------- BWR 0 = Black/White/Red (Runs LU1 & LU2)
// ||| *1 = Black/White (Runs LU1 only)
// |||-------- REG_EN 1 = LUT from register, *0 = LUT from OTP
// ||--------- RES1:RES0 (over-ridden by 0x61)
// 00 = 96x230
// 01 = 96x252
// *10 = 128x296
// 11 = 160x296
const uint8_t Vcom_and_data_interval_setting_CDI[] =
{0x50,0x87};
// 1000 0111 = Crystalfontz
// BBRB CCCC
// |||| ||||-- CDI: 0011 = default
// ||||------- DDX[0]: Black Data Polarity 1=ink, 0=white
// |||-------- DDX[1]: Red Data Polarity 1=ink, 0=white
// ||--------- VBD: Border Data Selection
// (by experiment for DDX = 00)
// 00=really light grey
// 01=muddy red
// 10=white <<<<
// 11=black
const uint8_t PLL_control_PLL[] =
{0x30,0x29};
const uint8_t Resolution_setting_TRES[] =
{0x61,128,296>>8,296&0xFF};
const uint8_t VCM_DC_Setting_VDCS_On[] =
{0x82,0x0A};
//-----------------------------------------------------------------------------
void ePaper_Init(void)
{
//Select 4-wire SPI mode.
ePaper_BS_0;
//Give the controller a hardware reset
ePaper_RST_0;
delay(1);
ePaper_RST_1;
delay(1);
WriteCMD_StringFlash(PTR_AND_SIZ(Power_Setting_PWR_On));
WriteCMD_StringFlash(PTR_AND_SIZ(Booster_Soft_Start_BTST));
WriteCMD_StringFlash(PTR_AND_SIZ(Power_ON_PON));
WriteCMD_StringFlash(PTR_AND_SIZ(Panel_Setting_PSR));
WriteCMD_StringFlash(PTR_AND_SIZ(Vcom_and_data_interval_setting_CDI));
WriteCMD_StringFlash(PTR_AND_SIZ(PLL_control_PLL));
WriteCMD_StringFlash(PTR_AND_SIZ(Resolution_setting_TRES));
WriteCMD_StringFlash(PTR_AND_SIZ(VCM_DC_Setting_VDCS_On));
//Load the look-up-tables (LUTs), which contain the waveforms
//that instruct the controller how to jiggle the ink particals
//into the correct places to produce the image.
WriteCMD_StringFlash(PTR_AND_SIZ(VCOM_LUT_LUTC));
WriteCMD_StringFlash(PTR_AND_SIZ(W2W_LUT_LUTWW));
WriteCMD_StringFlash(PTR_AND_SIZ(B2W_LUT_LUTBW_LUTR));
WriteCMD_StringFlash(PTR_AND_SIZ(W2B_LUT_LUTWB_LUTW));
WriteCMD_StringFlash(PTR_AND_SIZ(B2B_LUT_LUTBB_LUTB));
}
//=============================================================================
const uint8_t Vcom_and_data_interval_setting_CDI_Off[] =
{0x50,0x17};
const uint8_t VCM_DC_Setting_VDCS_Off[] =
{0x82,0x00};
const uint8_t Power_Setting_PWR_Off[] =
{0x01,0x00,0x00,0x00,0x00,0x00};
const uint8_t Power_OFF_POF[] =
{0x02};
const uint8_t Deep_sleep_DSLP[] =
{0x07,0xA5};
//-----------------------------------------------------------------------------
void ePaper_PowerOff(void)
{
WriteCMD_StringFlash(PTR_AND_SIZ(Vcom_and_data_interval_setting_CDI_Off));
WriteCMD_StringFlash(PTR_AND_SIZ(VCM_DC_Setting_VDCS_Off));
WriteCMD_StringFlash(PTR_AND_SIZ(Power_Setting_PWR_Off));
WriteCMD_StringFlash(PTR_AND_SIZ(Power_OFF_POF));
WriteCMD_StringFlash(PTR_AND_SIZ(Deep_sleep_DSLP));
}
//=============================================================================
|
FrankBuss/wifi-epaper
|
stm32L433-test/cube/test/Src/ePaper_CFAP128296D00290.c
|
ePaper_CFAP128296D00290.c
|
c
| 8,498
|
c
|
en
|
code
| 13
|
github-code
|
19
|
70263833963
|
// Room: /d/wuxi/road7.c
// Winder 2000/02/22
inherit ROOM;
void create()
{
set("short", "ๆ่ซ้");
set("long", @LONG
ไธๆกไธๅฎฝ็ๆ่ซ้๏ผไธคๆ้ฆๆจๆ ๅจ่ทฏไธค่พนๆญ่ตทไบไธไธชๅคฉ็ถ็ๅ่ฌ๏ผ
ไธญ้ดๅคนๆ็ไธไบๆจๆณๆ ๏ผๅจ้ฃไธญๆๆ่ก่ก๏ผไปคไบบๅฟๆท็ฅๆกใๅ้ขๆฏๆธ
ๅๆกฅ๏ผๅๅไธ็ด้ๅๅคชๆนใ่ฅฟ่พนๆไธๆกๅฐ้๏ผ้ๅๆข
ๆ็ๆณฐไผฏๅบใ
LONG );
set("outdoors", "wuxi");
set("no_clean_up", 0);
set("exits", ([
"west" : __DIR__"road8",
"south" : __DIR__"road10",
"north" : __DIR__"qingmingqiao",
]));
set("coor/x", 370);
set("coor/y", -860);
set("coor/z", 0);
setup();
replace_program(ROOM);
}
|
mudchina/xkx100
|
d/wuxi/road7.c
|
road7.c
|
c
| 575
|
c
|
zh
|
code
| 22
|
github-code
|
19
|
28377178890
|
//
// DetailViewController.h
// Fruitmunch
//
// Created by jrk on 7/12/10.
// Copyright 2010 flux forge. All rights reserved.
//
#pragma oncde
#import <UIKit/UIKit.h>
#import <StoreKit/StoreKit.h>
#import "CocosDenshion.h"
#import "CDAudioManager.h"
@interface MinyxStoreDetailViewController : UIViewController
{
SKProduct *product;
id dataSource;
IBOutlet UILabel *titleLabel;
IBOutlet UILabel *priceLabel;
IBOutlet UITextView *detailText;
IBOutlet UIImageView *imageView;
IBOutlet UIActivityIndicatorView *activity;
IBOutlet UIButton *buyButton;
IBOutlet UIButton *showDetialButton;
IBOutlet UIButton *showYTButton;
IBOutlet UIView *detailImageView;
IBOutlet UIImageView *detailImageView_imageView;
IBOutlet UIButton *detailImageView_closeButton;
IBOutlet UILabel *detailImageView_captionLabel;
IBOutlet UIView *youtubeView;
IBOutlet UIWebView *webView;
IBOutlet UIButton *youtubeView_closeButton;
IBOutlet UIActivityIndicatorView *youtubeView_activity;
IBOutlet UIButton *youtubeView_close2Button;
CGRect small_detail_frame;
CGRect large_detail_frame;
CGRect large_yt_frame;
CGRect small_yt_frame;
tAudioManagerMode _lolmode;
BOOL reinit_sfx;
}
@property (readwrite, assign) id dataSource;
@property (readwrite, retain) SKProduct *product;
- (IBAction) buyTheShit: (id) sender;
- (IBAction) showYTVideo: (id) sender;
- (IBAction) dismissYTVideo: (id) sender;
- (IBAction) showDetailImage: (id) sender;
- (IBAction) dismissDetailImage: (id) sender;
@end
|
kybernetyk/FrameworkV3
|
Classes/ComponentV3/Runtime/Platforms/iOS/Minyx Store/DetailViewController/MinyxStoreDetailViewController.h
|
MinyxStoreDetailViewController.h
|
h
| 1,502
|
c
|
en
|
code
| 1
|
github-code
|
19
|
72131459563
|
void bfs(){
int i;
//queue variables
int queue[500];
int rear = -1;
int front = 0;
int queueItemCount = 0;
//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];
//adjace
//mark frist node as visited
lstVertices[0]->visited = true;
//display the vertex
displayVertex(0);
//insert vertex index in queue
insert(0);
*/
}
|
adrian-santos/data-structures
|
homework6/hw7/bfs.c
|
bfs.c
|
c
| 422
|
c
|
en
|
code
| 0
|
github-code
|
19
|
29928862273
|
/* File : aropen.c
Author : Richard A. O'Keefe
Updated: 12/10/98
Purpose: Reading members of UNIX archive files.
SeeAlso: aropen.pl, man 5 ar, man 1 ar
Copyright (C) 1987, Quintus Computer Systems, Inc. All rights reserved.
This file defines
QARopen(+Archive, +Member, -Stream) -> Errno
which is the guts of opening an archive member. Basically,
we open a UNIX stdio stream to the Archive file, and search
it sequentially for the Member. (This is the best we can do,
given that UNIX ar(5) files were not designed to be searched
rapidly.) If we find the Member, we create a Prolog stream
for it, and return its stream code. If not, we return a
suitable error code.
For comparison, you might like to look at charsio.{c,pl}
and crypt.{c,pl} which also open user-defined streams.
Basically, a UNIX ar(5) file has the form
<magic><member>*
where
<magic> = "!<ARCH>!\n"
and a <member> has the form
<header><contents><pad>
where
<header> is an ar_hdr record describing the member,
<contents> is the characters comprising the member,
<pad> is 0 or 1 linefeeds, padding <contents> to an
even number of characters.
Two of the errors we can report are not standard unix errors,
but are listed in library(errno) just for this operation.
They are
ENOTARCH == 997 Archive is not a well formed ar(5) file
ENOTMEMB == 998 Archive is ok, but Member isn't in it.
In System V/386 there are *two* ar(5) formats, one identified as
"PORTAR" and one identified as "PORT5AR". Only the one identified
as "PORTAR" is truly portable, and that is the one we want. Note
that most versions of UNIX do not have PORT5AR at all.
*/
#undef PORT5AR
#define PORTAR 1
#include <stdio.h>
#include <ar.h>
#include <errno.h>
#include "quintus.h"
#include "qerrno.h"
#include "malloc.h"
#ifdef AIX
/* RS6000 only has its own ar format... */
#define SARMAG SAIAMAG
#define ARMAG AIAMAG
#define ARFMAG AIAFMAG
#define ar_fmag _ar_name.ar_fmag
#define ar_name _ar_name.ar_name
#endif
#ifndef lint
static char SCCSid[] = "@(#)98/12/10 aropen.c 76.1";
#endif/*lint*/
extern int strncmp(/*char^,char^,int*/);
/* [PM] 3.5 errno is often a macro these days: extern int errno; */
typedef struct ArRecord
{
QP_stream qpinfo;
int counter; /* bytes remaining in stream */
FILE* archive_stream; /* stdio stream for whole file */
char buffer[4]; /* mini-buffer to return chars */
} *ArHandle;
static int ar_read(qpstream, bufptr, sizeptr)
QP_stream *qpstream;
char **bufptr;
size_t *sizeptr;
{
register ArHandle stream = (ArHandle) qpstream;
register int c;
if (--stream->counter < 0) return QP_EOF;
if ((c = getc(stream->archive_stream)) < 0)
{ qpstream->errnum = (errno) ? errno : QP_E_CANT_READ;
return QP_ERROR;
}
stream->buffer[0] = (char) c;
*bufptr = stream->buffer;
*sizeptr = 1;
return (c == '\n') ? QP_FULL : QP_PART;
}
static int ar_close(qpstream)
QP_stream *qpstream;
{
register ArHandle stream = (ArHandle) qpstream;
(void)fclose(stream->archive_stream);
Free(stream);
return QP_SUCCESS;
}
/* strpadeql(str, pad, len) is true when the NUL-terminated
string str and the blank-padded counted string pad FOR len
are equal.
*/
static int strpadeql(str, pad, len)
register char *str;
register char *pad;
register int len;
{
register int chr;
while ((chr = *str++))
if (--len < 0 || *pad++ != chr)
return 0;
while (--len >= 0)
if (*pad++ != ' ')
return 0;
return 1;
}
/* strntol(str, len) converts the counted string str FOR len to
an integer; it ignores everything but digits on the assumption
that the ignored characters are padding and decoration.
*/
static long int strntol(str, len)
register char *str;
register int len;
{
register int dig;
register long int ans = 0;
while (--len >= 0)
if ((unsigned)(dig = *str++ - '0') < 10)
ans = ans*10 + dig;
return ans;
}
long QARopen(Archive, Member, StreamCode)
char *Archive;
char *Member;
QP_stream **StreamCode;
{
register ArHandle stream;
register FILE *archive_stream;
char magic[SARMAG];
long len;
struct ar_hdr header;
QP_stream *option;
*StreamCode = QP_NULL_STREAM; /* not a valid stream code */
archive_stream = fopen(Archive, "r");
if (!archive_stream) return errno;
if (fread(magic, 1, SARMAG, archive_stream) != SARMAG
|| strncmp(magic, ARMAG, SARMAG)) {
(void)fclose(archive_stream);
return ENOTARCH;
}
for (;;) {
len = fread((char*)&header, 1, sizeof header, archive_stream);
if (len <= 0) {
(void)fclose(archive_stream);
return ENOTMEMB;
} else
if (len != sizeof header
|| strncmp(header.ar_fmag, ARFMAG, sizeof header.ar_fmag)) {
(void)fclose(archive_stream);
return ENOTARCH;
}
len = strntol(header.ar_size, sizeof header.ar_size);
if (strpadeql(Member, header.ar_name, sizeof header.ar_name)) {
stream = Malloc(ArHandle, sizeof *stream);
if (!stream) {
(void)fclose(archive_stream);
return ENOMEM;
}
stream->counter = len;
stream->archive_stream = archive_stream;
/* we've opened Archive, found Member, allocated
and initialised an ArHandle to give Prolog.
Now we have to talk Prolog into accepting it.
*/
/* get default stream options */
option = &stream->qpinfo;
QU_stream_param(Archive, QP_READ, QP_DELIM_LF, option);
/* modify appropriate options */
option->max_reclen = 1;
option->read = ar_read;
option->close = ar_close;
option->seek_type = QP_SEEK_ERROR;
/* set Prolog system fields and register the stream */
QP_prepare_stream(&stream->qpinfo,
(unsigned char *)stream->buffer);
if (QP_register_stream(&stream->qpinfo) == QP_ERROR) {
(void) ar_close(&stream->qpinfo);
return EMFILE;
}
*StreamCode = &stream->qpinfo;
return 0;
}
/* This is not the member we're looking for. Skip it. */
if (len&1) len++;
if (fseek(archive_stream, len, 1) < 0) {
(void)fclose(archive_stream);
return ENOTARCH;
}
}
}
|
mclumd/Alfred
|
quintus_prolog/quintus3.5/generic/qplib3.5/library/aropen.c
|
aropen.c
|
c
| 6,148
|
c
|
en
|
code
| 2
|
github-code
|
19
|
10754760158
|
#include "primpl.h"
#include <sys/timeb.h>
struct _MDLock _pr_ioq_lock;
HINSTANCE _pr_hInstance = NULL;
char * _pr_top_of_task_stack;
_PRInterruptTable _pr_interruptTable[] = { { 0 } };
/*
*-----------------------------------------------------------------------
*
* PR_Now --
*
* Returns the current time in microseconds since the epoch.
* The epoch is midnight January 1, 1970 GMT.
* The implementation is machine dependent. This is the
* implementation for Windows.
* Cf. time_t time(time_t *tp)
*
*-----------------------------------------------------------------------
*/
#if defined(HAVE_WATCOM_BUG_2)
PRTime __pascal __export __loadds
#else
PR_IMPLEMENT(PRTime)
#endif
PR_Now(void)
{
PRInt64 s, ms, ms2us, s2us;
struct timeb b;
ftime(&b);
LL_I2L(ms2us, PR_USEC_PER_MSEC);
LL_I2L(s2us, PR_USEC_PER_SEC);
LL_I2L(s, b.time);
LL_I2L(ms, (PRInt32)b.millitm);
LL_MUL(ms, ms, ms2us);
LL_MUL(s, s, s2us);
LL_ADD(s, s, ms);
return s;
}
char *_PR_MD_GET_ENV(const char *name)
{
return NULL;
}
PRIntn
_PR_MD_PUT_ENV(const char *name)
{
return NULL;
}
int CALLBACK LibMain( HINSTANCE hInst, WORD wDataSeg,
WORD cbHeapSize, LPSTR lpszCmdLine )
{
_pr_hInstance = hInst;
return TRUE;
}
void
_PR_MD_EARLY_INIT()
{
_tzset();
return;
}
void
_PR_MD_WAKEUP_CPUS( void )
{
return;
}
|
thalium/icebox
|
third_party/virtualbox/src/libs/xpcom18a4/nsprpub/pr/src/md/windows/w16null.c
|
w16null.c
|
c
| 1,468
|
c
|
en
|
code
| 550
|
github-code
|
19
|
15331493961
|
#include "defs.h"
#include "complaints.h"
#include "gdb_assert.h"
#include "command.h"
#include "gdbcmd.h"
extern void _initialize_complaints (void);
/* Should each complaint message be self explanatory, or should we assume that
a series of complaints is being produced? */
/* case 1: First message of a series that must
start off with explanation. case 2: Subsequent message of a series
that needs no explanation (the user already knows we have a problem
so we can just state our piece). */
enum complaint_series {
/* Isolated self explanatory message. */
ISOLATED_MESSAGE,
/* First message of a series, includes an explanation. */
FIRST_MESSAGE,
/* First message of a series, but does not need to include any sort
of explanation. */
SHORT_FIRST_MESSAGE,
/* Subsequent message of a series that needs no explanation (the
user already knows we have a problem so we can just state our
piece). */
SUBSEQUENT_MESSAGE
};
/* Structure to manage complaints about symbol file contents. */
struct complain
{
const char *file;
int line;
const char *fmt;
int counter;
struct complain *next;
};
/* The explanatory message that should accompany the complaint. The
message is in two parts - pre and post - that are printed around
the complaint text. */
struct explanation
{
const char *prefix;
const char *postfix;
};
struct complaints
{
struct complain *root;
/* Should each complaint be self explanatory, or should we assume
that a series of complaints is being produced? case 0: Isolated
self explanatory message. case 1: First message of a series that
must start off with explanation. case 2: Subsequent message of a
series that needs no explanation (the user already knows we have
a problem so we can just state our piece). */
int series;
/* The explanatory messages that should accompany the complaint.
NOTE: cagney/2002-08-14: In a desperate attempt at being vaguely
i18n friendly, this is an array of two messages. When present,
the PRE and POST EXPLANATION[SERIES] are used to wrap the
message. */
const struct explanation *explanation;
};
static struct complain complaint_sentinel;
/* The symbol table complaint table. */
static struct explanation symfile_explanations[] = {
{ "During symbol reading, ", "." },
{ "During symbol reading...", "..."},
{ "", "..."},
{ "", "..."},
{ NULL, NULL }
};
static struct complaints symfile_complaint_book = {
&complaint_sentinel,
0,
symfile_explanations
};
struct complaints *symfile_complaints = &symfile_complaint_book;
/* Wrapper function to, on-demand, fill in a complaints object. */
static struct complaints *
get_complaints (struct complaints **c)
{
if ((*c) != NULL)
return (*c);
(*c) = XMALLOC (struct complaints);
(*c)->root = &complaint_sentinel;
(*c)->series = ISOLATED_MESSAGE;
(*c)->explanation = NULL;
return (*c);
}
static struct complain *
find_complaint (struct complaints *complaints, const char *file,
int line, const char *fmt)
{
struct complain *complaint;
/* Find the complaint in the table. A more efficient search
algorithm (based on hash table or something) could be used. But
that can wait until someone shows evidence that this lookup is
a real bottle neck. */
for (complaint = complaints->root;
complaint != NULL;
complaint = complaint->next)
{
if (complaint->fmt == fmt
&& complaint->file == file
&& complaint->line == line)
return complaint;
}
/* Oops not seen before, fill in a new complaint. */
complaint = XMALLOC (struct complain);
complaint->fmt = fmt;
complaint->file = file;
complaint->line = line;
complaint->counter = 0;
complaint->next = NULL;
/* File it, return it. */
complaint->next = complaints->root;
complaints->root = complaint;
return complaint;
}
/* How many complaints about a particular thing should be printed
before we stop whining about it? Default is no whining at all,
since so many systems have ill-constructed symbol files. */
static unsigned int stop_whining = 0;
/* Print a complaint, and link the complaint block into a chain for
later handling. */
static void
vcomplaint (struct complaints **c, const char *file, int line, const char *fmt,
va_list args)
{
struct complaints *complaints = get_complaints (c);
struct complain *complaint = find_complaint (complaints, file, line, fmt);
enum complaint_series series;
gdb_assert (complaints != NULL);
complaint->counter++;
if (complaint->counter > stop_whining)
return;
if (info_verbose)
series = SUBSEQUENT_MESSAGE;
else
series = complaints->series;
if (complaint->file != NULL)
internal_vwarning (complaint->file, complaint->line, complaint->fmt, args);
else if (deprecated_warning_hook)
(*deprecated_warning_hook) (complaint->fmt, args);
else
{
if (complaints->explanation == NULL)
/* A [v]warning() call always appends a newline. */
vwarning (complaint->fmt, args);
else
{
char *msg;
struct cleanup *cleanups;
msg = xstrvprintf (complaint->fmt, args);
cleanups = make_cleanup (xfree, msg);
wrap_here ("");
if (series != SUBSEQUENT_MESSAGE)
begin_line ();
fprintf_filtered (gdb_stderr, "%s%s%s",
complaints->explanation[series].prefix, msg,
complaints->explanation[series].postfix);
/* Force a line-break after any isolated message. For the
other cases, clear_complaints() takes care of any missing
trailing newline, the wrap_here() is just a hint. */
if (series == ISOLATED_MESSAGE)
/* It would be really nice to use begin_line() here.
Unfortunately that function doesn't track GDB_STDERR and
consequently will sometimes supress a line when it
shouldn't. */
fputs_filtered ("\n", gdb_stderr);
else
wrap_here ("");
do_cleanups (cleanups);
}
}
switch (series)
{
case ISOLATED_MESSAGE:
break;
case FIRST_MESSAGE:
complaints->series = SUBSEQUENT_MESSAGE;
break;
case SUBSEQUENT_MESSAGE:
case SHORT_FIRST_MESSAGE:
complaints->series = SUBSEQUENT_MESSAGE;
break;
}
/* If GDB dumps core, we'd like to see the complaints first.
Presumably GDB will not be sending so many complaints that this
becomes a performance hog. */
gdb_flush (gdb_stderr);
}
void
complaint (struct complaints **complaints, const char *fmt, ...)
{
va_list args;
va_start (args, fmt);
vcomplaint (complaints, NULL/*file*/, 0/*line*/, fmt, args);
va_end (args);
}
void
internal_complaint (struct complaints **complaints, const char *file,
int line, const char *fmt, ...)
{
va_list args;
va_start (args, fmt);
vcomplaint (complaints, file, line, fmt, args);
va_end (args);
}
/* Clear out / initialize all complaint counters that have ever been
incremented. If LESS_VERBOSE is 1, be less verbose about
successive complaints, since the messages are appearing all
together during a command that is reporting a contiguous block of
complaints (rather than being interleaved with other messages). If
noisy is 1, we are in a noisy command, and our caller will print
enough context for the user to figure it out. */
void
clear_complaints (struct complaints **c, int less_verbose, int noisy)
{
struct complaints *complaints = get_complaints (c);
struct complain *p;
for (p = complaints->root; p != NULL; p = p->next)
{
p->counter = 0;
}
switch (complaints->series)
{
case FIRST_MESSAGE:
/* Haven't yet printed anything. */
break;
case SHORT_FIRST_MESSAGE:
/* Haven't yet printed anything. */
break;
case ISOLATED_MESSAGE:
/* The code above, always forces a line-break. No need to do it
here. */
break;
case SUBSEQUENT_MESSAGE:
/* It would be really nice to use begin_line() here.
Unfortunately that function doesn't track GDB_STDERR and
consequently will sometimes supress a line when it shouldn't. */
fputs_unfiltered ("\n", gdb_stderr);
break;
default:
internal_error (__FILE__, __LINE__, "bad switch");
}
if (!less_verbose)
complaints->series = ISOLATED_MESSAGE;
else if (!noisy)
complaints->series = FIRST_MESSAGE;
else
complaints->series = SHORT_FIRST_MESSAGE;
}
void
_initialize_complaints (void)
{
add_setshow_zinteger_cmd ("complaints", class_support, &stop_whining, "\
Set max number of complaints about incorrect symbols.", "\
Show max number of complaints about incorrect symbols.", NULL, "\
Max number of complaints about incorrect symbols is %s.",
NULL, NULL,
&setlist, &showlist);
}
|
openbsd/src
|
gnu/usr.bin/binutils/gdb/complaints.c
|
complaints.c
|
c
| 8,781
|
c
|
en
|
code
| 2,915
|
github-code
|
19
|
34397885781
|
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
//funciรณn para la comunicaciรณn con el socket creado
int comunicacion(int puerto, char* ip, char *arch);
void menu();
void busqueda(int opc);
char** archivos;
int main(int argc, char *argv[]){
if(argc != 3){
printf("Favor de ingresa el puerto, direcion IP\n");
exit(-1);
}
// Inicializacion del puerto
//int puerto = atoi(argv[1]);
//Mostramos el menu que nos regresara los nombres de los archivos que buscamos
archivos = malloc(sizeof(char*)*100);
menu();
/* for (int i = 0; strcmp(archivos[i],"0000"); i++){
printf("%s\n", archivos[i]);
}
/*Hacemos la comunicacion
if(comunicacion(puerto, argv[2],argv[3]) != 0){
printf("Error fatal");
exit(-1);
}
printf("Envio exitoso\n");*/
return 0;
}
void menu(){
int opc = 0;
int ban = 1;
/* printf("Que tipo de archivo es el que desea enviar?\n1 .txt\n2 .pdf\n3 .jpg \n4 .mp3\n");
fflush(stdin);
scanf("%d",&opc);
while (ban)
{
switch (opc)
{
//caso de .txt
case 1:
printf("busqueda de archivos .txt ");
busqueda(opc);
ban = 0;
break;
//caso de .pdf
case 2:
printf("busqueda de archivos .pdf ");
busqueda(opc);
ban = 0;
break;
//caso de .jpg
case 3:
printf("busqueda de archivos .jpg ");
busqueda(opc);
ban = 0;
break;
//caso de .mp3
case 4:
printf("busqueda de archivos .mp3 ");
busqueda(opc);
ban = 0;
break;
default:
printf("elija una opcion valida");
break;
}
}
*/
}
void busqueda(int opc){
for (int i = 0 ; i != 5 ; i++)
strcpy(archivos[i],strcat("archivo",(char)i));
strcpy(archivos[5],"0000");
}
int comunicacion(int puerto, char* ip, char *arch){
// DECLARACION DE LAS VARIABLES UTILIZADAS DENTRO LA RECEPCION DE LA INFORMACION POR PARTE DEL CLIENTE
/** Variable para guardar canal de conexion */
int id_canal;
/** Variable para almacenar el tamano de la estructura del cliente*/
socklen_t tamano_cliente = sizeof(struct sockaddr_in);
/** Variable para guardar la cantidad de bytes enviados */
int bytes_enviados;
/** Variable para guardar la cantidad de bytes recibidos */
int bytes_recibidos;
/** Variable para guardar el tamaรฑo del buffer */
int BUFFER_SIZE = 250;
/** Variable para guardar la informacion recibida y enviada por el socket */
char bufferEnv[BUFFER_SIZE];
char bufferRec[BUFFER_SIZE];
/** Descriptor el cuรกl tendra 0 si fue creado satisfactoriamente o 0 en caso contrario */
int fd_socket;
/** Estructura el cual se llenara con la informacion del servidor */
struct sockaddr_in servidor;
/** Estructura el cual se llenara con la informacion del servidor */
struct sockaddr_in cliente;
/*------------------------------------*/
/*-----INICIALIZACION DEL SOCKET -----*/
/*------------------------------------*/
if((fd_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1){
printf("Error al crear el socket\n");
return -1;
}
// Inicializacion de la familia de la direccion
servidor.sin_family = AF_INET;
servidor.sin_port = htons(puerto);
// Inicializacion de la direccion del socket
inet_aton(ip,&servidor.sin_addr);
FILE *archivo = fopen(arch, "rb"); // Apuntador para el manejo del archivo
if (archivo == NULL) {
printf("El archivo [%s] no existe\n", arch);
return -1;
}
/*-----------------------------*/
/*-----CONEXION AL SOCKET -----*/
/*-----------------------------*/
if(connect(fd_socket, (struct sockaddr*) &servidor, sizeof(struct sockaddr)) == -1){
printf("Error al conectarse al socket\n");
fclose(archivo);
return -1;
}
printf("Conexion establecida con el servidor\n");
if((bytes_enviados = send(fd_socket, arch, strlen(arch) ,0)) == -1){
printf("Error al enviar el nombre del archivo\n");
fclose(archivo);
return -1;
}
if((bytes_recibidos = recv(fd_socket, bufferRec, sizeof(bufferRec), 0))==-1){
printf("Error en el recv()\n");
fclose(archivo);
return -1;
}
bufferRec[bytes_recibidos] = '\0';
if (strcmp(bufferRec, "ACK") != 0) {
printf("El servidor no pudo aceptar\n");
close(fd_socket);
fclose(archivo);
return -1;
}
int contador=0;
while (!feof(archivo)) {
// LECTURA CONTENIDO ARCHIVO
if (!fread(&bufferEnv,sizeof(char),BUFFER_SIZE, archivo)) {
break;
}
/*----- ENVIO DE INFORMACION AL SOCKET -----*/
if((bytes_enviados = send(fd_socket, bufferEnv, sizeof(bufferEnv) ,0)) == -1){
printf("Error al enviar el mensaje\n");
fclose(archivo);
return -1;
}
//contador++;
//printf("Contador: %d, Bytes enviados: %d ,Contenido BufferEnv: %s\n",contador,bytes_enviados,bufferEnv);
/*------ RECEPCION DEL MENSAJE DEL SOCKET ------*/
if((bytes_recibidos = recv(fd_socket, bufferRec, sizeof(bufferRec), 0))==-1){
printf("Error en el recv()\n");
fclose(archivo);
return -1;
}
bufferRec[bytes_recibidos] = '\0';
printf("%s\n", bufferRec);
if (strcmp(bufferRec, "ACK") != 0) {
printf("Error al rercibir el contenido del archivo\n");
close(fd_socket);
fclose(archivo);
exit(0);
}
memset(bufferEnv,0,BUFFER_SIZE);
memset(bufferRec,0,BUFFER_SIZE);
}
strcpy(bufferEnv,".....");
if((bytes_enviados = send(fd_socket, bufferEnv, sizeof(bufferEnv) ,0)) == -1){
printf("Error al enviar el mensaje\n");
fclose(archivo);
return -1;
}
printf(".....\n");
fclose(archivo);
printf("Se ha terminado de enviar el archivo\n");
return 0;
}
|
Anne0w0/P2P1
|
cliente/client.c
|
client.c
|
c
| 6,409
|
c
|
es
|
code
| 0
|
github-code
|
19
|
20676558928
|
//output for static keyword
#include<stdio.h>
void f1()
{
static int b=0;
printf("b = %d\n", b);
b++;
}
int main()
{
f1();
f1();
f1();
f1();
}
/*
$ ./static_stack
b = 0
b = 1
b = 2
b = 3
*/
|
sonusonali/C-Programs
|
static_stack.c
|
static_stack.c
|
c
| 213
|
c
|
en
|
code
| 0
|
github-code
|
19
|
7631368961
|
#include <stdio.h>
#if 1
#include "lua.h"
#include "iglobal.h"
#include "itable.h"
#include "idrv.h"
#endif
#include <iup.h>
//printf("gggg\n"); PrintListItems(IupGetHandle("list_analyze"));
static void PrintListItems(Ihandle *e)
{
char *index = NULL;
Itable *it = env(e);
while ((index=iupTableNext(it, index)) != NULL)
printf("index: %s value: %s\n", index, (char*) iupTableGet(it, index));
}
Ihandle *dlg, *bt, *bt2;
Ihandle *list1, *list2;
int list()
{
PrintListItems(list1);
return IUP_DEFAULT;
}
int list2_cb()
{
PrintListItems(list2);
return IUP_DEFAULT;
}
int main (void)
{
Ihandle *frame1, *frame2;
IupOpen ();
list1 = IupList ("list_act");
IupSetHandle("list1", list1);
IupSetAttribute(list1, "1", " Anรกlise Geomรฉtrica ");
IupSetAttribute(list1, "2", " Anรกlise Numรฉrica ");
//IupSetAttribute(list1, "SIZE", "80");
IupSetAttribute(list1, "BGCOLOR", "255 255 255");
//IupSetAttribute(list1, "DROPDOWN", "YES");
IupSetAttribute(list1, "FGCOLOR", "0 0 0");
IupSetAttribute(list1, "VALUE", "1");
IupSetAttribute(list1, "VISIBLE", "YES");
IupSetAttribute(list1, "VISIBLE_ITEMS", "2");
IupSetAttribute(list1, "TIP", "Modo de Anรกlise");
IupSetAttribute(list1, "ACTIVE", "YES");
IupSetAttribute(list1, "EXPAND", "YES");
list2 = IupList ("list_act");
IupSetHandle("list2", list2);
IupSetAttributes(list2, "1=1, 2=2, 3=C, 4=D, SIZE=EIGHTHxEIGHTH, DROPDOWN=YES");
bt = IupButton("List", "list");
IupSetFunction("list", (Icallback) list);
bt2 = IupButton("List2", "list2_cb");
IupSetFunction("list2_cb", (Icallback) list2_cb);
frame2 = IupFrame(list2);
IupSetAttribute(frame2, IUP_TITLE, "funciona?");
frame1 = IupFrame(IupVbox(list1, frame2, bt, bt2, NULL));
dlg = IupDialog(frame1);
IupSetAttribute (dlg, IUP_TITLE, "IupList Example");
IupShowXY (dlg, IUP_CENTER, IUP_CENTER);
IupSetAttribute(list2, "VALUE", "2");
IupMainLoop ();
IupClose ();
return 0;
}
|
ewmailing/IupNext
|
iup2/test/iuplist/value1.c
|
value1.c
|
c
| 1,998
|
c
|
en
|
code
| 9
|
github-code
|
19
|
39571710822
|
#ifndef IXIS_IMCS01_DRIVER_H
#define IXIS_IMCS01_DRIVER_H
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <vector>
#include <string>
#include <mutex>
#include <termios.h>
#include "urbtc.h"
#include "urobotc.h"
#define JOINT_INDEX_REAR_RIGHT 0
#define JOINT_INDEX_REAR_LEFT 1
#define JOINT_INDEX_FRONT 2
template<typename N, typename M>
inline double MIN(const N& a, const M& b)
{
return a < b ? a : b;
}
template<typename N, typename M>
inline double MAX(const N& a, const M& b)
{
return a > b ? a : b;
}
template<typename T>
inline double NORMALIZE(const T& z)
{
return atan2(sin(z), cos(z));
}
enum class RunningState {
FORWARD,
FORWARD_STOP,
BACK,
BACK_STOP,
OTHERWISE
};
// RunningMode means switch of Handle of car.
enum class RunningMode {
FORWARD,
BACK
};
class IxisImcs01Driver
{
public:
IxisImcs01Driver(std::string port_name);
~IxisImcs01Driver();
int update();
sensor_msgs::JointState getJointState();
int controlRearWheel(double rear_speed);
protected:
int openPort(std::string port_name);
int closePort();
int setImcs01();
int parseEncoderTime();
int parseFrontEncoderCounts();
int parseRearEncoderCounts();
int writeOffsetCmd(RunningMode mode,
unsigned short duty);
struct uin received_data_;
std::vector<int> rear_last_encoder_counts_;
std::vector<int> rear_delta_encoder_counts_;
double delta_encoder_time_;
double last_encoder_time_;
sensor_msgs::JointState state_;
int imcs01_fd_;
RunningState running_state_;
struct ccmd cmd_ccmd_;
struct uin cmd_uin_;
termios oldtio_imcs01_;
termios newtio_imcs01_;
std::mutex communication_mutex_;
};
#endif /* IXIS_IMCS01_DRIVER_H */
|
CIR-KIT-Unit03/cirkit_unit03_robot
|
cirkit_unit03_base/include/ixis_imcs01_driver/ixis_imcs01_driver.h
|
ixis_imcs01_driver.h
|
h
| 1,722
|
c
|
en
|
code
| 0
|
github-code
|
19
|
43323825036
|
/* ============================================================ *
* bao.h *
* Martin Kilbinger 2008 *
* ============================================================ */
#ifndef __BAO_H
#define __BAO_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "pmctools/errorlist.h"
#include "pmctools/mvdens.h"
#include "pmctools/maths.h"
#include "nicaea/cmb_bao.h"
#include "param.h"
#include "wrappers.h"
#include "types.h"
#include "stdnames.h"
/* Error codes */
#define bao_base -1200
#define bao_unknown -1 + bao_base
/* Methods: each data type can have several methods to calculate the posterior */
typedef enum {distance_A, distance_d_z, distance_D_V_ratio} method_t;
#define smethod_t(i) ( \
i==distance_A ? "distance_A" : \
i==distance_d_z ? "distance_d_z" : \
i==distance_D_V_ratio ? "distance_D_V_ratio" : \
"" )
#define Nmethod_t 3
typedef struct {
char smethod[128], datname[1024], model_file[1024], sspecial[128];
method_t method;
mvdens *data;
double *z;
special_t special;
cosmo *model;
} bao_state;
functions_wrapper_t *init_functions_BAO(error **err);
void read_from_config_BAO(void **state, FILE *F, error **err);
void init_BAO(common_like *like, error **err);
double likeli_BAO(common_like *like, const double *params, error **err);
special_t special_BAO(void *state);
void print_BAO(FILE *where, void *state, error **err);
#endif
|
CosmoStat/CosmoPMC
|
wrappers/include/bao.h
|
bao.h
|
h
| 1,410
|
c
|
en
|
code
| 1
|
github-code
|
19
|
31541345189
|
/*
* This file is part of QtPollyNom.
*
* QtPollyNom 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 3 of the License, or
* (at your option) any later version.
*
* QtPollyNom 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 QtPollyNom. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef TESTEXPRESSIONBUILDER_H
#define TESTEXPRESSIONBUILDER_H
#include <memory>
#include "../Backend/constant.h"
#include "../Backend/basex.h"
#include "../Backend/expression.h"
#include "../Backend/sum.h"
#include "../Backend/product.h"
#include "../Backend/power.h"
#include "../Backend/parser.h"
using namespace Backend;
/*!
* \brief The TestExpressionBuilder class creates expressions for testing purposes.
* It is abstract.
*/
class TestExpressionBuilder
{
public:
TestExpressionBuilder() = delete;
/*!
* \brief Builds the expression representing 2.0*x.
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build01();
/*!
* \brief Builds the expression representing 2.0*x^3.0/(x-2^x).
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build02();
/*!
* \brief Builds the expression representing 2.0*(x+1.0).
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build03();
/*!
* \brief Builds the expression representing (x+1.0)^2.0.
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build04();
/*!
* \brief Builds the expression representing (x+1.0)^(x/3.0).
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build05();
/*!
* \brief Builds the expression representing x-1+2-3.
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build06();
/*!
* \brief Builds the expression representing x+1-2+3.
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build07();
/*!
* \brief Builds the expression representing x+1-4+7.
* \return An expression instance.
*/
static std::shared_ptr<Expression> Build08();
};
#endif // TESTEXPRESSIONBUILDER_H
|
tristhaus/QtPollyNom
|
BackendTest/testexpressionbuilder.h
|
testexpressionbuilder.h
|
h
| 2,580
|
c
|
en
|
code
| 0
|
github-code
|
19
|
18556448805
|
#include "pnal.h"
#include "pnet_options.h"
#include "options.h"
#include "osal_log.h"
#include <net/ethernet.h>
#include <net/if.h>
#include <netpacket/packet.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <string.h>
struct pnal_eth_handle
{
pnal_eth_callback_t * callback;
void * arg;
int socket;
os_thread_t * thread;
};
/**
* @internal
* Run a thread that listens to incoming raw Ethernet sockets.
* Delegate the actual work to thread_arg->callback
*
* This is a function to be passed into os_thread_create()
* Do not change the argument types.
*
* @param thread_arg InOut: Will be converted to pnal_eth_handle_t
*/
static void os_eth_task (void * thread_arg)
{
pnal_eth_handle_t * eth_handle = thread_arg;
ssize_t readlen;
int handled = 0;
pnal_buf_t * p = pnal_buf_alloc (PNAL_BUF_MAX_SIZE);
assert (p != NULL);
while (1)
{
readlen = recv (eth_handle->socket, p->payload, PNAL_BUF_MAX_SIZE, 0);
if (readlen == -1)
continue;
p->len = readlen;
if (eth_handle->callback != NULL)
{
handled = eth_handle->callback (eth_handle, eth_handle->arg, p);
}
else
{
handled = 0; /* Message not handled */
}
if (handled == 1)
{
p = pnal_buf_alloc (PNAL_BUF_MAX_SIZE);
assert (p != NULL);
}
}
}
pnal_eth_handle_t * pnal_eth_init (
const char * if_name,
pnal_ethertype_t receive_type,
const pnal_cfg_t * pnal_cfg,
pnal_eth_callback_t * callback,
void * arg)
{
pnal_eth_handle_t * handle;
int i;
struct ifreq ifr;
struct sockaddr_ll sll;
int ifindex;
struct timeval timeout;
struct packet_mreq mreq;
const uint8_t pn_mcast_addr[ETH_ALEN] = {0x01, 0x0e, 0xcf, 0x00, 0x00, 0x00};
const uint16_t linux_receive_type =
(receive_type == PNAL_ETHTYPE_ALL) ? ETH_P_ALL : receive_type;
handle = malloc (sizeof (pnal_eth_handle_t));
if (handle == NULL)
{
return NULL;
}
handle->arg = arg;
handle->callback = callback;
handle->socket = socket (PF_PACKET, SOCK_RAW, htons (linux_receive_type));
/* Adjust send timeout */
timeout.tv_sec = 0;
timeout.tv_usec = 1;
setsockopt (
handle->socket,
SOL_SOCKET,
SO_SNDTIMEO,
&timeout,
sizeof (timeout));
/* Send outgoing messages directly to the interface, without using Linux
* routing */
i = 1;
setsockopt (handle->socket, SOL_SOCKET, SO_DONTROUTE, &i, sizeof (i));
/* Read interface index */
strcpy (ifr.ifr_name, if_name);
ioctl (handle->socket, SIOCGIFINDEX, &ifr);
ifindex = ifr.ifr_ifindex;
/* Set flags of NIC interface */
strcpy (ifr.ifr_name, if_name);
ifr.ifr_flags = 0;
ioctl (handle->socket, SIOCGIFFLAGS, &ifr);
ifr.ifr_flags = ifr.ifr_flags | IFF_MULTICAST | IFF_BROADCAST;
if (receive_type == PNAL_ETHTYPE_ALL)
{
ifr.ifr_flags |= IFF_ALLMULTI; /* Receive all multicasts */
}
ioctl (handle->socket, SIOCSIFFLAGS, &ifr);
/* Bind socket to relevant protocol */
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifindex;
sll.sll_protocol = htons (linux_receive_type);
bind (handle->socket, (struct sockaddr *)&sll, sizeof (sll));
/* Join profinet multicast group */
mreq.mr_ifindex = ifindex;
mreq.mr_type = PACKET_HOST | PACKET_MR_MULTICAST;
mreq.mr_alen = ETH_ALEN;
memcpy (mreq.mr_address, pn_mcast_addr, ETH_ALEN);
if (
setsockopt (
handle->socket,
SOL_PACKET,
PACKET_ADD_MEMBERSHIP,
&mreq,
sizeof (mreq)) != 0)
{
LOG_WARNING (
PF_PNAL_LOG,
"PNAL(%d): Failed to join Profinet multicast group\n",
__LINE__);
}
if (handle->socket > -1)
{
handle->thread = os_thread_create (
"os_eth_task",
pnal_cfg->eth_recv_thread.prio,
pnal_cfg->eth_recv_thread.stack_size,
os_eth_task,
handle);
return handle;
}
else
{
free (handle);
return NULL;
}
}
int pnal_eth_send (pnal_eth_handle_t * handle, pnal_buf_t * buf)
{
int ret = send (handle->socket, buf->payload, buf->len, 0);
return ret;
}
|
rtlabs-com/p-net
|
src/ports/linux/pnal_eth.c
|
pnal_eth.c
|
c
| 4,191
|
c
|
en
|
code
| 383
|
github-code
|
19
|
50510396593
|
#include "graph.h"
#include <math.h>
// This function initializes an adjacency list for
// a graph.
//
// Note that adj list is an array of """adj_node_t*""" which is passed
// in by reference.
// That is, you are passing in a pointer (i.e, *) to an array (i.e., *)
// of adj_node_t*, which is why list is of type adj_node_t***
void init_adj_list(adj_node_t ***list, int rows)
{
//allocate memory and set it all equal to NULL
*list = (adj_node_t **)malloc(sizeof(adj_node_t *) * rows);
for (int i = 0; i < rows; i++)
{
(*list)[i] = NULL;
}
}
// This function creates a new adj_node_t node
// and initializes it with node->vid = vid
// and node->next = NULL;
// The function then returns this node
adj_node_t *create_node(int vid)
{
//create a new node
adj_node_t *newnode = (adj_node_t*)malloc(sizeof(adj_node_t));
newnode->vid = vid;
newnode->next = NULL;
return newnode;
}
// Pass in the list and the row to which you need to add a new node
// First check that the adjacency list for the current row is not
// empty (i.e., NULL). If it is NULL, it is the first adjacent node.
// Otherwise, traverse the list until you reach the end, and then add
// the new node
void add_node(adj_node_t** list, int row, adj_node_t* node)
{
//Create a temp
adj_node_t *temp = list[row];
//while not empty
if(temp != NULL)
{
//get to the end of temp
for (; temp->next != NULL; temp = temp->next);
temp->next = node;
}
//if empty
else
{
list[row] = node;
}
}
// deqeueu a node from a queue
// and return the vertex id of the first member
// when list returns, it points to the next member in the queue
int remove_node(adj_node_t **list)
{
//create temp node to keep values in
//save vid into id and return it
//then free temp
adj_node_t *temp = *list;
int id = temp->vid;
*list = temp->next;
free(temp);
return id;
}
// This function constructs an adjacency list for a graph.
//
// adj_mat is a 2D array that represents the adjacency matrix
//
// list is passed in by reference from the main function so that
// it can be malloc'd via the init_adj_list function (see aobve)
//
// After initializing it go through each row and add its adjacent
// nodes
void construct_adj_list(int **adj_mat, int rows, int cols, adj_node_t ***list)
{
// verify that the adj matrix is correct
if(rows != cols) {
printf("Adjacency matrix is not square\n");
exit(EXIT_FAILURE);
}
init_adj_list(list, rows);
//create the adj list
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
//if there's a one in the adj matrix then use create with vid j
//and add node with row i
if(adj_mat[i][j] == 1)
{
adj_node_t *newnode = create_node(j);
add_node(*list, i, newnode);
}
}
}
}
// This takes in an adjacency ilst and prints out the list
void print_adj_list(adj_node_t **list, int rows)
{
assert(list);
printf("---- Print Adj. List ----\n");
for(int i = 0; i < rows; i++) {
printf("|%d| -> ", i);
adj_node_t* next = list[i];
while(next != NULL) {
printf("%d -> ", next->vid);
next = next->next;
}
printf("END\n");
}
printf("--------\n\n");
}
void free_adj_list(adj_node_t **list, int rows)
{
// free the list
// for each row and until the end of the list
for(int i = 0; i < rows; i++)
{
adj_node_t *newnode = list[i];
adj_node_t *temp;
while(newnode != NULL)
{
temp = newnode->next;
free(newnode);
newnode = temp;
}
}
//free the final list
free(list);
}
void print_bfs_result(int rows, int *color, int *distance, int *parent)
{
assert(color);
assert(distance);
assert(parent);
printf("---- Print BFS Result ----\n");
printf("Vert\tCol\tDis\tParent\n");
for(int i = 0; i < rows; i++) {
printf("%d\t%d\t%d\t%d\n", i, color[i], distance[i], parent[i]);
}
printf("--------\n\n");
}
// Do BFS here, given the source node and the
// graph's adjacency list
int bfs(adj_node_t **list, int rows, int source,
int *color, int *distance, int *parent)
{
// Make sure the source is a valid vertex
if(source >= rows) {
printf("Invalid source vertex\n");
return 0;
}
// Make sure the adjacency list is not empty
if(list == NULL) {
printf("There is nothing in the adjacency list\n");
return 0;
}
// Make sure all these are properly allocated
assert(color);
assert(distance);
assert(parent);
// Part 5 - Fill in the rest of this function
//initialize the arrays
for(int i = 0; i < rows; i++)
{
color[i] = 0;
distance[i] = INFINITY;
parent[i] = -1;
}
//intialize the source
color[source] = 1;
distance[source] = 0;
parent[source] = -1;
//create Q
adj_node_t *Q = create_node(source);
adj_node_t *node = Q;
while(Q != NULL)
{
int current = remove_node(&Q);
for(adj_node_t *newnode = list[current]; newnode != NULL; newnode = newnode->next)
{
//add if not already visited
if(color[newnode->vid] == 0)
{
color[newnode->vid] = 1;
parent[newnode->vid] = current;
//update distance
if(distance[newnode->vid] > (distance[current] + 1))
{
distance[newnode->vid] = distance[current] + 1;
}
adj_node_t *anothernode = create_node(newnode->vid);
if(Q != NULL)
{
node->next = anothernode;
node = node->next;
}
else{
Q = anothernode;
node = Q;
}
}
}
}
#if DEBUG
print_bfs_result(rows, color, distance, parent);
#endif
return 0;
}
|
olivialpannell/school_work
|
ProgrammingConcepts/CS330/hw04/graph.c
|
graph.c
|
c
| 6,209
|
c
|
en
|
code
| 0
|
github-code
|
19
|
19309272199
|
#include <string.h>
unsigned char xkey[17] = { 0x6E, 0xC2, 0xE1, 0x2D, 0x05, 0xF8, 0x68, 0x71, 0xAF, 0x76, 0x68, 0xFD, 0xF8, 0x76, 0xA3, 0x82, 0x00 };
int seed = 0x1337;
int rand()
{
seed = 214013 * seed + 0x269EC3;
return (seed >> 16) & 0x7FFF;
}
unsigned int rol(unsigned char a1, char a2)
{
return (a1 << a2) | ((unsigned int)a1 >> (8 - a2));
}
int ror(unsigned int a1, char a2)
{
return (a1 >> a2) | (a1 << (32 - a2));
}
int main(int argc, char *argv[])
{
unsigned char input[16];
klee_make_symbolic(input, sizeof(input), "input");
for ( int i = 0; i < 16; ++i )
input[i] ^= xkey[i];
int v6 = 0x12345678;
for ( int i = 0; i < 13; ++i ) {
input[i] = rol(input[i], 3);
*(unsigned int*)&input[i] ^= v6;
int v8 = ror(v6, 5);
v6 = rand() % 13371337 ^ v8;
}
if ( !memcmp("0p3n5354m3...=.=", input, 16) )
klee_assert(0);
return 0;
}
|
L4ys/LazyKLEE
|
example/TMCTF-2017-REV400/solve.c
|
solve.c
|
c
| 917
|
c
|
en
|
code
| 66
|
github-code
|
19
|
27071496017
|
#ifndef __SpinnerAdapter_H__
#define __SpinnerAdapter_H__
namespace NSDEVICE
{
class BaseAdapter;
class SpinnerAdapter : public Adapter
{
friend BaseAdapter;
public:
virtual ~SpinnerAdapter()
{
}
virtual View* getDropDownView(int position, View* convertView, ViewGroup* parent) = 0;
protected:
SpinnerAdapter()
{
}
private:
SpinnerAdapter(NKrossFriend* vNKrossFriend) :
Adapter(vNKrossFriend)
{
}
};
} // End namespace
#endif
|
wengerclub/aXplorience
|
app/src/main/cpp/include/nclozer/nkross/device/widget/SpinnerAdapter.h
|
SpinnerAdapter.h
|
h
| 483
|
c
|
en
|
code
| 0
|
github-code
|
19
|
72018524204
|
//
// AppDelegate.h
// ArchiPeda
//
// Created by Jeffrey Delawder Jr on 10/13/12.
// Copyright (c) 2012 Jeffrey Delawder Jr. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
Glchriste/Architecture_Pedagogical_App
|
ArchiPeda/AppDelegate.h
|
AppDelegate.h
|
h
| 296
|
c
|
en
|
code
| 0
|
github-code
|
19
|
36167437639
|
#include "Node.h"
template <typename T>
class ListaOrdenada
{
private:
Node<T> *Head;
int N;
public:
bool insert(T X)
{
Node<T> *P = Node<T> ::MontaNode(X);
if (!P)
return false;
Node<T> **K = &Head;
int M = X.Mat;
while ((*K) && ((*K)->D).Mat <= M)
{
K = &((*K)->next);
}
P->next = *K;
*K = P;
N++;
return true;
}
T erase(int X)
{
T R;
Node<T> *Aux;
Node<T> **P = &Head;
while ((*P) && ((*P)->D).Mat != X)
{
P = &((*P)->next);
}
if (*P)
{
Aux = *P;
*P = (Aux->next);
R = Node<T> ::DesmontaNode(Aux);
N--;
}
}
bool search(int m, T *PX)
{
Node<T> *P = Head;
while (P && (P->D).Mat < m)
{ // procura ate achar ou atรฉ acabar
P = P->next;
}
if (P && m > (P->D).Mat)
{
// achou o elemento
*PX = P->D;
return true;
}
return false;
}
ListaOrdenada(/* args */)
{
Head = 0;
N = 0;
}
~ListaOrdenada()
{
Node<T> *P;
while (Head)
{
P = Head->next;
Node<T> ::DesmontaNode(Head);
Head = P;
}
}
};
|
Raikyr4/Estrutura_de_Dados
|
Lista/ListaOrdenada.h
|
ListaOrdenada.h
|
h
| 1,400
|
c
|
en
|
code
| 1
|
github-code
|
19
|
2760575202
|
#pragma once
#include <optional>
#include <QString>
#include <QVariant>
#include <mpv/client.h>
// ========================================================
// MPV type conversion
// ========================================================
namespace mpv_type {
// mpv/C type mapping
template<typename T>
struct format {
// static mpv_format id;
};
template<mpv_format ID>
struct ctype {
// using type;
};
// Generic type conversion template
template<typename T>
struct convert {
using mpv_type = T;
static constexpr std::optional<T> from(mpv_type *v)
{
return *v;
}
static constexpr std::optional<T> to(const T &v)
{
return v;
}
};
// Typed access functions for properties
template<typename T>
struct property {
static inline std::optional<T> get(mpv_handle *mpv, const char *name) {
typename convert<T>::mpv_type res;
if (mpv_get_property(mpv, name, format<T>::id, &res) < 0)
return {};
return convert<T>::from(&res);
}
static inline bool set(mpv_handle *mpv, const char *name, const T &value) {
auto mv = convert<T>::to(value);
if (!mv)
return false;
return mpv_set_property(mpv, name, format<T>::id, mv.operator->()) >= 0;
}
static inline std::optional<T> unpack_event(mpv_event_property *ep) {
if (ep->format != format<T>::id)
return {};
return convert<T>::from(reinterpret_cast<typename convert<T>::mpv_type*>(ep->data));
}
};
// ------------------------------------------------------------------
// Concrete Type Specializations
#define MPV_TYPE(type_, fmt) \
template<> struct format<type_> { static constexpr mpv_format id = fmt; }; \
template<> struct ctype<fmt> { using type = type_; };
MPV_TYPE(bool, MPV_FORMAT_FLAG)
template<> struct convert<bool> {
using mpv_type = int;
static constexpr std::optional<bool> from(int *v)
{
return *v == 1;
}
static constexpr std::optional<int> to(const bool &v)
{
return v ? 1 : 0;
}
};
MPV_TYPE(qint64, MPV_FORMAT_INT64)
MPV_TYPE(double, MPV_FORMAT_DOUBLE)
MPV_TYPE(QString, MPV_FORMAT_STRING)
template<> struct convert<QString> {
using mpv_type = char *;
static inline std::optional<QString> from(char **v)
{
return QString::fromUtf8(*v);
}
static inline std::optional<char*> to(const QString &v)
{
return v.toUtf8().data();
}
};
MPV_TYPE(QVariant, MPV_FORMAT_NODE)
template<> struct convert<QVariant> {
struct AutoNode : mpv_node{
AutoNode();
AutoNode(AutoNode &&);
~AutoNode();
};
using mpv_type = AutoNode;
static std::optional<QVariant> from(AutoNode *);
static std::optional<AutoNode> to(const QVariant &);
};
#undef MPV_TYPE
}
|
Orochimarufan/Midoku
|
src/mpv/mpv_type.h
|
mpv_type.h
|
h
| 2,815
|
c
|
en
|
code
| 0
|
github-code
|
19
|
29063631843
|
/*
* Copyright 2014-present Alibaba Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INDEXLIB_PLUGIN_PLUGINS_AITHETA_UTIL_PARALLEL_MERGE_TASK_PARALLEL_MERGE_UTIL_H
#define INDEXLIB_PLUGIN_PLUGINS_AITHETA_UTIL_PARALLEL_MERGE_TASK_PARALLEL_MERGE_UTIL_H
#include "autil/legacy/jsonizable.h"
#include "indexlib/common_define.h"
#include "indexlib/index/normal/inverted_index/customized_index/index_reducer.h"
#include "indexlib_plugin/plugins/aitheta/util/indexlib_io_wrapper.h"
#include "indexlib_plugin/plugins/aitheta/common_define.h"
#include "indexlib_plugin/plugins/aitheta/segment_meta.h"
#include "indexlib_plugin/plugins/aitheta/index_segment.h"
namespace indexlib {
namespace aitheta_plugin {
struct ParallelMergeUtil {
static bool DumpSegmentMeta(const indexlib::file_system::DirectoryPtr &directory,
const indexlib::index::ParallelReduceMeta ¶llelReduceMeta);
static bool DumpOfflineIndexAttr(const indexlib::file_system::DirectoryPtr &directory,
const indexlib::index::ParallelReduceMeta ¶llelReduceMeta);
static bool LoadIndexSegments(const indexlib::file_system::DirectoryPtr &directory,
const indexlib::index::ParallelReduceMeta ¶llelReduceMeta,
const LoadType &loadType, std::vector<IndexSegmentPtr> &subIndexSgts);
private:
IE_LOG_DECLARE();
};
}
}
#endif // INDEXLIB_PLUGIN_PLUGINS_AITHETA_UTIL_PARALLEL_MERGE_TASK_PARALLEL_MERGE_UTIL_H
|
Hansonwong47/havenask
|
aios/plugins/indexlib_plugin/plugins/aitheta/util/parallel_merge/parallel_merge_util.h
|
parallel_merge_util.h
|
h
| 2,048
|
c
|
en
|
code
| null |
github-code
|
19
|
73228929642
|
/*
* Copyright (c) 2009,
* Computational Image and Simulation Technologies in Biomedicine (CISTIB),
* Universitat Pompeu Fabra (UPF), Barcelona, Spain. All rights reserved.
* See license.txt file for details.
*/
#ifndef _wxMitkMultiSliceFactory_H
#define _wxMitkMultiSliceFactory_H
#include "wxMitkWidgetsWin32Header.h"
#include "wxMitkMultiRenderWindow.h"
namespace mitk
{
/*
\brief Factory for wxMitkMultiRenderWindow
\ingroup wxMitkWidgets
\author Xavi Planes
\date 17 Oct 2007
*/
class WXMITKWIDGETS_EXPORT wxMitkMultiSliceFactory
{
public:
//!
static wxMitkMultiRenderWindow* Build(
wxWindow* parent,
wxWindowID id,
mitk::SliceNavigationController::ViewDirection direction,
int numSlices,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize );
//!
static void InitRenderWindows(
mitk::wxMitkMultiRenderWindow* window,
mitk::SliceNavigationController::ViewDirection direction,
int numSlices );
private:
};
} // namespace mitk
#endif // _wxMitkMultiSliceFactory_H
|
jakubsadura/Swiezy
|
src/Modules/wxMitk/libmodules/wxMitkWidgets/include/wxMitkMultiSliceFactory.h
|
wxMitkMultiSliceFactory.h
|
h
| 1,029
|
c
|
en
|
code
| 3
|
github-code
|
19
|
23949072973
|
/*
* Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _HARDWARE_STRUCTS_SCB_H
#define _HARDWARE_STRUCTS_SCB_H
#include "hardware/address_mapped.h"
#include "hardware/regs/m0plus.h"
// SCB == System Control Block
typedef struct {
io_ro_32 cpuid;
io_rw_32 icsr;
io_rw_32 vtor;
io_rw_32 aircr;
io_rw_32 scr;
// ...
} armv6m_scb_t;
#define scb_hw ((armv6m_scb_t *const)(PPB_BASE + M0PLUS_CPUID_OFFSET))
#endif
|
Klipper3d/klipper
|
lib/rp2040/hardware/structs/scb.h
|
scb.h
|
h
| 489
|
c
|
en
|
code
| 7,817
|
github-code
|
19
|
70257410923
|
//sgzl
#include <ansi.h>
inherit NPC;
#include "huoyannpc2.h"
void create()
{
set_name("้ญ็คผ็บข", ({ "moli hong", "guangmu tianwang", "hong", "tianwang" }) );
set("gender", "็ทๆง" );
set("long",
"้ญๅฎถๅๅฐไนไธ๏ผไฝฟไธๆๆนๅคฉ็ปๆ๏ผ็งๆไธๆไผใๅๆฐ๏ผใๆททๅ
ไผใใ\n"
"ไผ็ๆ็ ็ฉฟๆ๏ผๆ็ฅๆฏ็ปฟ๏ผ็ฅๆฏ็ขง๏ผๅคๆ็ ๏ผ่พๅฐ็ ๏ผ่พ็ซ็ ๏ผ่พๆฐด\n"
"็ ๏ผๆถๅ็ ๏ผไนๆฒ็ ๏ผๅฎ้ข็ ๏ผๅฎ้ฃ็ ใ่ฟๆ็็ ็ฉฟๆใ่ฃ
่ฝฝไนพๅคใ\n"
"ๅๅญ๏ผ่ฟๆไผไธๆขๆ๏ผๆๅผๆถๅคฉๆๅฐๆ๏ผๆฅๆๆ ๅ
๏ผ่ฝฌไธ่ฝฌไนพๅคๆๅจใ\n"
);
set("age",50);
set("title", "ๅนฟ็ฎๅคฉ็");
set("attitude", "heroism");
set("str",40);
set("int",30);
set("max_kee",1100);
set("kee",1100);
set("max_sen",1100);
set("sen",1100);
set("combat_exp",2000000);
set("daoxing",1500000);
set("force",2500);
set("max_force",1500);
set("mana",2500);
set("max_mana",1600);
set("force_factor", 80);
set("mana_factor",80);
set("eff_dx", 450000);
set("nkgain", 500);
set_skill("unarmed",150);
set_skill("yingzhaogong", 200);
set_skill("parry",200);
set_skill("dodge",200);
set_skill("spear",200);
set_skill("bawang-qiang",200);
set_skill("force",200);
set_skill("spells", 200);
set_skill("moshenbu", 200);
map_skill("dodge", "moshenbu");
map_skill("parry", "bawang-qiang");
map_skill("spear","bawang-qiang");
map_skill("unarmed", "yingzhaogong");
set("inquiry", ([
"name" : "ๅจไธๅนฟ็ฎๅคฉ็้ญ็คผ็บข๏ผๅฅๅฃ่ฐๆๅฎไธๅคฉ้จใ",
"here" : "่ฟ้ๅฐฑๆฏไธๅคฉ้จ, ๅ
ฅๅ
ๅฐฑๆฏๅคฉ็ไบใ",
]) );
setup();
carry_object("/d/obj/weapon/spear/huaji")->wield();
carry_object("/d/obj/armor/jinjia")->wear();
}
void hurting(object me, object ob)
{
int n;
remove_call_out("hurting");
if(environment(me)!=environment(ob) || !me->is_fighting()) return;
if(me->is_busy()) {
call_out("hurting",6+random(5),me,ob);
return;
}
message_vision(HIY"$nไปๆไธญๆฝๅบๆททๅ
ไผ๏ผไฝๅฃฐๅฟตไบๅ ๅฃฐๅ่ฏญ๏ผๆททๅ
ไผๅฆๅคฉ็ฝๅฐ็ฝ่ฌๅ$N็ฝฉๆฅ๏ผ\n"NOR,ob,me);
n = 10 - (int)ob->query("daoxing")/(1 + (int)me->query("daoxing") ) -
(int)ob->query("combat_exp")/(1+(int)me->query("combat_exp") );
if(random(n)){
me->start_busy( 60/ ((int)me->query_kar()+1));
ob->start_busy(60/((int)ob->query_kar()+1) +1);
message_vision("็ปๆ$N่ขซ็ฝฉไฝ๏ผ้กฟๆถ่กๅจไธๅพ๏ผ\n",ob);
}
else {
me->start_busy( 30/ ( (int)me->query_kar()+1) );
message_vision("$N็บต่บซ่ทๅฐๆททๅ
ไผ้กถ๏ผ้ช่ฟไบ่ฟไธๅปใ\n",ob);
}
call_out("hurting",6+random(5),me,ob);
}
|
mudchina/xyj2006
|
world/d/dntg/sky/npc/tianwang2.c
|
tianwang2.c
|
c
| 2,463
|
c
|
en
|
code
| 17
|
github-code
|
19
|
24337030322
|
//
// RPGiftPointV.h
// Market
//
// Created by ้ๆฅ on 15/3/25.
// Copyright (c) 2015ๅนด lunan. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>
@protocol RPGiftPointVDelegate <NSObject>
-(void)RPGiftPointVButtonPressed:(id)info;
@end
@interface RPGiftPointV : UIView<ABPeoplePickerNavigationControllerDelegate,UITextFieldDelegate>
{
UIImageView *head;
ABPeoplePickerNavigationController *personPicker;
NSString *_phoneNumber;
UITextField *personT;
UITextField *pointT;
UITextField *captchaT;
UILabel *wrongL01;
BOOL correct01;//ๅ่ฎฉไบบๆญฃ็กฎๆ ่ฏ
UILabel *wrongL02;
BOOL correct02;//็งฏๅๆญฃ็กฎๆ ่ฏ
UILabel *wrongL03;
BOOL correct03;//้ช่ฏ็ ๆญฃ็กฎๆ ่ฏ
UIButton *commitBtn;
}
@property (nonatomic, retain) id<RPGiftPointVDelegate>delegate;
@end
@interface CaptchaButton : UIButton
{
NSTimeInterval currentTime;
NSTimer *countTimer;
}
@property (nonatomic, assign) NSTimeInterval countdown;
-(void)startCount;
@end
|
XIAOXIAO8023/https---git.oschina.net-zify-woxin
|
MyMobileServiceYN/MyMobileServiceYN/Market/MaretUI/MKAboutPoint/RegiftPoint/RPGiftPointV.h
|
RPGiftPointV.h
|
h
| 1,143
|
c
|
en
|
code
| 0
|
github-code
|
19
|
42094134490
|
/*
// Copyright (c) 2010-2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifndef _STATS_PORT_H_
#define _STATS_PORT_H_
#include <inttypes.h>
enum PKT_SIZE_BIN {
PKT_SIZE_64,
PKT_SIZE_65,
PKT_SIZE_128,
PKT_SIZE_256,
PKT_SIZE_512,
PKT_SIZE_1024,
PKT_SIZE_1522,
PKT_SIZE_COUNT,
};
struct port_stats_sample {
uint64_t tsc;
uint64_t no_mbufs;
uint64_t ierrors;
uint64_t imissed;
uint64_t oerrors;
uint64_t rx_tot;
uint64_t tx_tot;
uint64_t rx_bytes;
uint64_t tx_bytes;
uint64_t tx_pkt_size[PKT_SIZE_COUNT];
};
struct port_stats {
struct port_stats_sample sample[2];
};
struct get_port_stats {
uint64_t no_mbufs_diff;
uint64_t ierrors_diff;
uint64_t imissed_diff;
uint64_t rx_bytes_diff;
uint64_t tx_bytes_diff;
uint64_t rx_pkts_diff;
uint64_t tx_pkts_diff;
uint64_t rx_tot;
uint64_t tx_tot;
uint64_t no_mbufs_tot;
uint64_t ierrors_tot;
uint64_t imissed_tot;
uint64_t last_tsc;
uint64_t prev_tsc;
};
int stats_port(uint8_t port_id, struct get_port_stats *ps);
void stats_port_init(void);
void stats_port_reset(void);
void stats_port_update(void);
uint64_t stats_port_get_ierrors(void);
uint64_t stats_port_get_imissed(void);
uint64_t stats_port_get_rx_packets(void);
uint64_t stats_port_get_tx_packets(void);
int stats_get_n_ports(void);
struct port_stats_sample *stats_get_port_stats_sample(uint32_t port_id, int l);
#endif /* _STATS_PORT_H_ */
|
opnfv/samplevnf
|
VNFs/DPPD-PROX/stats_port.h
|
stats_port.h
|
h
| 1,918
|
c
|
en
|
code
| 21
|
github-code
|
19
|
2008835792
|
/**
******************************************************************************
* ๆไปถๅ kf32a_basic_aes.c
* ไฝ ่
ChipON_AE/FAE_Group
* ็ ๆฌ V2.6
* ๆฅ ๆ 2019-11-16
* ๆ ่ฟฐ ่ฏฅๆไปถๆไพไบๅ ๅฏๆจกๅ(AE)ๅค่ฎพๅ่ฝๅฝๆฐ๏ผๅ
ๅซ๏ผ
* + AESๅค่ฎพ้
็ฝฎ
*
*********************************************************************
*/
#include "kf32a_basic_aes.h"
#include "kf32a_basic_rst.h"
#include "kf32a_basic_pclk.h"
#ifdef KF32A_Periph_aes
/* AES็งๆๅฎไน ----------------------------------------------------*/
/* AES_CTLๅฏๅญๅจ้
็ฝฎๆฉ็ */
#define AES_CTL_INIT_MASK (AES_CTL_OFBEN \
| AES_CTL_AESCS \
| AES_CTL_AESDIV \
| AES_CTL_AESRUN \
| AES_CTL_AESFIE \
| AES_CTL_AESFIC)
/**
* ##### ๅๅงๅๅ้
็ฝฎๅฝๆฐ #####
*/
/**
* ๆ่ฟฐAESๅค่ฎพๅคไฝ๏ผไฝฟ่ฝๅค่ฎพๆถ้ใ
* ่พๅ
ฅ : ๆ
* ่ฟๅ ๆ ใ
*/
void
AES_Reset ()
{
RST_CTL3_Peripheral_Reset_Enable(RST_CTL3_AESRST, TRUE);
RST_CTL3_Peripheral_Reset_Enable(RST_CTL3_AESRST, FALSE);
PCLK_CTL3_Peripheral_Clock_Enable(PCLK_CTL3_AESCLKEN, TRUE);
}
/**
* ๆ่ฟฐ AESๅค่ฎพ้
็ฝฎใ
* ่พๅ
ฅ AES: AESInitStruct: AES้
็ฝฎไฟกๆฏ
* ่ฟๅ ๆ ใ
*/
void
AES_Configuration (AES_InitTypeDef* AESInitStruct)
{
uint32_t tmpreg = 0;
CHECK_RESTRICTION(CHECK_AES_OFB(AESInitStruct->m_OFB));
CHECK_RESTRICTION(CHECK_AES_CLKSOURCE(AESInitStruct->m_ClockSelect));
CHECK_RESTRICTION(CHECK_AES_CLK_DIV(AESInitStruct->m_ClockDiv));
CHECK_RESTRICTION(CHECK_AES_RUN(AESInitStruct->m_Run));
CHECK_RESTRICTION(CHECK_AES_FINISH_INT(AESInitStruct->m_FinishIntEn));
CHECK_RESTRICTION(CHECK_AES_FINISH_INT_CLEAR(AESInitStruct->m_FinishIntClr));
/*---------------------------- AES_CTLๅฏๅญๅจ้
็ฝฎ -----------------*/
/* ๆ นๆฎ็ปๆไฝๆๅm_OFB๏ผ่ฎพ็ฝฎOFBENไฝๅ */
/* ๆ นๆฎ็ปๆไฝๆๅm_ClockSelect๏ผ่ฎพ็ฝฎAESCSไฝๅ */
/* ๆ นๆฎ็ปๆไฝๆๅm_ClockDiv๏ผ่ฎพ็ฝฎAESDIVไฝๅ */
/* ๆ นๆฎ็ปๆไฝๆๅm_Run๏ผ่ฎพ็ฝฎAESRUNไฝๅ */
/* ๆ นๆฎ็ปๆไฝๆๅm_FinishIntEn๏ผ่ฎพ็ฝฎAESFIEไฝๅ */
/* ๆ นๆฎ็ปๆไฝๆๅm_FinishIntClr๏ผ่ฎพ็ฝฎAESFICไฝๅ */
tmpreg = ((AESInitStruct->m_OFB ) | \
(AESInitStruct->m_ClockSelect) | \
(AESInitStruct->m_ClockDiv) | \
(AESInitStruct->m_Run) | \
(AESInitStruct->m_FinishIntEn) | \
(AESInitStruct->m_FinishIntClr));
AES_SFR->CTL = SFR_Config (AES_SFR->CTL,
~AES_CTL_INIT_MASK,
tmpreg);
}
/**
* ๆ่ฟฐ ๅๅงๅAES้
็ฝฎไฟกๆฏ็ปๆไฝใ
* ่พๅ
ฅ AESInitStruct: ๆๅๅพ
ๅๅงๅ็็ปๆไฝๆ้ใ
* ่ฟๅ ๆ ใ
*/
void
AES_Struct_Init (AES_InitTypeDef* AESInitStruct)
{
/* ๅๅงๅAES OFBๆจกๅผ่พๅ
ฅๆงๅถไฝ */
AESInitStruct->m_OFB = AES_OFB_DISABLE;
/* ๅๅงๅ AESๅทฅไฝๆถ้ๆบ้ๆฉไฝ */
AESInitStruct->m_ClockSelect = AES_CLK_SEL_SCLK;
/* ๅๅงๅ AESๆถ้ๅ้ขๆงๅถไฝ */
AESInitStruct->m_ClockDiv = AES_CLK_DIV_1;
/* ๅๅงๅ AES่ฟ่กไฝฟ่ฝไฝ */
AESInitStruct->m_Run = AES_RUN_DISABLE;
/* ๅๅงๅ AESๅ ๅฏๅฎๆไธญๆญไฝฟ่ฝไฝ */
AESInitStruct->m_FinishIntEn = AES_FINISH_INT_DISABLE;
/* ๅๅงๅ AESๅ ๅฏๅฎๆๆธ
้ถไฝ */
AESInitStruct->m_FinishIntClr = AES_FINISH_INT_CLEAR_DISABLE;
}
/**
* ๆ่ฟฐ AESๅฏ้ฅๅฏๅญๅจใ
* ่พๅ
ฅ KEYDATA:ไฝๅฎฝbit32
* ่ฟๅ ๆ ใ
*/
void
AES_KEY0_DATA (uint32_t DATA)
{
AES_SFR->KEY0=DATA;
}
void
AES_KEY1_DATA (uint32_t DATA)
{
AES_SFR->KEY1=DATA;
}
void
AES_KEY2_DATA (uint32_t DATA)
{
AES_SFR->KEY2=DATA;
}
void
AES_KEY3_DATA (uint32_t DATA)
{
AES_SFR->KEY3=DATA;
}
/**
* ๆ่ฟฐ AES่พๅ
ฅๅฏๅญๅจใ
* ่พๅ
ฅ INPUTDATA:ไฝๅฎฝbit32
* ่ฟๅ ๆ ใ
*/
void
AES_INPUT0_DATA (uint32_t DATA)
{
AES_SFR->INPUT0=DATA;
}
void
AES_INPUT1_DATA (uint32_t DATA)
{
AES_SFR->INPUT1=DATA;
}
void
AES_INPUT2_DATA (uint32_t DATA)
{
AES_SFR->INPUT2=DATA;
}
void
AES_INPUT3_DATA (uint32_t DATA)
{
AES_SFR->INPUT3=DATA;
}
/**
* ๆ่ฟฐ AES่พๅ
ฅๅฏๅญๅจใ
* ่พๅ
ฅ :ๆ
* ่พๅบ๏ผ OUTPUTDATA:ไฝๅฎฝbit32
* ่ฟๅ ๆ ใ
*/
uint32_t
GET_AES_OUTPUT0_DATA (void)
{
uint32_t DATA;
DATA=AES_SFR->OUTPUT0;
return DATA;
}
uint32_t
GET_AES_OUTPUT1_DATA (void)
{
uint32_t DATA;
DATA=AES_SFR->OUTPUT1;
return DATA;
}
uint32_t
GET_AES_OUTPUT2_DATA (void)
{
uint32_t DATA;
DATA=AES_SFR->OUTPUT2;
return DATA;
}
uint32_t
GET_AES_OUTPUT3_DATA (void)
{
uint32_t DATA;
DATA=AES_SFR->OUTPUT3;
return DATA;
}
FlagStatus
AES_Get_Flag_Status (void)
{
if ((AES_SFR->CTL & AES_CTL_AESFIF) != RESET)
{
/* AES ๅ ๅฏๅฎๆ */
return SET;
}
else
{
/* AES ๅ ๅฏๆชๅฎๆ */
return RESET;
}
}
/**
* ๆ่ฟฐ AESๅผๅงๅ ๅฏ
* ่พๅ
ฅ :ๆ
* ่พๅบ :ๆ
* ่ฟๅ :ๆ
*/
void
AES_Start ()
{
/* AES ๅผๅงๅ ๅฏ */
AES_SFR->CTL |= AES_CTL_AESRUN;
}
/**
* ๆ่ฟฐ AESๆธ
ๆ ๅฟไฝ
* ่พๅ
ฅ :ๆ
* ่พๅบ :ๆ
* ่ฟๅ :ๆ
*/
void
AES_CLR_Flag_Status ()
{
// /* AESๆธ
ๆ ๅฟไฝ */
AES_SFR->CTL |= 0x00800000;
while(AES_Get_Flag_Status());//ๅคๆญๆ ๅฟไธบ0
AES_SFR->CTL &= 0xFF7FFFFF;
}
#endif //KF32A_Periph_aes
|
ChipON-IC/ChipON-KF32Axxx_StdPeriph_Lib
|
src/kf32a_basic_aes.c
|
kf32a_basic_aes.c
|
c
| 5,190
|
c
|
zh
|
code
| 4
|
github-code
|
19
|
26772437792
|
#include <stdio.h>
#include <string.h>
#define TOUPPER(c) ('a'<=(c)&&(c)<='z'?(c)-'a'+'A':(c) )
int main(void) {
char str[10];
int i;
strcpy(str, "0123");
i = 0;
putchar(TOUPPER(str[++i]));
}
|
frkn9/kn-king-kitab-cevaplar
|
chap 14/exercises/5.c
|
5.c
|
c
| 222
|
c
|
en
|
code
| 0
|
github-code
|
19
|
36743189270
|
//#define OUTPUT_READABLE_QUATERNION
//#define OUTPUT_READABLE_EULER
#define OUTPUT_READABLE_YAWPITCHROLL
//#define OUTPUT_READABLE_REALACCEL
//#define OUTPUT_READABLE_WORLDACCEL
MPU6050 mpu;
bool dmpReady = false;
uint8_t mpuIntStatus;
uint8_t devStatus;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q; // [w, x, y, z] quaternion container
VectorInt16 aa; // [x, y, z] accel sensor measurements
VectorInt16 aaReal; // [x, y, z] gravity-free accel sensor measurements
VectorInt16 aaWorld; // [x, y, z] world-frame accel sensor measurements
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi] Euler angle container
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
volatile bool mpuInterrupt = false;
void dmpDataReady()
{
mpuInterrupt = true;
}
void InitMPU()
{
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
mpu.initialize();
devStatus = mpu.dmpInitialize();
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788);
if (devStatus == 0)
{
mpu.setDMPEnabled(true);
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
dmpReady = true;
packetSize = mpu.dmpGetFIFOPacketSize();
}
else
{
Serial.println("Not read MPU6050");
}
}
float ReadGyroValue(float* yaw, float* pitch, float* roll)
{
if (!dmpReady) return;
if (!mpuInterrupt && fifoCount < packetSize)
return;
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
fifoCount = mpu.getFIFOCount();
if ((mpuIntStatus & 0x10) || fifoCount == 1024)
{
mpu.resetFIFO();
}
else if (mpuIntStatus & 0x02)
{
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
mpu.getFIFOBytes(fifoBuffer, packetSize);
fifoCount -= packetSize;
#ifdef OUTPUT_READABLE_QUATERNION
mpu.dmpGetQuaternion(&q, fifoBuffer);
return (atan2(2 * (q.y * q.z + q.w * q.x), q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z) * RAD2GRAD);
#endif
#ifdef OUTPUT_READABLE_EULER
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetEuler(euler, &q);
#endif
#ifdef OUTPUT_READABLE_YAWPITCHROLL
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
*yaw = ypr[0] * 180 / M_PI;
*pitch = ypr[1] * 180 / M_PI;
*roll = ypr[2] * 180 / M_PI;
#endif
#ifdef OUTPUT_READABLE_REALACCEL
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
#endif
#ifdef OUTPUT_READABLE_WORLDACCEL
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
#endif
}
}
|
VanThanBK/Trobot_Balancing
|
Trobot/MPUSenser.h
|
MPUSenser.h
|
h
| 3,089
|
c
|
en
|
code
| 0
|
github-code
|
19
|
13238813835
|
//
// PTScanner.h
// Proteus
//
// Created by David Owens II on 10/8/14.
// Copyright (c) 2014 owensd.io. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, PTTokenType)
{
PTTokenTypeError = -1,
PTTokenTypeIdentifier,
PTTokenTypeKeyword,
PTTokenTypeIndent,
PTTokenTypeNewLine,
PTTokenTypeColon,
PTTokenTypePipe,
PTTokenTypeOperator
};
@interface PTToken : NSObject
@property (assign) NSInteger line;
@property (assign) NSInteger column;
@property (assign) NSInteger offset;
@property (copy) NSString *text;
@property (copy) NSDictionary *attributes;
@property (assign) PTTokenType type;
@end
@interface PTScanner : NSObject
- (instancetype)initWithString:(NSString *)content;
- (PTToken *)nextToken;
@end
|
NelsonLeDuc/proteus
|
src/_old/lexer/PTScanner.h
|
PTScanner.h
|
h
| 786
|
c
|
en
|
code
| 0
|
github-code
|
19
|
17045271534
|
//
// PlayListController.h
// Run and Roll
//
// Created by Joaquin on 13-4-20.
// Copyright (c) 2013ๅนด Joaquin Hwang. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
@class PlayListController;
@protocol PlayListControllerDelegate <NSObject>
- (void)updatePlayList:(NSMutableDictionary *)playList;
@end
@interface PlayListController : UITableViewController
{
NSMutableDictionary *m_playList;
NSMutableArray *m_albumTitle;
}
@property (nonatomic,weak) id <PlayListControllerDelegate> delegate;
@property (nonatomic,strong) NSMutableDictionary *m_playList;
@property (nonatomic,strong) NSMutableArray *m_albumTitle;
@end
|
CarlSelves/runtohell
|
PlayListController.h
|
PlayListController.h
|
h
| 673
|
c
|
en
|
code
| 0
|
github-code
|
19
|
9530664905
|
#include "main.h"
#include <string.h>
/**
* _strcmp - the function that strcat two arrays
*
* @s1: the string one
* @s2: the string 2
*
* Return: 1 if true , 0 if false
*/
int _strcmp(char *s1, char *s2)
{
int equal = 0;
while (*s1)
{
if (*s1 != *s2)
{
equal = ((int)*s1 - 48) - ((int)*s2 - 48);
break;
}
s1++;
s2++;
}
return (equal);
}
|
Engobito/alx-low_level_programming
|
0x06-pointers_arrays_strings/3-strcmp.c
|
3-strcmp.c
|
c
| 369
|
c
|
en
|
code
| 0
|
github-code
|
19
|
34852705524
|
#ifndef ANTLR_TEXT_POSITION_H
#define ANTLR_TEXT_POSITION_H
class AntlrTextPosition
{
public:
AntlrTextPosition(): mLine(-1), mPos(-1) {}
AntlrTextPosition(int line, int pos): mLine(line), mPos(pos) {}
AntlrTextPosition(const AntlrTextPosition& that): mLine(that.mLine), mPos(that.mPos) {}
const AntlrTextPosition& operator=(const AntlrTextPosition& that) {
mLine = that.mLine;
mPos = that.mPos;
return *this;
}
// get/set
int getLine() const { return mLine; }
int getPos() const { return mPos; }
private:
// data
int mLine;
int mPos;
};
#endif // ANTLR_TEXT_POSITION_H
|
crafter2d/crafter2d
|
src/tools/yasc/compiler/antlr/antlrtextposition.h
|
antlrtextposition.h
|
h
| 624
|
c
|
en
|
code
| 2
|
github-code
|
19
|
3082630072
|
/*
* File: apostas.c
* Author: marcos-bah
*
* Created on July 21, 2021, 9:40 AM
*/
#include "apostas.h"
#include<time.h> //necessรกrio p/ funรงรฃo time()
#include <stdlib.h>// necessรกrio p/ as funรงรตes rand() e srand()
#include "keypad.h"
#include "lcd.h"
#include "bits.h"
#include "config.h"
#include "ssd.h"
#include "io.h"
#include "pwm.h"
#include <pic18f4520.h>
#define ON 0x0F
#define L0 0x80
#define L1 0xC0
#define CLR 0x01
#define DISP0 PIN_A2
#define DISP1 PIN_A3
#define DISP2 PIN_A4
#define DISP3 PIN_A5
char i;
void escreve(char text[]) {
char i = 0;
while (text[i] != '\0') {
lcdData(text[i]);
i++;
}
}
void delay() {
char i, j;
for (i = 0; i < 255; i++) {
for (j = 0; j < 255; j++);
for (j = 0; j < 255; j++);
}
}
void verso() {
delay();
unsigned char k, x;
x = 0b10000001;
for (k = 0; k < 8; k++) {
delay();
PORTD = x;
x = x << 1;
}
}
void inverso() {
delay();
unsigned char k, x;
x = 0b10000000;
for (k = 0; k < 8; k++) {
delay();
PORTD = x;
x = x >> 1;
}
}
void textInit() {
char text[12] = "Bem Vindo ao";
char text2[16] = "CASSINO UNIFEI!!!";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
//limpa a tela
lcdCommand(CLR);
}
char* itoa(int value, char* result, int basea) {
// check that the base if valid
if (basea < 2 || basea > 36) {
*result = '\0';
return result;
}
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= basea;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * basea)];
} while (value);
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while (ptr1 < ptr) {
tmp_char = *ptr;
*ptr-- = *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
void textInstrutions() {
char text[15] = "Clique em 1";
char text2[15] = "para o saldo";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
//limpa a tela
lcdCommand(CLR);
}
void textApostas() {
char text[15] = "Clique em 2";
char text2[15] = "para APOSTAR!";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
//limpa a tela
lcdCommand(CLR);
}
int saldo = 650;
void textSaldo() {
//limpa a tela
lcdCommand(CLR);
char text[6] = "Saldo: ";
char text2[10] = "";
itoa(saldo, text2, 10);
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
//limpa a tela
lcdCommand(CLR);
}
void textWait() {
lcdCommand(CLR);
char text[15] = "Esperando";
char text2[15] = "Aposte com 2";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
}
void textGameOver() {
char text[15] = "GAME OVER";
char text2[20] = "saldo insuf...";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
lcdCommand(CLR);
textSaldo();
}
void textLost() {
char text[15] = "VC PERDEU";
char text2[15] = "Custo: -200 ";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
lcdCommand(CLR);
textSaldo();
}
void textWin() {
char text[15] = "VC GANHOU";
char text2[15] = "Custo: +200 ";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//delay
delay();
delay();
delay();
lcdCommand(CLR);
saldo += 400; //descontando os 200 ja tirados
textSaldo();
}
int sorte = 0;
void Apostando() {
sorte = rand() % 10000;
sorte -= 1;
char ssorte[4];
itoa(sorte, ssorte, 10);
for (float t = 0; t < 200; t++) {
ssdDigit(sorte / 1000, 0);
ssdDigit((sorte / 100) % 10, 1);
ssdDigit((sorte / 10) % 10, 2);
ssdDigit(sorte % 10, 3);
ssdUpdate();
for (float tempo = 0; tempo < 100; tempo++); // +- 10ms
}
digitalWrite(DISP0, 0);
digitalWrite(DISP1, 0);
digitalWrite(DISP2, 0);
digitalWrite(DISP3, 0);
if (ssorte[0] == ssorte[1] && ssorte[2] == ssorte[3] && ssorte[1] == ssorte[2]) {
textWin();
} else {
textLost();
}
}
void textApostando() {
if (saldo - 200 <= 0) {
textGameOver();
} else {
char text[15] = "Apostando";
char text2[15] = "Custo: -200 ";
lcdCommand(L0 | (0));
escreve(text);
lcdCommand(L1 | (0));
escreve(text2);
//aposta
saldo -= 200;
pwmSet(99);
pwmFrequency(1000);
TRISD = 0x00;
PORTD = 0x00;
verso();
inverso();
pwmSet(0);
pwmFrequency(0);
Apostando();
lcdCommand(CLR);
}
}
|
marcos-bah/embarcados-caca-niquel
|
apostas.c
|
apostas.c
|
c
| 5,318
|
c
|
en
|
code
| 0
|
github-code
|
19
|
43801948237
|
#include <inc/lib.h>
#include <lwip/sockets.h>
#include <lwip/inet.h>
int
umain(int argc, char **argv)
{
if(argc != 5)
{
cprintf("migrate_send_normal: argument error!\n");
cprintf("migrate_send_normal \"env_id\" \"destination_ip\" \"destination_port\" \"local_ip\"\n");
return -1;
}
int sockfd;
struct sockaddr_in servaddr;
char buffer[1500];
struct Env_Header eh;
int count;
envid_t src_envid=strtol(argv[1], 0, 0);
int src_env_index=0;
for(count=0; count<NENV; count++)
{
if(envs[count].env_id == src_envid)
{
src_env_index=count;
break;
}
}
if(envs[count].env_status == ENV_RUNNABLE)
{
cprintf("You cannot migrate running process. Pause it first.\n");
return -1;
}
if((sockfd=socket(PF_INET,SOCK_STREAM, IPPROTO_UDP)) < 0)
{
cprintf("socket error\n");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr(argv[2]);
servaddr.sin_port=htons(strtol(argv[3], 0, 0));
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
cprintf("connect error\n");
return -1;
}
memset(&eh, 0, sizeof(struct Env_Header));
strcpy(eh.env_ip_from, argv[4]);
strcpy(eh.env_ip_to, argv[2]);
//eh.env_port_from=50002;
//eh.env_port_to=50001;
eh.env_from_id=src_envid;
eh.env_tf=envs[src_env_index].env_tf;
memset(buffer, 0, 1500);
memcpy(buffer, (void *)&eh, sizeof(struct Env_Header));
write(sockfd, buffer, sizeof(struct Env_Header));
uint8_t *addr;
void *temp_mem;
temp_mem=malloc(PGSIZE);
struct Migration_Env_Normal *me=(struct Migration_Env_Normal *)malloc(sizeof(struct Migration_Env_Normal));
int status;
for(addr=(uint8_t*)UTEXT; addr<(uint8_t*)0xeebfe000; addr=addr+PGSIZE)
{
memset(temp_mem, 0, PGSIZE);
sys_my_check_page(src_envid, addr, temp_mem, &status);
if(status == 1)
{
memset(me, 0, sizeof(struct Migration_Env_Normal));
me->m_env_va=(uint32_t)addr;
me->m_env_sequence=1;
memmove(me->m_env_mem, (char *)(temp_mem+1024*0), 1024);
me->m_status=1;
memset(buffer, 0, 1500);
memcpy(buffer, (void *)me, sizeof(struct Migration_Env_Normal));
write(sockfd, buffer, sizeof(struct Migration_Env_Normal));
cprintf("Send Page: 0x%08x, Sequence: %d\n", (uint32_t)addr, me->m_env_sequence);
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
memset(me, 0, sizeof(struct Migration_Env_Normal));
me->m_env_va=(uint32_t)addr;
me->m_env_sequence=2;
memmove(me->m_env_mem, (char *)(temp_mem+1024*1), 1024);
me->m_status=1;
memset(buffer, 0, 1500);
memcpy(buffer, (void *)me, sizeof(struct Migration_Env_Normal));
write(sockfd, buffer, sizeof(struct Migration_Env_Normal));
cprintf("Send Page: 0x%08x, Sequence: %d\n", (uint32_t)addr, me->m_env_sequence);
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
memset(me, 0, sizeof(struct Migration_Env_Normal));
me->m_env_va=(uint32_t)addr;
me->m_env_sequence=3;
memmove(me->m_env_mem, (char *)(temp_mem+1024*2), 1024);
me->m_status=1;
memset(buffer, 0, 1500);
memcpy(buffer, (void *)me, sizeof(struct Migration_Env_Normal));
write(sockfd, buffer, sizeof(struct Migration_Env_Normal));
cprintf("Send Page: 0x%08x, Sequence: %d\n", (uint32_t)addr, me->m_env_sequence);
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
memset(me, 0, sizeof(struct Migration_Env_Normal));
me->m_env_va=(uint32_t)addr;
me->m_env_sequence=4;
memmove(me->m_env_mem, (char *)(temp_mem+1024*3), 1024);
me->m_status=1;
memset(buffer, 0, 1500);
memcpy(buffer, (void *)me, sizeof(struct Migration_Env_Normal));
write(sockfd, buffer, sizeof(struct Migration_Env_Normal));
cprintf("Send Page: 0x%08x, Sequence: %d\n", (uint32_t)addr, me->m_env_sequence);
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
sys_yield();
}
}
memset(me, 0, sizeof(struct Migration_Env_Normal));
me->m_status=0;
memset(buffer, 0, 1500);
memcpy(buffer, (void *)me, sizeof(struct Migration_Env_Normal));
write(sockfd, buffer, sizeof(struct Migration_Env_Normal));
memset(buffer, 0, 1500);
read(sockfd, buffer, 1500);
cprintf("Feedback: %s\n", buffer);
cprintf("You have successfully moved Env %d to %s\n", src_envid, argv[2]);
close(sockfd);
free(me);
return 0;
}
|
finallyjustice/mitjos
|
process-migration/vm1/user/migrate_send_normal.c
|
migrate_send_normal.c
|
c
| 4,439
|
c
|
en
|
code
| 0
|
github-code
|
19
|
38263364592
|
#ifndef MF3D_BINARYREAD_H
#define MF3D_BINARYREAD_H
/*==============================================================================
*
* File: MFBINRD.H
*
* Function: Binary reading utilities.
*
* Version: Metafile: Version 1.0 3DMF files
* Package: Release #3 of this code
*
* Author(s): Rick Wong (RWW), Duet Development Corp.
* John Kelly (JRK), Duet Development Corp.
*
* Copyright: (c) 1995 by Apple Computer, Inc., all rights reserved.
*
* Change History (most recent first):
* FBL_JRK Lowercase include file names
* FB7_JRK Pragma macros
* Fabio Changed file name to 8 characters
* F3A_RWW Binary TOC.
* F2O_RWW File created.
*==============================================================================
*/
#if defined(applec) || defined(__MWERKS__) || defined(THINK_C)
#pragma once
#endif
#include "mftypes.h"
#include "mfintobj.h"
/*==============================================================================
* MF3D_BinaryReadProc
*==============================================================================
*/
MF3DErr MF3D_BinaryReadProc (
MF3D_FilePtr inMetafilePtr,
MF3DSize inAmtToRead,
char *outBuffer);
MF3DErr
MF3D_PreprocessBinaryFile (
MF3D_FilePtr inMetafilePtr);
MF3DCStringPtr
MF3D_GetRefNameB (
MF3D_FilePtr inMetafilePtr,
MF3DReferenceID inRefID);
MF3DErr
MF3D_GetBinaryRefID (
MF3D_FilePtr inMetafilePtr,
MF3DBinaryFilePosition inLocation,
MF3DReferenceID * outRefID);
MF3DErr
MF3D_PostprocessBinaryFile (
MF3D_FilePtr inMetafilePtr);
#endif
|
virtualritz/ayam
|
ayam-sys/ayam/ayam/src/MF3D/mfbinrd.h
|
mfbinrd.h
|
h
| 1,593
|
c
|
en
|
code
| 0
|
github-code
|
19
|
74536991722
|
#ifndef HYGROMETER
#define HYGROMETER
#include <wiringPi.h>
class Hygrometer{
public:
Hygrometer(int pinNum);
bool soil_isDry(void);
float readAnalog(void);
private:
float threshold; // If moisture level is below this percentage, soil is too dry
int pinNumber;
};
#endif
|
grwells/Projects
|
I61_Internship/SoilHumidity_Sensor/Hygrometer.h
|
Hygrometer.h
|
h
| 302
|
c
|
en
|
code
| 2
|
github-code
|
19
|
27310766139
|
#include <stdlib.h>
#include <string.h>
#include "main.h"
/**
* _strdup - Creates an in-memory copy of a string
* @str: Character string to be duplicated
*
* Description: This function returns a pointer to a new string
* that is a copy of the string 'str'
*
* Memory for the new string is obtained with malloc and can be
* freed with free
*
* Return: Returns NULL if 'str' is NULL or if not enough memory available
*/
char *_strdup(char *str)
{
char *duplicate;
if (str == NULL)
{
return (NULL);
}
duplicate = (char *)malloc(strlen(str) + 1);
if (duplicate == NULL)
{
return (NULL);
}
strcpy(duplicate, str);
return (duplicate);
}
|
AlanTuring2030/holbertonschool-low_level_programming
|
malloc_free/1-strdup.c
|
1-strdup.c
|
c
| 660
|
c
|
en
|
code
| 0
|
github-code
|
19
|
74581314284
|
#ifndef PISCES_H
#define PISCES_H
#include "../animal.h"
/** @class Pisces
* Kelas Pisces mendefinisikan atribut untuk pisces
*/
class Pisces: public Animal {
public:
/** @brief Constructor
* Menciptakan Pisces dengan atribut default untuk pisces pada umumnya.
*/
Pisces();
private:
const int def_limb_count;
const std::string def_skin_type;
};
#endif
|
holylovenia/meinzoo
|
src/animal/pisces/pisces.h
|
pisces.h
|
h
| 391
|
c
|
id
|
code
| 0
|
github-code
|
19
|
10723507738
|
/*
* Copyright (C) 2001 Peter Hunnisett
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
/*
* Oracle LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
* other than GPL or LGPL is available it will apply instead, Oracle elects to use only
* the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
* a choice of LGPL license versions is made available with the language indicating
* that LGPLv2 or any later version may be used, or where a choice of which version
* of the LGPL is applied is otherwise unspecified.
*/
#ifndef __RPCNTERR_H__
#define __RPCNTERR_H__
#define RPC_S_OK ERROR_SUCCESS
#define RPC_S_INVALID_ARG ERROR_INVALID_PARAMETER
#define RPC_S_OUT_OF_MEMORY ERROR_OUTOFMEMORY
#define RPC_S_OUT_OF_THREADS ERROR_MAX_THRDS_REACHED
#define RPC_S_INVALID_LEVEL ERROR_INVALID_PARAMETER
#define RPC_S_BUFFER_TOO_SMALL ERROR_INSUFFICIENT_BUFFER
#define RPC_S_INVALID_SECURITY_DESC ERROR_INVALID_SECURITY_DESCR
#define RPC_S_ACCESS_DENIED ERROR_ACCESS_DENIED
#define RPC_S_SERVER_OUT_OF_MEMORY ERROR_NOT_ENOUGH_SERVER_MEMORY
#define RPC_S_ASYNC_CALL_PENDING ERROR_IO_PENDING
#define RPC_S_UNKNOWN_PRINCIPAL ERROR_NONE_MAPPED
#define RPC_S_TIMEOUT ERROR_TIMEOUT
#define RPC_X_NO_MEMORY RPC_S_OUT_OF_MEMORY
#define RPC_X_INVALID_BOUND RPC_S_INVALID_BOUND
#define RPC_X_INVALID_TAG RPC_S_INVALID_TAG
#define RPC_X_ENUM_VALUE_TOO_LARGE RPC_X_ENUM_VALUE_OUT_OF_RANGE
#define RPC_X_SS_CONTEXT_MISMATCH ERROR_INVALID_HANDLE
#define RPC_X_INVALID_BUFFER ERROR_INVALID_USER_BUFFER
#define RPC_X_PIPE_APP_MEMORY ERROR_OUTOFMEMORY
#define RPC_X_INVALID_PIPE_OPERATION RPC_X_WRONG_PIPE_ORDER
#endif /* __RPCNTERR_H__ */
|
thalium/icebox
|
third_party/virtualbox/src/VBox/Devices/Graphics/shaderlib/wine/include/rpcnterr.h
|
rpcnterr.h
|
h
| 2,637
|
c
|
en
|
code
| 550
|
github-code
|
19
|
17907332969
|
#include <stdbool.h>
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#ifndef __SIM__
#include "cortexm/cortexm.h"
#endif
#include "sffs_block.h"
#include "sffs_local.h"
#include "sffs_filelist.h"
#include "sffs_serialno.h"
#include "sffs_dir.h"
#include "sffs_file.h"
#define DEBUG_LEVEL 10
static void svcall_execute_callback(cl_handle_t * handle) MCU_ROOT_EXEC_CODE;
static int cleanup_file(const void * cfg, block_t hdr_block, int addr, uint8_t status);
int mark_file_closed(const void * cfg, block_t hdr_block);
static int get_sffs_block_data_addr(const void * cfg, block_t block){
return block * BLOCK_SIZE + offsetof(sffs_block_data_t, data);
}
void svcall_execute_callback(cl_handle_t * handle){
CORTEXM_SVCALL_ENTER();
handle->op->handler.callback(handle->op->handler.context, NULL);
}
static int calc_page_size(const void * cfg, cl_handle_t * handle, int * offset){
*offset = (handle->op->loc % BLOCK_DATA_SIZE);
return (handle->bytes_left > ( BLOCK_DATA_SIZE - *offset )) ? (BLOCK_DATA_SIZE - *offset) : handle->bytes_left;
}
static void update_current_segment(cl_handle_t * handle, int page_size){
handle->op->loc += page_size;
handle->bytes_left -= page_size;
handle->op->buf += page_size;
}
static int read_current_segment(const void * cfg, cl_handle_t * handle){
int page_size;
int offset;
page_size = calc_page_size(cfg, handle, &offset);
if ( page_size > 0 ){
memcpy(handle->op->buf, &(handle->segment_data.data[offset]), page_size);
update_current_segment(handle, page_size);
}
return page_size;
}
static int write_current_segment(const void * cfg, cl_handle_t * handle){
int page_size;
int offset;
page_size = calc_page_size(cfg, handle, &offset);
if ( page_size > 0 ){
memcpy(&(handle->segment_data.data[offset]), handle->op->buf, page_size);
handle->segment_data.hdr.status = BLOCK_STATUS_CLOSED;
update_current_segment(handle, page_size);
if( handle->op->loc > handle->size ){
handle->size = handle->op->loc;
}
}
return page_size;
}
int sffs_file_startread(const void * cfg, cl_handle_t * handle){
int segment;
segment = handle->op->loc / BLOCK_DATA_SIZE;
//first check to see if the current segment is the segment being read
handle->bytes_left = handle->op->nbyte;
if ( handle->bytes_left + handle->op->loc > handle->size ){
handle->bytes_left = handle->size - handle->op->loc;
handle->op->nbyte = handle->bytes_left;
}
if ( segment == handle->segment ){
read_current_segment(cfg, handle);
if ( handle->bytes_left == 0 ){
return handle->op->nbyte;
}
}
return 0;
}
int sffs_file_finishread(const void * cfg, cl_handle_t * handle){
int nsegments;
if ( sffs_file_savesegment(cfg, handle) < 0 ){
sffs_error("could not save segment\n");
return -1;
}
//load the first segment
if ( sffs_file_loadsegment(cfg, handle, handle->op->loc / BLOCK_DATA_SIZE) < 0){
sffs_error("could not load segment\n");
return -1;
}
read_current_segment(cfg, handle);
if( handle->bytes_left > 0 ){
//read remaining full segments
nsegments = handle->bytes_left / BLOCK_DATA_SIZE;
if ( sffs_file_read(cfg, handle, handle->segment + 1, nsegments) < 0 ){
sffs_error("failed to read file\n");
return -1;
}
//read the final segment
if ( sffs_file_loadsegment(cfg, handle, handle->segment + 1) < 0){
sffs_error("failed to load final segment\n");
return -1;
}
read_current_segment(cfg, handle);
}
if ( handle->op->handler.callback != NULL ){
cortexm_svcall((cortexm_svcall_t)svcall_execute_callback, handle);
}
return 0;
}
int sffs_file_startwrite(const void * cfg, cl_handle_t * handle){
int segment;
segment = handle->op->loc / BLOCK_DATA_SIZE;
if ( handle->op->loc > handle->size ){
sffs_error("loc is > size\n");
return -1;
}
//first check to see if the current segment is the segment being written
handle->bytes_left = handle->op->nbyte;
if ( segment == handle->segment ){
write_current_segment(cfg, handle);
if ( handle->bytes_left == 0 ){
return handle->op->nbyte; //The operation completed just using the RAM buffer
}
}
//This means the operation must finish using sffs_file_finishwrite()
return 0;
}
int sffs_file_finishwrite(const void * cfg, cl_handle_t * handle){
int nsegments;
//save the first segment or the previous segment
if ( sffs_file_savesegment(cfg, handle) < 0 ){
sffs_error("could not save segment\n");
return -1;
}
//load the first segment
if ( sffs_file_loadsegment(cfg, handle, handle->op->loc / BLOCK_DATA_SIZE) < 0){
return -1;
}
write_current_segment(cfg, handle);
if ( handle->bytes_left > 0 ){
if ( sffs_file_savesegment(cfg, handle) < 0 ){
sffs_error("could not save next segment\n");
return -1;
}
//write remaining full segments
handle->segment++;
nsegments = handle->bytes_left / BLOCK_DATA_SIZE;
if ( sffs_file_write(cfg, handle, handle->segment, nsegments) < 0 ){
sffs_error("could not write file\n");
return -1;
}
//load the final segment
if ( sffs_file_loadsegment(cfg, handle, handle->segment) < 0){
sffs_error("could not load final segment\n");
return -1;
}
write_current_segment(cfg, handle);
}
if ( handle->op->handler.callback != NULL ){
cortexm_svcall((cortexm_svcall_t)svcall_execute_callback, handle);
}
return 0;
}
int sffs_file_remove(const void * cfg, serial_t serialno){
int addr;
block_t sffs_block_num;
//lookup the block number
sffs_block_num = sffs_serialno_get(cfg, serialno, SFFS_SNLIST_ITEM_STATUS_CLOSED, &addr);
sffs_debug(DEBUG_LEVEL, "remove serialno:%d at block:%d\n", serialno, sffs_block_num);
if ( sffs_block_num == BLOCK_INVALID ){
return -1;
}
//set serial number status to discarding header and list
if ( sffs_serialno_setstatus(cfg, addr, SFFS_SNLIST_ITEM_STATUS_DISCARDING) < 0 ){
sffs_error("failed to set status at addr 0x%X\n", addr);
return -1;
}
return cleanup_file(cfg, sffs_block_num, addr, SFFS_SNLIST_ITEM_STATUS_DISCARDING);
}
int sffs_file_savesegment(const void * cfg, cl_handle_t * handle){
block_t block;
//save this to a new block in the file
if ( handle->segment_data.hdr.status == BLOCK_STATUS_CLOSED){
handle->mtime = 0;
block = sffs_block_alloc(cfg, handle->segment_data.hdr.serialno, handle->segment_list_block, BLOCK_TYPE_FILE_DATA);
sffs_debug(DEBUG_LEVEL + 2, "saving segment %d to block %d\n", handle->segment, block);
if ( block == BLOCK_INVALID ){
sffs_error("could not alloc block\n");
return -1;
}
//save the new block to the disk -- this will be closed when the file is closed
if ( sffs_block_save(cfg, block, &(handle->segment_data)) < 0 ){
sffs_error("could not save block %d\n", block);
return -1;
}
//Enter the new block in the list
if ( sffs_filelist_update(cfg,
handle->segment_list_block,
handle->segment,
block) < 0){
sffs_error("could not update file list\n");
return -1;
}
} else {
sffs_debug(DEBUG_LEVEL + 2, "segment not dirty\n");
}
return 0;
}
int sffs_file_loadsegment(const void * cfg, cl_handle_t * handle, int segment){
block_t block;
//save this to a new block in the file
block = sffs_filelist_get(cfg, handle->segment_list_block, segment, SFFS_FILELIST_STATUS_CURRENT, NULL);
if ( block == BLOCK_INVALID ){ //the segment doesn't exist in the file; create it
sffs_debug(DEBUG_LEVEL + 2, "segment %d doesn't exist %d\n", segment, handle->segment_list_block);
memset(handle->segment_data.data, 0, BLOCK_DATA_SIZE);
} else {
sffs_debug(DEBUG_LEVEL + 2, "loading segment %d from block %d\n", segment, block);
if( sffs_block_load(cfg, block, &(handle->segment_data)) < 0 ){
sffs_error("failed to load segment (%d) data block (%d)\n", segment, block);
return -1;
}
}
handle->segment = segment;
handle->segment_data.hdr.status = BLOCK_STATUS_OPEN;
return 0;
}
int sffs_file_swapsegment(const void * cfg, cl_handle_t * handle, int new_segment){
block_t block;
if ( new_segment == handle->segment ){
//The new segment is equal to the current segment
return 0;
}
//check if current buffer needs to be written to disk
if ( sffs_file_savesegment(cfg, handle) ){
return -1;
}
//now load the new segment -- mark it as allocated
handle->segment = new_segment;
block = sffs_filelist_get(cfg, handle->segment_list_block, new_segment, SFFS_FILELIST_STATUS_CURRENT, NULL);
if ( block == BLOCK_INVALID ){ //the segment doesn't exist in the file; create it
memset(handle->segment_data.data, 0, BLOCK_DATA_SIZE);
} else {
sffs_block_load(cfg, block, &(handle->segment_data));
}
handle->segment_data.hdr.status = BLOCK_STATUS_OPEN;
return 0;
}
int sffs_file_write(const void * cfg, cl_handle_t * handle, int start_segment, int nsegments){
int i;
if ( nsegments > 0 ){
handle->segment = start_segment;
for(i=0; i < nsegments; i++){
memcpy(handle->segment_data.data, handle->op->buf, BLOCK_DATA_SIZE);
handle->segment_data.hdr.status = BLOCK_STATUS_CLOSED;
if ( sffs_file_savesegment(cfg, handle) < 0){
return -1;
}
handle->segment++;
handle->op->buf += BLOCK_DATA_SIZE;
}
handle->op->loc += (BLOCK_DATA_SIZE * nsegments);
handle->bytes_left -= (BLOCK_DATA_SIZE * nsegments);
if( handle->op->loc > handle->size ){
handle->size = handle->op->loc;
}
}
return 0;
}
int sffs_file_read(const void * cfg, cl_handle_t * handle, int start_segment, int nsegments){
int i;
if ( nsegments > 0 ){
for(i=0; i < nsegments; i++){
if ( sffs_file_loadsegment(cfg, handle, start_segment + i) < 0 ){
return -1;
}
memcpy(handle->op->buf, handle->segment_data.data, BLOCK_DATA_SIZE);
handle->op->buf += BLOCK_DATA_SIZE;
}
handle->op->loc += (BLOCK_DATA_SIZE * nsegments);
handle->bytes_left -= (BLOCK_DATA_SIZE * nsegments);
}
return 0;
}
int sffs_file_open(const void * cfg, cl_handle_t * handle, serial_t serialno, int amode, bool trunc){
block_t block;
cl_hdr_t * hdr;
block = sffs_serialno_get(cfg, serialno, SFFS_SNLIST_ITEM_STATUS_CLOSED, &(handle->serialno_addr));
if ( block == BLOCK_INVALID ){
sffs_error("serialno does not exist\n");
return -1;
}
sffs_debug(DEBUG_LEVEL, "file exists at block %d\n", block);
if ( sffs_block_load(cfg, block, &(handle->segment_data)) < 0 ){
sffs_error("could not load block\n");
return -1;
}
hdr = (cl_hdr_t*)(handle->segment_data.data);
if ( handle->segment_data.hdr.type == BLOCK_TYPE_FILE_HDR ){
if ( amode & W_OK ){ //create a new entry
sffs_debug(DEBUG_LEVEL, "Creating a new entry for file writing\n");
block = sffs_block_alloc(cfg, serialno, block, BLOCK_TYPE_FILE_HDR);
if ( block == BLOCK_INVALID ){
sffs_error("failed to alloc block for new header entry\n");
return -1;
}
//add an entry in the serial number list -- this entry will be marked as open
if ( sffs_serialno_append(cfg, serialno, block, &(handle->serialno_addr), SFFS_SNLIST_ITEM_STATUS_OPEN) < 0 ){
sffs_error("failed to append new serialno %d %d\n", serialno, block);
return -1;
}
if ( (hdr->open.content_block = sffs_filelist_consolidate(cfg, serialno, hdr->open.content_block)) == BLOCK_INVALID ){
sffs_error("failed to consolidate list\n");
return -1;
}
if ( trunc == true ){
//consolidate the file list to a new block
if ( sffs_filelist_makeobsolete(cfg, hdr->open.content_block) < 0 ){
sffs_error("failed to make the list obsolete\n");
}
sffs_debug(DEBUG_LEVEL, "file is being truncated to new list block %d\n", hdr->open.content_block);
hdr->close.size = 0;
} else {
sffs_debug(DEBUG_LEVEL, "file is being modified to new list block %d\n", hdr->open.content_block);
}
sffs_debug(DEBUG_LEVEL, "New header block is open as serialno %d at block %d\n", serialno, block);
//write the constant part of the file header
if ( sffs_dev_write(cfg, get_sffs_block_data_addr(cfg, block) + offsetof(cl_hdr_t, open),
&(hdr->open),
sizeof(cl_hdr_open_t)) != sizeof(cl_hdr_open_t) ){
sffs_error("failed to write the open portion of header\n");
return -1;
}
}
handle->amode = amode;
handle->hdr_block = block;
handle->segment_list_block = hdr->open.content_block;
handle->op = NULL;
if ( hdr->close.size < 0 ){
//In this case the file was never created properly and will be truncated
handle->size = 0; //! \todo set the size to the number of segments * BLOCK_DATA_SIZE
handle->mtime = 0;
} else {
handle->size = hdr->close.size;
}
sffs_debug(DEBUG_LEVEL, "Load first segment\n");
if ( sffs_file_loadsegment(cfg, handle, 0) < 0 ){
sffs_error("failed to load segment 0\n");
return -1;
}
}
sffs_debug(DEBUG_LEVEL, "File opened successfully\n");
return 0;
}
int sffs_file_new(const void * cfg, cl_handle_t * handle, const char * name, int mode, sffs_dir_lookup_t * entry, uint8_t type, int amode){
cl_hdr_t hdr;
block_t block;
block_t list_block;
//Allocate the block for the file header
if ( (block = sffs_block_alloc(cfg, entry->serialno, BLOCK_INVALID, type)) == BLOCK_INVALID ){
sffs_error("failed to alloc header block\n");
return -1;
}
sffs_debug(DEBUG_LEVEL, "new file serialno %d block %d\n", entry->serialno, block);
//mark the serial number as "open" in the serial number list
if ( sffs_serialno_append(cfg, entry->serialno, block, &(handle->serialno_addr), SFFS_SNLIST_ITEM_STATUS_OPEN) < 0 ){
sffs_error("failed to append serialno\n");
return -1;
}
//Allocate the block for the file data list
if ( (list_block = sffs_block_alloc(cfg, entry->serialno, block, BLOCK_TYPE_FILE_LIST)) == BLOCK_INVALID ){
sffs_error("failed to alloc list block\n");
return -1;
}
handle->hdr_block = block;
handle->segment_list_block = list_block;
handle->size = 0;
handle->segment = SEGMENT_INVALID;
handle->segment_data.hdr.status = BLOCK_STATUS_FREE;
handle->segment_data.hdr.serialno = entry->serialno;
handle->segment_data.hdr.type = BLOCK_TYPE_FILE_DATA;
handle->mtime = 0;
handle->amode = amode;
handle->op = NULL;
sffs_debug(DEBUG_LEVEL, "new file: list block:%d\n", list_block);
//populate the part of the header that is written on open
strcpy(hdr.open.name, name);
hdr.open.content_block = list_block;
//write the constant part of the file header
if ( sffs_dev_write(cfg, get_sffs_block_data_addr(cfg, block) + offsetof(cl_hdr_t, open),
&(hdr.open),
sizeof(cl_hdr_open_t)) != sizeof(cl_hdr_open_t) ){
return -1;
}
return 0;
}
static int finish_close(const void * cfg,
uint8_t discard_status,
block_t new_block,
block_t old_block,
int new_addr,
int old_addr,
bool already_closed){
bool close_failed;
sffs_debug(DEBUG_LEVEL, "need to discard old file list/header\n");
//The old entry needs to be updated
close_failed = false;
if ( already_closed == false ){
//update the status of the old and new serial number entries
//Mark the new entry as closing
sffs_debug(DEBUG_LEVEL, "writing CLOSING to 0x%X\n", new_addr);
if ( sffs_serialno_setstatus(cfg, new_addr, SFFS_SNLIST_ITEM_STATUS_CLOSING) < 0 ){
return -1;
}
CL_TP_DESC(CL_PROB_COMMON, "New file is CLOSING and old file is CLOSED");
if ( mark_file_closed(cfg, new_block) < 0 ){
sffs_error("failed to close file blocks\n");
close_failed = true;
} else {
CL_TP_DESC(CL_PROB_COMMON, "new file has been closed but not marked CLOSED");
sffs_debug(DEBUG_LEVEL, "writing 0x%X to 0x%X\n", discard_status, old_addr);
if ( sffs_serialno_setstatus(cfg, old_addr, discard_status) < 0 ){
return -1;
}
CL_TP_DESC(CL_PROB_COMMON, "New file is CLOSING and old file is DISCARDING...");
//Mark the new entry as closing
if ( sffs_serialno_setstatus(cfg, new_addr, SFFS_SNLIST_ITEM_STATUS_CLOSED) < 0 ){
return -1;
}
}
}
if ( close_failed == false ){
//test point
CL_TP_DESC(CL_PROB_COMMON, "About to complete discard");
//clean up the old file data
if ( cleanup_file(cfg, old_block, old_addr, discard_status) < 0 ){
sffs_error("failed to clean\n");
return -1;
}
}
return 0;
}
int mark_file_closed(const void * cfg, block_t hdr_block){
//this is done in a bottom up manner -- data, then list, then header
sffs_block_data_t tmp;
cl_hdr_t * hdr;
sffs_list_t list;
sffs_filelist_item_t file_item;
int filelist_addr;
sffs_debug(DEBUG_LEVEL, "close hdr block %d\n", hdr_block);
//load the header which is located at sffs_block_num
if ( sffs_block_load(cfg, hdr_block, &tmp) ){
sffs_error("failed to load block %d\n", hdr_block);
return -1;
}
if ( tmp.hdr.status == BLOCK_STATUS_CLOSED ){
//this file is already closed (up to the header)
return 0;
}
if ( (tmp.hdr.type != BLOCK_TYPE_FILE_HDR) ){
sffs_error("header block is wrong type 0x%X\n", tmp.hdr.type);
return -1;
}
hdr = (cl_hdr_t*)tmp.data;
sffs_debug(DEBUG_LEVEL, "discarding file data serialno: %d hdr %d list %d\n",
tmp.hdr.serialno,
hdr_block,
hdr->open.content_block);
//Discard all the segments in the file
if ( sffs_filelist_init(cfg, &list, hdr->open.content_block) < 0 ){
sffs_error("failed to init file list\n");
return -1;
}
while( sffs_list_getnext(cfg, &list, &file_item, &filelist_addr) == 0 ){
if ( (file_item.status == SFFS_FILELIST_STATUS_CURRENT) ){
sffs_debug(DEBUG_LEVEL + 2, "closing current block %d\n", file_item.block);
if ( sffs_block_close(cfg, file_item.block) < 0 ){
sffs_error("failed to discard block\n");
return -1;
}
} else if ( file_item.status == SFFS_FILELIST_STATUS_OBSOLETE ){
//discard the associated data block
sffs_debug(DEBUG_LEVEL + 4, "discard this block %d 0x%X\n", file_item.block, file_item.status);
if ( sffs_block_discard(cfg, file_item.block) < 0 ){
sffs_error("failed to discard block\n");
return -1;
}
//mark it dirty in the list
if ( sffs_filelist_setstatus(cfg, SFFS_FILELIST_STATUS_DIRTY, filelist_addr) < 0 ){
sffs_error("failed to set status to dirty\n");
return -1;
}
}
//close the list block if not already closed
if ( list.block_data.hdr.status == BLOCK_STATUS_OPEN ){
sffs_block_close(cfg, list.current_block);
list.block_data.hdr.status = BLOCK_STATUS_CLOSED;
}
}
//close the list of file segments
if ( sffs_list_close(cfg, hdr->open.content_block) ){
return -1;
}
//close the header
if ( sffs_block_close(cfg, hdr_block) < 0 ){
return -1;
}
return 0;
}
int sffs_file_close(const void * cfg, cl_handle_t * handle){
cl_hdr_t hdr;
block_t block;
uint8_t discard_status;
int old_addr;
if ( !(handle->amode & W_OK) ){
//if the file was not written (ie. opened read-only), nothing needs to be done here
return 0;
}
//write the RAM segment to disk if it has been modified
sffs_debug(DEBUG_LEVEL, "Saving segment\n");
if ( sffs_file_savesegment(cfg, handle) ){
sffs_error("Failed to save file segment\n");
return -1;
}
//write the header to the file -- with the size and modified/accessed date
hdr.close.size = handle->size;
sffs_debug(DEBUG_LEVEL, "content block is %d\n", handle->segment_list_block);
sffs_debug(DEBUG_LEVEL, "write to header block %d\n", handle->hdr_block);
CL_TP_DESC(CL_PROB_COMMON, "about to close (size not written)");
//Write the information available on close (size is written on close)
sffs_debug(DEBUG_LEVEL, "close file (size:%d content block:%d)\n", hdr.close.size, handle->segment_list_block);
if ( sffs_dev_write(cfg, get_sffs_block_data_addr(cfg, handle->hdr_block) + offsetof(cl_hdr_t, close),
&hdr.close,
sizeof(cl_hdr_close_t)) != sizeof(cl_hdr_close_t) ){
sffs_error("failed to write close data\n");
return -2;
}
//this should be handled the same every time
//get the address of the old serial number
block = sffs_serialno_get(cfg, handle->segment_data.hdr.serialno, SFFS_SNLIST_ITEM_STATUS_CLOSED, &old_addr);
sffs_debug(DEBUG_LEVEL, "Old block is %d\n", block);
if ( block != BLOCK_INVALID ){
CL_TP_DESC(CL_PROB_COMMON, "modifying but still open");
//The old entry needs to be updated
discard_status = SFFS_SNLIST_ITEM_STATUS_DISCARDING_HDR_LIST;
sffs_debug(DEBUG_LEVEL, "finish close status 0x%X hdr %d old hdr %d serialno %d\n",
discard_status, handle->hdr_block, block, handle->segment_data.hdr.serialno);
if ( finish_close(cfg, discard_status, handle->hdr_block, block, handle->serialno_addr, old_addr, false) < 0 ){
return -3;
}
} else {
sffs_debug(DEBUG_LEVEL, "closing new file (file did not previously exist)\n");
if ( sffs_serialno_setstatus(cfg, handle->serialno_addr, SFFS_SNLIST_ITEM_STATUS_CLOSING) < 0 ){
sffs_error("failed to close out new serialno\n");
return -1;
}
CL_TP_DESC(CL_PROB_COMMON, "CLOSING but not cleaned");
//Close the file (includes discarding obsolete segments)
if ( mark_file_closed(cfg, handle->hdr_block) < 0 ){
sffs_error("failed to clean file list block\n");
return -1;
}
CL_TP_DESC(CL_PROB_COMMON, "cleaned but not CLOSED");
if ( sffs_serialno_setstatus(cfg, handle->serialno_addr, SFFS_SNLIST_ITEM_STATUS_CLOSED) < 0 ){
sffs_error("failed to close out new serialno\n");
return -4;
}
}
return 0;
}
int sffs_file_clean(const void * cfg, serial_t serialno, block_t hdr_block, uint8_t status){
int new_addr;
int old_addr;
block_t old_block;
block_t new_block;
sffs_block_data_t sffs_block_data;
bool already_closed;
sffs_debug(DEBUG_LEVEL, "cleaning file %d\n", serialno);
old_block = sffs_serialno_get(cfg, serialno, status, &old_addr);
if ( hdr_block != old_block ){
sffs_error("failed to clean file\n");
return -1;
}
switch(status){
case SFFS_SNLIST_ITEM_STATUS_DISCARDING:
if ( cleanup_file(cfg, old_block, old_addr, status) < 0 ){
sffs_error("failed to complete discard\n");
return -1;
}
break;
case SFFS_SNLIST_ITEM_STATUS_DISCARDING_HDR_LIST:
case SFFS_SNLIST_ITEM_STATUS_DISCARDING_HDR:
//look for the new file
if ( (new_block = sffs_serialno_get(cfg, serialno, SFFS_SNLIST_ITEM_STATUS_CLOSING, &new_addr)) == BLOCK_INVALID ){
//no "CLOSING" files exist -- check for "CLOSED"
if ( (new_block = sffs_serialno_get(cfg, serialno, SFFS_SNLIST_ITEM_STATUS_CLOSED, &new_addr)) == BLOCK_INVALID ){
sffs_error("new file is not found anywhere\n");
return -1;
} else {
sffs_debug(DEBUG_LEVEL, "new file is already closed\n");
already_closed = true;
}
} else {
already_closed = false;
}
if ( sffs_block_load(cfg, new_block, &sffs_block_data) < 0 ){
sffs_error("failed to load new block %d\n", new_block);
return -1;
}
sffs_debug(DEBUG_LEVEL, "finish closing and discarding file\n");
if ( finish_close(cfg, status, new_block, old_block, new_addr, old_addr, already_closed) < 0 ){
return -1;
}
break;
case SFFS_SNLIST_ITEM_STATUS_CLOSING:
//need to see if another file is "CLOSED"
sffs_debug(DEBUG_LEVEL, "cleaning CLOSING file\n");
if ( (new_block = sffs_serialno_get(cfg, serialno, SFFS_SNLIST_ITEM_STATUS_CLOSED, &new_addr)) == BLOCK_INVALID ){
//the CLOSING file is the only one that exists -- it just needs to be clean and closed
sffs_debug(DEBUG_LEVEL, "clean CLOSING file (no other files)\n");
if ( sffs_block_load(cfg, old_block, &sffs_block_data) < 0 ){
sffs_error("failed to load new block %d\n", new_block);
return -1;
}
//Close the file (includes discarding obsolete segments)
if ( mark_file_closed(cfg, hdr_block) < 0 ){
sffs_error("failed to clean file list block\n");
return -1;
}
CL_TP_DESC(CL_PROB_COMMON, "cleaned but not CLOSED");
if ( sffs_serialno_setstatus(cfg, old_addr, SFFS_SNLIST_ITEM_STATUS_CLOSED) < 0 ){
sffs_error("failed to close file\n");
return -1;
}
} else {
sffs_debug(DEBUG_LEVEL, "clean CLOSING file (other file is already closed)\n");
//the file already exists as "CLOSED"
sffs_debug(DEBUG_LEVEL, "cleaning CLOSING file but original is still CLOSED\n");
if ( cleanup_file(cfg, old_block, old_addr, SFFS_SNLIST_ITEM_STATUS_DISCARDING_HDR) < 0 ){
sffs_error("failed to complete discard\n");
return -1;
}
return 1;
}
break;
case SFFS_SNLIST_ITEM_STATUS_OPEN:
sffs_debug(DEBUG_LEVEL, "cleaning open file\n");
if ( sffs_serialno_setstatus(cfg, old_addr, SFFS_SNLIST_ITEM_STATUS_DIRTY) < 0 ){
sffs_error("failed to close file\n");
return -1;
}
return 1;
break;
default:
sffs_error("unknown status %d\n", status);
return -1;
}
return 0;
}
int cleanup_file(const void * cfg, block_t hdr_block, int addr, uint8_t status){
sffs_block_data_t tmp;
cl_hdr_t * hdr;
sffs_list_t list;
sffs_filelist_item_t file_item;
int filelist_addr;
sffs_debug(DEBUG_LEVEL, "clean block %d (0x%X)\n", hdr_block, status);
//load the header which is located at sffs_block_num
if ( sffs_block_load(cfg, hdr_block, &tmp) ){
sffs_error("failed to load block %d\n", hdr_block);
return -1;
}
if ( (tmp.hdr.type != BLOCK_TYPE_FILE_HDR) ){
sffs_error("header block is wrong type 0x%X\n", tmp.hdr.type);
return -1;
}
hdr = (cl_hdr_t*)tmp.data;
switch(status){
case SFFS_SNLIST_ITEM_STATUS_DISCARDING:
sffs_debug(DEBUG_LEVEL, "discarding file data serialno: %d hdr %d list %d\n",
tmp.hdr.serialno,
hdr_block,
hdr->open.content_block);
//Discard all the segments in the file
if ( sffs_filelist_init(cfg, &list, hdr->open.content_block) < 0 ){
sffs_error("failed to open list\n");
return -1;
}
while( sffs_list_getnext(cfg, &list, &file_item, &filelist_addr) == 0 ){
sffs_debug(DEBUG_LEVEL + 2, "discard this block 0x%X\n", file_item.status);
if ( (file_item.status == SFFS_FILELIST_STATUS_CURRENT) || (file_item.status == SFFS_FILELIST_STATUS_OBSOLETE) ){
//if the whole file is discarded, discard all blocks
sffs_debug(DEBUG_LEVEL + 2, "Discarding obsolete block %d\n", file_item.block);
if ( sffs_block_discard(cfg, file_item.block) < 0 ){
sffs_error("failed to discard block\n");
return -1;
}
//mark it dirty in the list
if ( sffs_filelist_setstatus(cfg, SFFS_FILELIST_STATUS_DIRTY, filelist_addr) < 0 ){
sffs_error("failed to set status to dirty\n");
return -1;
}
}
}
case SFFS_SNLIST_ITEM_STATUS_DISCARDING_HDR_LIST:
//Discard the list of file segments
if ( sffs_list_discard(cfg, hdr->open.content_block) ){
sffs_error("failed to discard list\n");
return -1;
}
case SFFS_SNLIST_ITEM_STATUS_DISCARDING_HDR:
//Discard the header
if ( sffs_block_discard(cfg, hdr_block) < 0 ){
sffs_error("failed to discard header\n");
return -1;
}
}
sffs_debug(DEBUG_LEVEL, "Marking file dirty at 0x%X\n", addr);
//the old entry has been deleted
if ( sffs_serialno_setstatus(cfg, addr, SFFS_SNLIST_ITEM_STATUS_DIRTY) < 0 ){
return -1;
}
return 0;
}
|
StratifyLabs/StratifyOS
|
src/sys/sffs/sffs_file.c
|
sffs_file.c
|
c
| 26,975
|
c
|
en
|
code
| 109
|
github-code
|
19
|
70261355243
|
inherit ROOM;
int do_out(string arg);
void create()
{
set("short", "็ญๅญๆกฅ");
set("long", @LONG
่ฟๆฏไธๅบง็ ดๆง็็ณๆกฅ๏ผๆกฅไธๆฏๆคๅๆฒณ็ผ็ผ็ๆตๆฐดใๆฐด็ไธๅปๅพๆธ
๏ผ
่ฟ้ๆฏ่ฟ็ๅฎซๅ้จ็ๅฟ
็ปไน่ทฏใ
LONG);
set("outdoors", "beijing");
set("exits", ([
"north" : __DIR__"di_anmen",
"south" : "/d/huanggong/jingshan",
]));
set("no_clean_up", 0);
set("coor/x", -250);
set("coor/y", 5270);
set("coor/z", 0);
setup();
replace_program(ROOM);
}
|
mudchina/xkx100
|
d/beijing/hbridge.c
|
hbridge.c
|
c
| 500
|
c
|
en
|
code
| 22
|
github-code
|
19
|
69943180844
|
#define _CRT_SECURE_NO_WARNINGS_
//#include<stdio.h>
//int main()
//{
// int x = 10;
// int y = 10;
// x = y = ++y;
// printf("%d %d ",x, y);
// return 0;
//}
//int main()
//{
// int a = 'A' + 1.6;
// printf("%d", a);
// return 0;
//}
#include<stdio.h>
//int removeElement(int* nums, int numsSize, int val)
//{
// int i = 0;
// int j = 0;
// for (i = 0; i < numsSize; i++)
// {
// if (nums[i] == val)
// {
// for (j = i; j < numsSize - 1; j++)
// {
// nums[j] = nums[j + 1];
// }
// numsSize--;
// i--;
// }
// }
// return numsSize;
//}
//int removeElement(int* nums, int numsSize, int val)
//{
// int count = 0;
// int i = 0;
// for (i = 0; i < numsSize; i++)
// {
// if (nums[i] != val)
// {
// nums[count++] = nums[i];
// }
// }
// return count;
//}
//int main()
//{
// int nums[] = { 3,2,2,3,3 };
// int sz = sizeof(nums) / sizeof(nums[0]);
// int val = 3;
// int n = removeElement(nums, sz, val);
// int i = 0;
// for (i = 0; i < n; i++)
// {
// printf("%d", nums[i]);
// }
// return 0;
//}
#include<stdio.h>
int searchInsert(int* nums, int numsSize, int target)
{
int low = 0;
int high = numsSize - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (nums[mid] < target)
{
low = mid + 1;
}
else if (nums[mid] > target)
{
high = mid - 1;
}
}
return low;
}
int main()
{
int nums[] = { 1,3,5,6 };
int sz = sizeof(nums) / sizeof(nums[0]);
int target = 7;
int n = searchInsert(nums, sz, target);
printf("%d", n);
return 0;
}
|
yaozebing/c-code
|
1_13/1_13/1_13.c
|
1_13.c
|
c
| 1,503
|
c
|
uk
|
code
| 0
|
github-code
|
19
|
32016000990
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>
// TODO: remember to add these dynamically
#define DNS_SERVER "8.8.8.8"
#define PORT 53
#define DNS_STATIC_SIZE 17
#define REC_SIZE 1024
#pragma pack(1)
typedef struct dns_hdr {
uint16_t transaction_id;
uint16_t flags;
uint16_t questions;
uint16_t answer_rrs;
uint16_t authority_rrs;
uint16_t addtional_rrs;
uint8_t label_len;
} dns_hdr;
typedef struct domain_label {
uint8_t len;
char* label;
} domain_label;
int generate_trans_id() {
srand(time(0));
return rand();
}
int count_labels(char* domain) {
int len = strlen(domain);
int dots_found = 1;
for(int i = 0; i < len; i++) {
if(domain[i] == '.') {
dots_found++;
}
}
return dots_found;
}
char** extract_labels(char* domain, int labels_count) {
char** labels = (char**)malloc(sizeof(char*) * labels_count);
int counter = 0;
for (int i = 0; i < labels_count; i++) {
labels[i] = (char*)malloc(sizeof(char) * 253);
}
int labels_index = 0;
int last_stop = 0;
int chars_count = 0;
for (int i = 0; i < strlen(domain); i++) {
if (domain[i] == '.') {
for (int j = 0; j < chars_count; j++) {
labels[labels_index][j] = domain[last_stop+j];
}
last_stop = i+1;
labels[labels_index][chars_count] = '\0';
labels_index++;
chars_count = 0;
}
else {
chars_count++;
}
}
for (int j = 0; j < chars_count; j++) {
labels[labels_index][j] = domain[last_stop + j];
}
labels[labels_index][chars_count] = '\0';
labels_index++;
return labels;
}
int copy(int write_start, char* dest, char* src) {
for (int i = 0; i < strlen(src); i++) {
dest[write_start] = src[i];
write_start++;
}
return write_start;
}
char* create_labels_str(char** labels, int count, int labels_count) {
char* buffer = (char*)malloc(sizeof(char)*count);
int buff_counter = 0;
for (int i = 0; i < labels_count; i++) {
buffer[buff_counter] = strlen(labels[i]);
buff_counter++;
buff_counter = copy(buff_counter, buffer, labels[i]);
}
buffer[buff_counter] = 0;
return buffer;
}
// TODO: do not forget to deallocaet heap memory after sending the packet
void* create_packet(char* domain, int* packet_len) {
int domain_len = strlen(domain) + 1;
int total_len = DNS_STATIC_SIZE + domain_len+1;
*packet_len = total_len;
dns_hdr dns;
dns.transaction_id = generate_trans_id();
dns.flags = 1;
((uint8_t*)&(dns.questions))[0] = 0;
((uint8_t*)&(dns.questions))[1] = 1;
dns.answer_rrs = 0;
dns.authority_rrs = 0;
dns.addtional_rrs = 0;
void* dns_buffer = malloc(sizeof(char)*total_len);
memcpy(dns_buffer, &dns, total_len);
char* offseted_buffer = ((char*)(dns_buffer+sizeof(dns_hdr)));
int label_count = count_labels(domain);
char** result = extract_labels(domain, label_count);
char* labels_str = create_labels_str(result, strlen(domain)+2, label_count);
strncpy(offseted_buffer-1, labels_str, strlen(labels_str));
char* offseted_buffer2 = (offseted_buffer+strlen(labels_str));
(offseted_buffer+strlen(labels_str)-1)[0] = 0;
offseted_buffer2[0] = 0;
offseted_buffer2[1] = 1;
offseted_buffer2[2] = 0;
offseted_buffer2[3] = 1;
return dns_buffer;
}
void* send_dns_packet(char* domain, int* packet_len_out) {
int sock = socket(AF_INET, SOCK_DGRAM, 17);
if(sock < 0) {
perror("while creating socket");
exit(-1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
inet_aton(DNS_SERVER, &addr.sin_addr);
int con = connect(sock, (struct sockaddr*)&addr, sizeof(addr));
if(con < 0) {
perror("while trying to connect to DNS Server");
exit(-1);
}
int packet_len = 0;
void* packet = create_packet(domain, &packet_len);
int result = sendto(sock, packet, packet_len, 0, 0, 0);
if(result < 0) {
perror("while sending the packet");
exit(-1);
}
printf("Sent DNS Standard Query Packet\n");
printf("Waiting for an answer...\n");
char temp_buff[REC_SIZE];
memset(temp_buff, 0, REC_SIZE);
int msg_len = recvfrom(sock, temp_buff, REC_SIZE, MSG_WAITALL, 0, 0);
*packet_len_out = msg_len;
void* rec_buffer = malloc(sizeof(char)*msg_len);
memcpy(rec_buffer, temp_buff, msg_len);
close(sock);
free(packet);
return rec_buffer;
}
void extract_ip_address(void* dns_res_packet, int packet_len, char* output) {
unsigned char* ip = ((unsigned char*)dns_res_packet)+packet_len-4;
printf("%d.", ip[0]);
printf("%d.", ip[1]);
printf("%d.", ip[2]);
printf("%d\n", ip[3]);
}
int main(int argc, char* argv[]) {
if(argc != 2) {
printf("Usage: %s <domain-name>\n", argv[0]);
return -1;
}
int packet_len = 0;
void* dns_res_packet = send_dns_packet(argv[1], &packet_len);
char ip[16];
memset(ip, 0, 16);
extract_ip_address(dns_res_packet, packet_len, ip);
free(dns_res_packet);
}
|
ahmedmagdy492/simple_dns_client
|
main.c
|
main.c
|
c
| 5,180
|
c
|
en
|
code
| 0
|
github-code
|
19
|
39384812138
|
//
// Receiver.h
// ๅฝไปคๆจกๅผ
//
// Created by ้ฅถๅๆณข on 2018/8/29.
// Copyright ยฉ 2018ๅนด ้ฅถๅๆณข. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
//ๆญฃ็็ๆง่ก่
,ไนๅฐฑๆฏๅฝไปค็็ๆญฃๆง่ก่
@interface Receiver : NSObject
@property (nonatomic, strong)UIView *receiverView;
- (void)makeDarker:(float)param;
- (void)makeLighter:(float)param;
@end
|
raojunbo/DesignPatterns
|
ๅฝไปคๆจกๅผ/ๅฝไปคๆจกๅผ/Receiver.h
|
Receiver.h
|
h
| 412
|
c
|
en
|
code
| 3
|
github-code
|
19
|
40878961955
|
#ifndef _BOOK_H_
#define _BOOK_H_
#include <iostream>
using namespace std;
class Book
{
public:
string Author;
string Category;
int Pages;
bool Loaned;
Book();
Book(const char*, const char*, int, bool);
~Book();
friend ostream & operator << (ostream &, const Book &);
};
Book::Book()
{
}
Book::Book(const char* Auth, const char* Cat, int pag, bool loa)
{
Author = Auth;
Category = Cat;
Pages = pag;
Loaned = loa;
}
Book::~Book()
{
}
ostream & operator << (ostream & o, const Book & e)
{
o << e.Author << " " << e.Category << " " << "Pages: " << e.Pages << " Loaned: " << e.Loaned;
return o;
}
#endif
|
Krizuu/C_Files_from_old_repo
|
map_book/book.h
|
book.h
|
h
| 615
|
c
|
en
|
code
| 0
|
github-code
|
19
|
19736231859
|
///
/// @file Dictionary.h
/// @author haowang(improvesf@163.com)
/// @date 2018-05-16 14:34:01
///
#ifndef __DICTIONARY_H__
#define __DICTIONARY_H__
#include "Noncopyable.h"
#include <string>
#include <vector>
#include <utility>
#include <unordered_map>
#include <set>
using std::string;
using std::vector;
using std::unordered_map;
using std::set;
using std::pair;
using namespace wd;
namespace hw
{
class Dictionary
:Noncopyable
{
public:
static Dictionary * getInstance();
void initDict(const char * dictPath);
void initIndex(const char* indexPath);
void showDict();
void showIndexTable();
vector<pair<string,size_t>> & getDict();
unordered_map<string,set<size_t>> & getIndexTable();
private:
Dictionary();
~Dictionary();
class AutoRelease
{
public:
AutoRelease();
~AutoRelease();
};
private:
static Dictionary * _pInstance;
static AutoRelease _autoRelease;
vector<pair<string,size_t>> _dict;
//็ดขๅผ่กจๅฐฑๆฏ่ฑๆๅญๆฏๅฏนๅบๅบ็ฐ่ฟไธชๅญๆฏ็ๅ่ฏ็vectorๅญๅ
ธไธๆ
//ไธญๆๅฐฑๆฏไธไธชๆฑๅญๅฏนๅบๅบ็ฐ่ฟไธชๆฑๅญ็่ฏ่ฏญ็vectorๅญๅ
ธไธๆ
unordered_map<string,set<size_t>> _indexTable;
};
}//end of namespace hw
#endif
|
tianxintian/cpp
|
Inputassistant/inc/server/Dictionary.h
|
Dictionary.h
|
h
| 1,213
|
c
|
en
|
code
| 1
|
github-code
|
19
|
6823387031
|
// Tests that inline kickasm uses clause makes the compiler treat the variable in a special way
// Always allocate memory for the variable (do not allow it to be turned into a constant)
char color = 7;
void main() {
kickasm(uses color) {{
lda color
sta $d020
}}
}
|
jbrandwood/kickc
|
src/test/kc/kickasm-uses-0.c
|
kickasm-uses-0.c
|
c
| 291
|
c
|
en
|
code
| 5
|
github-code
|
19
|
38558452212
|
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* abcdefghijklmnopqrstuvwxyz */
const char *WWF_SCORES = "144214331:524214:11125483:";
const char *SCR_SCORES = "1332142418513113:11114484:";
const char *g_scores = NULL;
int g_show_words = 1;
#ifdef __GNUC__
void usage(FILE *f, int exit_code) __attribute((noreturn));
#endif
void usage(FILE *f, int exit_code) {
fprintf(f, "SYNOPSIS\n");
fprintf(f, " wd-score [OPTIONS] [words]\n");
fprintf(f, "\n");
fprintf(f, "DESCRIPTION\n");
fprintf(f, " wd-score will score words using Scrabble or Words-with-Friends tile\n");
fprintf(f, " values.\n");
fprintf(f, "\n");
fprintf(f, " If no words are provided on the command line, words will be read from\n");
fprintf(f, " stdin.\n");
fprintf(f, "\n");
fprintf(f, "OPTIONS\n");
fprintf(f, " -h Print this help info.\n");
fprintf(f, " -s Use Scrabble tile values.\n");
fprintf(f, " -w Use Words-with-Friends tile values. [default]\n");
fprintf(f, " -n Suppress printing words along with scores.\n");
fprintf(f, "\n");
exit(exit_code);
}
int word_score(const char *w) {
int score = 0;
for (; *w; w++) {
unsigned char c = tolower(*w);
if (('a' <= c) && (c <= 'z')) {
score += g_scores[c - 'a'] - '0';
}
}
return score;
}
void print_word_score(const char *w) {
int score = word_score(w);
if (g_show_words) {
printf("%d %s\n", score, w);
} else {
printf("%d\n", score);
}
}
void print_scores_for_line(char *line) {
char *tok = strtok(line, " \t\r\n\"'");
while (tok != NULL) {
print_word_score(tok);
tok = strtok(NULL, " \t\r\n\"'");
}
}
int main(int argc, char *argv[]) {
int ch = 0;
g_scores = WWF_SCORES;
while ((ch = getopt(argc, argv, "hswn")) > 0) {
switch (ch) {
case 'h': usage(stdout, 0); break;
case 's': g_scores = SCR_SCORES; break;
case 'w': g_scores = WWF_SCORES; break;
case 'n': g_show_words = 0; break;
default:
fprintf(stderr, "wd-score: invalid option -%c; use -h for help\n", ch);
return 1;
}
}
argc -= optind;
argv += optind;
if (argc > 0) {
for (int i = 0; i < argc; ++i) {
print_word_score(argv[i]);
}
} else {
char *line = NULL;
size_t line_length = 0;
while (getline(&line, &line_length, stdin) > 0) {
print_scores_for_line(line);
}
free(line);
}
return 0;
}
|
doug16rogers/dr
|
fun/wtools/wd-score.c
|
wd-score.c
|
c
| 2,675
|
c
|
en
|
code
| 3
|
github-code
|
19
|
41664974503
|
#include "cpu/instr.h"
/*
Put the implementations of `push' instructions here.
*/
static void instr_execute_1op()
{
OPERAND temp;
temp.data_size = data_size;
temp.sreg = SREG_DS;
temp.type = OPR_MEM;
operand_read(&opr_src);
cpu.esp -= data_size / 8;
temp.addr = cpu.esp;
temp.val = sign_ext(opr_src.val, opr_src.data_size);
operand_write(&temp);
}
make_instr_impl_1op(push, r, v)
make_instr_impl_1op(push, i, v)
make_instr_impl_1op(push, i, b)
make_instr_impl_1op(push, rm, v)
make_instr_func(pusha){
print_asm_0("pusha", "", 1);
opr_dest.data_size = 32;
opr_dest.type = OPR_MEM;
opr_dest.sreg = SREG_DS;
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.eax;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.ecx;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.edx;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.ebx;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.esp;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.ebp;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.esi;
operand_write(&opr_dest);
cpu.esp -= data_size / 8;
opr_dest.addr = cpu.esp;
opr_dest.val = cpu.edi;
operand_write(&opr_dest);
return 1;
}
|
TF-Liu/NJUCS-PA2020_fall
|
nemu/src/cpu/instr/push.c
|
push.c
|
c
| 1,527
|
c
|
en
|
code
| 3
|
github-code
|
19
|
7531626376
|
/******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, deng@tsinghua.edu.cn
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2006-2013. All rights reserved.
******************************************************************************************/
#pragma once
void readLaby ( char* labyFile ) { //ยถรรรซรรยนยฌ
FILE* fp;
if ( ! ( fp = fopen ( labyFile, "r" ) ) )
{ cout << "can't open " << labyFile << endl; exit ( -1 ); }
fscanf ( fp, "Laby Size = %d\n", &labySize );
if ( LABY_MAX < labySize )
{ cout << "Laby size " << labySize << " > " << LABY_MAX << endl; exit ( -1 ); }
int startX, startY; fscanf ( fp, "Start = (%d, %d)\n", &startX, &startY );
startCell = &laby[startX][startY];
int goalX, goalY; fscanf ( fp, "Goal = (%d, %d)\n", &goalX, &goalY );
goalCell = &laby[goalX][goalY];
for ( int j = 0; j < labySize; j ++ )
for ( int i = 0; i < labySize; i ++ ) {
laby[i][j].x = i;
laby[i][j].y = j;
int type; fscanf ( fp, "%d", &type );
switch ( type ) {
case 1: laby[i][j].status = WALL; break;
case 0: laby[i][j].status = AVAILABLE; break;
default: exit ( -1 );
}
laby[i][j].incoming =
laby[i][j].outgoing = UNKNOWN;
}
fclose ( fp );
}
|
AngelKitty/review_the_national_post-graduate_entrance_examination
|
books_and_notes/professional_courses/data_structures_and_algorithms/sources/cpp_code/course_code/src/laby/readlaby.h
|
readlaby.h
|
h
| 1,518
|
c
|
en
|
code
| 803
|
github-code
|
19
|
35971374372
|
/* This file is part of the UAF (Unified Architecture Framework) project.
*
* Copyright (C) 2012 Wim Pessemier (Institute of Astronomy, KULeuven)
*
* Project website: http://www.ster.kuleuven.be/uaf
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef UAF_MONITORINGMODES_H_
#define UAF_MONITORINGMODES_H_
// STD
#include <string>
// SDK
#include "uabasecpp/uaplatformlayer.h"
// UAF
#include "uaf/util/util.h"
namespace uaf
{
namespace monitoringmodes
{
/**
* The monitoring mode.
*
* @ingroup Util
*/
enum MonitoringMode
{
Disabled = 0, /**< The data source is not monitored. */
Sampling = 1, /**< The data source is being sampled, but not reported. */
Reporting = 2, /**< The data source is being sampled and reported. */
};
/**
* Get a string representation of the monitoring mode.
*
* @param mode The monitoring mode (as an enum).
* @return The corresponding name of the monitoring mode.
*
* @ingroup Util
*/
std::string UAF_EXPORT toString(uaf::monitoringmodes::MonitoringMode mode);
/**
* Convert the SDK/Stack instance to a UAF instance.
*
* @ingroup Util
*/
MonitoringMode UAF_EXPORT fromSdkToUaf(OpcUa_MonitoringMode mode);
/**
* Convert the UAF instance to a SDK/Stack instance.
*
* @ingroup Util
*/
OpcUa_MonitoringMode UAF_EXPORT fromUafToSdk(MonitoringMode mode);
}
}
#endif /* UAF_MONITORINGMODES_H_ */
|
uaf/uaf
|
src/uaf/util/monitoringmodes.h
|
monitoringmodes.h
|
h
| 2,282
|
c
|
en
|
code
| 104
|
github-code
|
19
|
17175262920
|
char *ft_strcpy(char *s1, char *s2)
{
int i;
i = 0;
while (s2[i])
{
s1[i] = s2[i];
i++;
}
s1[i] = s2[i];
return (s2);
}
/*-------------------------------TEST BELOW-----------------------------------*/
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putstr(char *str)
{
int i;
i = 0;
while(str[i])
{
ft_putchar(str[i]);
i++;
}
}
int main()
{
char src[13] = "i like bread";
char dest[13] = "";
ft_putstr(ft_strcpy(dest, src));
return (0);
}
|
Nylux/Prep-Exam-Final
|
t1/ft_strcpy/ft_strcpy.c
|
ft_strcpy.c
|
c
| 572
|
c
|
en
|
code
| 0
|
github-code
|
19
|
14675139434
|
#ifndef _SFTP_MKDIR_H_
#define _SFTP_MKDIR_H_
#include "sftp_operation.h"
#include <string>
#include "CreateDirRequest.h"
namespace sftp
{
/* Class: sftp_mkdir
* Description: Used to create a directory on the remote host
*/
class sftp_mkdir : sftp_operation
{
public:
sftp_mkdir(const wchar_t * path, sftp_notify * notify, sftp_impl * impl)
: sftp_operation(notify, impl), m_path(path),m_request(0)
{
}
sftp_mkdir(const std::wstring & path, sftp_notify * notify, sftp_impl * impl)
: sftp_operation(notify, impl), m_path(path), m_request(0)
{
}
OperationStatus handle_reply(const sftp_hdr & hdr, ssh::IStreamIO *)
{
return StatusError;
}
// writes a message to the buffer.
OperationStatus write(ssh::ArrayStream * stream, uint32 id)
{
m_request = new (std::nothrow) CreateDirRequest(m_path,m_impl);
if(m_request == NULL) {
std::cerr << "Could not create the CreateDirRequest instance" << std::endl;
return OperationError;
}
sftp_request_base status = m_request->write(stream,id);
}
private:
std::wstring m_path;
CreateDirRequest * m_request;
};
};
#endif
|
magnusl/ssh
|
src/sftp_mkdir.h
|
sftp_mkdir.h
|
h
| 1,397
|
c
|
en
|
code
| 0
|
github-code
|
19
|
150616070
|
#include <sys/resource.h>
#include <stdio.h>
#include <inttypes.h>
#include "bmp.h"
#include "file.h"
#include "image.h"
#include "sepia.h"
#include "utils.h"
#define OUT stderr
#define EXECUTABLE "image-transformer"
static const char *r_msg[] = {
[READ_INVALID_SIGNATURE] ="Invalid bitmap signature",
[READ_INVALID_BITS] = "Invalid number of bits",
[READ_INVALID_HEADER] = "Invalid bitmap header"
};
static const char *w_msg[] = {
[WRITE_ERROR] = "Error while writing"
};
void usage() {
fprintf(OUT, "Usage: ./" EXECUTABLE " <source-image>\n");
}
static void test_avg_time(struct image, int, FILE *);
int main(int argc, char *argv[]) {
if (argc != 2) usage();
if (argc < 2) err("Not enough arguments\n");
if (argc > 2) err("Too many arguments\n");
FILE *in, *out_c, *out_asm;
if (file_open(&in, argv[1], "rb") != 0 ||
file_open(&out_c, "sepia_out_c.bmp", "wb") != 0 ||
file_open(&out_asm, "sepia_out_asm.bmp", "wb") != 0) {
err("Could not open the file for reading\n");
}
struct image source = {0};
enum read_status rstat = from_bmp(in, &source);
file_close(&in);
if (rstat != READ_OK) {
fprintf(OUT, "%s\n", r_msg[rstat]);
return rstat;
}
struct image img_c = sepia_c_inplace(source);
struct image img_asm = sepia_sse(source);
enum write_status wstat_c = to_bmp(out_c, &img_c);
file_close(&out_c);
if (wstat_c != WRITE_OK) {
image_destroy(&img_c);
fprintf(OUT, "%s\n", w_msg[wstat_c]);
}
enum write_status wstat_asm = to_bmp(out_asm, &img_asm);
file_close(&out_asm);
if (wstat_asm != WRITE_OK) {
image_destroy(&img_asm);
fprintf(OUT, "%s\n", w_msg[wstat_asm]);
}
fprintf(OUT, "Image size: %" PRId32 "x%" PRId32 "\n", source.dims.width, source.dims.height);
test_avg_time(source, 64, OUT);
image_destroy(&source);
image_destroy(&img_c);
image_destroy(&img_asm);
return 0;
}
static void test_avg_time(struct image img, int n, FILE *file) {
struct rusage r;
struct timeval start, middle, end;
long total_c = 0, total_asm = 0;
for (int i = 0; i < n; i++) {
getrusage(RUSAGE_SELF, &r);
start = r.ru_utime;
struct image img_c = sepia_c_inplace(img);
getrusage(RUSAGE_SELF, &r);
middle = r.ru_utime;
struct image img_asm = sepia_sse(img);
getrusage(RUSAGE_SELF, &r);
end = r.ru_utime;
total_c += ((middle.tv_sec - start.tv_sec) * 1000000L) + middle.tv_usec - start.tv_usec;
total_asm += ((end.tv_sec - middle.tv_sec) * 1000000L) + end.tv_usec - middle.tv_usec;
image_destroy(&img_c);
image_destroy(&img_asm);
}
fprintf(file, "Avg time elapsed in microseconds for c: %ld\n", total_c / n);
fprintf(file, "Avg time elapsed in microseconds for asm: %ld\n", total_asm / n);
}
|
octoant/low-level-programming
|
src/main.c
|
main.c
|
c
| 2,756
|
c
|
en
|
code
| 1
|
github-code
|
19
|
4761437549
|
#include "rule.h"
static int dirRow[4] = {0, 1, 1, 1};
static int dirCol[4] = {1, 0, 1, -1};
static int checkGomokuInDirection(board_t board, char chess, int row, int col, int dir) {
int i, moku = 1;
// to negative direction
int r = row, c = col, dr = dirRow[dir], dc = dirCol[dir];
for (i = 1; i < 5; i++) {
r -= dr;
c -= dc;
if (!is_valid_pos(r, c)) {
break;
}
if (board[r][c] != chess) {
break;
}
}
moku += i - 1;
// to positive direction
r = row;
c = col;
for (i = 1; i < 5; i++) {
r += dr;
c += dc;
if (!is_valid_pos(r, c)) {
break;
}
if (board[r][c] != chess) {
break;
}
}
moku += i - 1;
// result
return (moku >= 5);
}
static int checkGomoku(board_t board, char chess, int row, int col) {
for (int i = 0; i < 4; i++) {
if (checkGomokuInDirection(board, chess, row, col, i)) return 1;
}
return 0;
}
int rule_judgeWinner(board_t board, int lastTurn, int lastPlayRow, int lastPlayColumn) {
// empty board
if (lastPlayRow < 0) {
return -1;
}
// non-empty board
char lastPlayChess;
if (lastTurn == ROLE_PLAYER) {
lastPlayChess = GRID_PLAYER;
} else {
lastPlayChess = GRID_GOMOKO;
}
if (checkGomoku(board, lastPlayChess, lastPlayRow, lastPlayColumn)) {
return lastTurn;
} else {
return -1;
}
}
|
Hidden-me/Gomoku
|
src/rule.c
|
rule.c
|
c
| 1,503
|
c
|
en
|
code
| 0
|
github-code
|
19
|
23997603341
|
#pragma once
#include <bits/stdc++.h>
#include <search_space.h>
#include <state_space.h>
namespace planner
{
class Node
{
public:
Node() = delete;
Node(const world::Vector2 &data) : data_(data), parent_(nullptr), cost_(std::numeric_limits<double>::max()), id_(idCounter_++) {}
Node(const Node &other) : data_(other.data_), parent_(other.parent_), cost_(other.cost_), children_(other.children_), id_(idCounter_++) {}
~Node()
{
children_.clear();
}
world::Vector2 data_;
double cost_;
static unsigned int idCounter_;
unsigned int id_;
std::shared_ptr<Node> parent_;
std::vector<std::shared_ptr<Node>> children_;
};
class Tree
{
public:
Tree() {}
~Tree()
{
nodes_.clear();
root_.reset();
root_ = nullptr;
}
void reset()
{
nodes_.clear();
root_.reset();
root_ = nullptr;
}
bool nodeExists(const world::Vector2 &, std::shared_ptr<Node> &);
bool nodeExists(const world::Vector2 &, std::shared_ptr<Node> &) const;
std::shared_ptr<Node> addNode(const world::Vector2 &);
std::shared_ptr<Node> root_;
std::map<std::size_t, std::shared_ptr<Node>> nodes_;
};
class RRTConfig
{
public:
RRTConfig()
{
minStepSize_ = 0.0;
maxStepSize_ = 20.0;
maxIterations_ = 100;
minIterations_ = 10;
goalClosenessThreshold_ = 1.0;
}
RRTConfig(const RRTConfig &other)
{
minStepSize_ = other.minStepSize_;
maxStepSize_ = other.maxStepSize_;
maxIterations_ = other.maxIterations_;
minIterations_ = other.minIterations_;
goalClosenessThreshold_ = other.goalClosenessThreshold_;
}
void print()
{
std::cout << "\n--------RRT CONFIG--------\n";
std::cout << "Max Iterations : [" << maxIterations_ << "]\n";
std::cout << "Min Iterations : [" << minIterations_ << "]\n";
std::cout << "Min Step Size : [" << minStepSize_ << "]\n";
std::cout << "Max Step Size : [" << maxStepSize_ << "]\n";
std::cout << "Goal Closeness Threshold: [" << goalClosenessThreshold_ << "]\n";
std::cout << "--------------------------\n";
}
void print() const
{
std::cout << "\n--------RRT CONFIG--------\n";
std::cout << "Max Iterations : [" << maxIterations_ << "]\n";
std::cout << "Min Iterations : [" << minIterations_ << "]\n";
std::cout << "Min Step Size : [" << minStepSize_ << "]\n";
std::cout << "Max Step Size : [" << maxStepSize_ << "]\n";
std::cout << "Goal Closeness Threshold: [" << goalClosenessThreshold_ << "]\n";
std::cout << "--------------------------\n";
}
double minStepSize_;
double maxStepSize_;
unsigned int maxIterations_;
unsigned int minIterations_;
double goalClosenessThreshold_;
};
class RRT
{
public:
RRT() = delete;
RRT(const world::SearchGrid2 &, const RRTConfig &);
~RRT() {}
bool pathFound() { return pathFound_; }
bool pathFound() const { return pathFound_; }
world::Path2 path();
world::Path2 path() const;
double pathLength();
double pathLength() const;
std::shared_ptr<Tree> tree() { return std::make_shared<Tree>(tree_); }
std::shared_ptr<Tree> tree() const { return std::make_shared<Tree>(tree_); }
void reset();
bool findPath(const world::Vector2 &, const world::Vector2 &);
std::shared_ptr<Node> getNodeClosestTo(const world::Vector2 &, double &);
private:
double getRandomStepSize();
Tree tree_;
std::shared_ptr<world::SearchGrid2> searchGridPtr;
RRTConfig config_;
unsigned int numIterations_;
bool pathFound_;
std::shared_ptr<Node> goalNode_;
};
}
|
arihantb2/rrt
|
include/rrt.h
|
rrt.h
|
h
| 4,268
|
c
|
en
|
code
| 1
|
github-code
|
19
|
72069792043
|
/**
*
* @file ClockLabelWindow.h
*
* Declaration of class ClockLabelWindow.
*
* @author Patrick Schwab
* @date 5/23/12
*
*/
#pragma once
#include <QtGui/QWidget.h>
#include "Observer.h"
#include "ClockModel.h"
class QLabel;
/**
* @class ClockLabelWindow
*
* This class implements a widget for displaying a clock model in digital form.
*
* @author Patrick Schwab
*/
class ClockLabelWindow : public QWidget, public Observer {
public:
ClockLabelWindow(ClockModel* model);
private:
QLabel* label;
ClockModel* model;
void valueChanged(Observable* observable);
};
|
d909b/SWPUE5-Observer
|
SWPUE5-Observer/ClockLabelWindow.h
|
ClockLabelWindow.h
|
h
| 587
|
c
|
en
|
code
| 1
|
github-code
|
19
|
30384082972
|
// general constants used by the kernel
//
//
#if (CHIP == INTEL)
#define K_STACK_BYTES 1024 // kernel stack bytes
#define INIT_PSW 0x0200 // initial psw
#define INIT_TASK_PSW 0x1200 // initial psw of task(IOPL is 1)
#define TRACEBIT 0x100 // take psw and OR of proc[] and use them for tracing
#define SETPSW(rp,new) /* allow setting only certain bits */ \
((rp)->p_reg.psw = (rp)->p_reg.psw & 0xCD5 | (new) & 0xCD5)
// initial sp for mm,fs and init
// * 2bytes for short jamp
// * 2bytes are not used
// * 3words for init_org[] used by only fs
// * real mode debugger trap is 3words( actually need one more )
// * 3words for temporary save and restart
// * 3words for interrupt
// no margin left to flush bugs early
//
#define INIT_SP (2 + 2 + 3*2 + 3*2 + 3*2 + 3*2)
#define HCLICK_SHIFT 4 // log2 of HCLICK_SIZE
#define HCLICK_SIZE 16 // hardware segment conversion magic
#if CLICK_SIZE >= HCLICK_SIZE
#define click_to_hclick(n) ((n) << (CLICK_SHIFT - HCLICK_SHIFT))
#else
#define click_to_hclick(n) ((n) >> (HCLICK_SHIFT - CLICK_SHIFT))
#endif // CLICK_SIZE >= HCLICK_SIZE
#define hclick_to_physb(n) ((phys_bytes) (n) << HCLICK_SHIFT)
#define physb_to_hclick(n) ((n) >> HCLICK_SHIFT)
// interrupt vector defined/reserved by the processor
#define DIVIDE_VECTOR 0 // split error
#define DEBUG_VECTOR 1 // single step (trace)
#define NMI_VECTOR 2 // unmaskable interrupt
#define BREAKPOINT_VECTOR 3 // software break point
#define OVERFLOW_VECTOR 4 // from INTO
// fixed sysytem call vector
#define SYS_VECTOR 32 // make system calls with int SYSVEC
#define SYS386_VECTOR 33 // use this except 386 system call
#define LEVEL0_VECTOR 34 // for function execution in lebel 0
// IRQ base suitable for hardware interrupts. the BIOS does not respect the vectors
// reserverd for all processors and reprograms using the default settings in the PC BIOS.
#define BIOS_IRQ0_VEC 0x08 // IRQ0-7 vector base used by BIOS
#define BIOS_IRQ8_VEC 0x70 // IRQ8-15 vector base used by BIOS
#define IRQ0_VECTOR 0x28 // more or less optional,but greater than SYS_VECTOR
#define IRQ8_VECTOR 0x30 // bulk for brevity
// hardware interrupt number
#define NR_IRQ_VECTOR 16
#define CLOCK_IRQ 0
#define KEYBOARD_IRQ 1
#define CASCADE_IRQ 2 // valid cascade for 2nd AT controller
#define ETHER_IRQ 3 // default ethernet interrupt vector
#define SECONDARY_IRQ 3 // RS232 interrupt vector of port 2
#define RS232_IRQ 4 // RS232 interrupt vector of port 1
#define XT_WINI_IRQ 5 // xt winchester
#define FLOPPY_IRQ 6 // floppy disk
#define PRINTER_IRQ 7
#define AT_WINI_IRQ 14 // AT winchester
// interrupt number to hardware vector
#define BIOS_VECTOR(irq) (((irq) < 8 ? BIOS_IRQ0_VEC : BIOS_IRQ8_VEC) + ((irq) & 0x07))
#define VECTOR(irq) (((irq) < 8 ? IRQ0_VECTOR : IRQ8_VECTOR) + ((irq) & 0x07))
// BIOS hardware disk parameter vector
#define WINI_0_PARM_VEC 0x41
#define WINI_1_PARM_VEC 0x46
// 8259A interrupt controller port
#define INT_CTL 0x20 // I/O port for interrupt controller
#define INT_CTLMASK 0x21 // setting bit to disable interrupts on this port
#define INT2_CTL 0xA0 // I/O port for secondary interrupt controller
#define INT2_CTLMASK 0xA1 // setting bit to disable interrupts on this port
// magic number of interrupt controller
#define ENABLE 0x20 // after interrupt,code used to re-enable
// size of memory table
#define NR_MEMS 3 // number of memory chunks
// other port
#define PCR 0x65 // planer control register
#define PORT_B 0x61 // I/O port of 8255 port B(keyboard,mother...)
#define TIMER0 0x40 // I/O port of timer channel 0
#define TIMER2 0x42 // I/O port of timer channel 2
#define TIMER_MODE 0x43 // I/O port of timer mode control
#endif // (CHIP == INTEL)
#if (CHIP == M68000)
#define K_STACK_BYTES 1024 // number of bytes of kernel stack
// size of memory table
#define NR_MEMS 2 // number of memory chunks
// p_reg includes d0-d7,a0-a6 in this order
#define NR_REGS 15 // number of general registers in each process slot
#define TRACEBIT 0x8000 // take psw and OR of proc[] and use them for tracing
#define SETPSW(rp,new) /* allow only certain bits to be set */ \
((rp)->p_reg.psw = (rp)->p_reg.psw & 0xFF | (new) & 0xFF)
#define MEM_BYTES 0xffffffff // memory size of /dev/mem
#ifdef __ACK__
#define FSTRUCOPY
#endif
#endif // (CHIP == M68000)
// the following items are related to the scheduling queue.
#define TASK_0 0 // execution town tasks are scheduled in queue 0
#define TASK_1 1 // execution town tasks are scheduled in queue 1
#define TASK_2 2 // execution town tasks are scheduled in queue 2
#if (MACHINE == ATARI)
#define SHADOW_Q 3 // executable,but shadow process
#define NQ 4 // number of scheduling queue
#else
#define NQ 3 // number of scheduling queue
#endif // (CHIP == ATARI)
// Env_parse() return values.
#define EP_UNSET 0 // variables that are not set
#define EP_OFF 1 // var = off
#define EP_ON 2 // var = on
#define EP_SET 3 // var = 1:2:3(without blank field)
// replace the kernel space address with the physical address.
// this is the same as umap(proc_ptr,D,vir,sizeof(*vir)) , but at a much lower cost.
#define vir2phys(vir) (data_base + (vir_bytes) (vir))
#define printf printk // the kernel actually uses printk instead of printf
|
tatsuya4649/minix
|
src/kernel/const.h
|
const.h
|
h
| 5,331
|
c
|
en
|
code
| 0
|
github-code
|
19
|
15501383601
|
#include <errno.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include "smtpd.h"
#include "log.h"
#define PROTOCOL_VERSION "0.7"
struct filter;
struct filter_session;
static void filter_protocol_internal(struct filter_session *, uint64_t *, uint64_t, enum filter_phase, const char *);
static void filter_protocol(uint64_t, enum filter_phase, const char *);
static void filter_protocol_next(uint64_t, uint64_t, enum filter_phase);
static void filter_protocol_query(struct filter *, uint64_t, uint64_t, const char *, const char *);
static void filter_data_internal(struct filter_session *, uint64_t, uint64_t, const char *);
static void filter_data(uint64_t, const char *);
static void filter_data_next(uint64_t, uint64_t, const char *);
static void filter_data_query(struct filter *, uint64_t, uint64_t, const char *);
static int filter_builtins_notimpl(struct filter_session *, struct filter *, uint64_t, const char *);
static int filter_builtins_connect(struct filter_session *, struct filter *, uint64_t, const char *);
static int filter_builtins_helo(struct filter_session *, struct filter *, uint64_t, const char *);
static int filter_builtins_mail_from(struct filter_session *, struct filter *, uint64_t, const char *);
static int filter_builtins_rcpt_to(struct filter_session *, struct filter *, uint64_t, const char *);
static int filter_builtins_data(struct filter_session *, struct filter *, uint64_t, const char *);
static int filter_builtins_commit(struct filter_session *, struct filter *, uint64_t, const char *);
static void filter_result_proceed(uint64_t);
static void filter_result_junk(uint64_t);
static void filter_result_rewrite(uint64_t, const char *);
static void filter_result_reject(uint64_t, const char *);
static void filter_result_disconnect(uint64_t, const char *);
static void filter_session_io(struct io *, int, void *);
void lka_filter_process_response(const char *, const char *);
struct filter_session {
uint64_t id;
struct io *io;
char *lastparam;
char *filter_name;
struct sockaddr_storage ss_src;
struct sockaddr_storage ss_dest;
char *rdns;
int fcrdns;
char *helo;
char *username;
char *mail_from;
enum filter_phase phase;
};
static struct filter_exec {
enum filter_phase phase;
const char *phase_name;
int (*func)(struct filter_session *, struct filter *, uint64_t, const char *);
} filter_execs[FILTER_PHASES_COUNT] = {
{ FILTER_CONNECT, "connect", filter_builtins_connect },
{ FILTER_HELO, "helo", filter_builtins_helo },
{ FILTER_EHLO, "ehlo", filter_builtins_helo },
{ FILTER_STARTTLS, "starttls", filter_builtins_notimpl },
{ FILTER_AUTH, "auth", filter_builtins_notimpl },
{ FILTER_MAIL_FROM, "mail-from", filter_builtins_mail_from },
{ FILTER_RCPT_TO, "rcpt-to", filter_builtins_rcpt_to },
{ FILTER_DATA, "data", filter_builtins_data },
{ FILTER_DATA_LINE, "data-line", filter_builtins_notimpl },
{ FILTER_RSET, "rset", filter_builtins_notimpl },
{ FILTER_QUIT, "quit", filter_builtins_notimpl },
{ FILTER_NOOP, "noop", filter_builtins_notimpl },
{ FILTER_HELP, "help", filter_builtins_notimpl },
{ FILTER_WIZ, "wiz", filter_builtins_notimpl },
{ FILTER_COMMIT, "commit", filter_builtins_commit },
};
struct filter {
uint64_t id;
uint32_t phases;
const char *name;
const char *proc;
struct filter **chain;
size_t chain_size;
struct filter_config *config;
};
static struct dict filters;
struct filter_entry {
TAILQ_ENTRY(filter_entry) entries;
uint64_t id;
const char *name;
};
struct filter_chain {
TAILQ_HEAD(, filter_entry) chain[nitems(filter_execs)];
};
static struct tree sessions;
static int filters_inited;
static struct dict filter_chains;
struct reporter_proc {
TAILQ_ENTRY(reporter_proc) entries;
const char *name;
};
TAILQ_HEAD(reporters, reporter_proc);
static struct dict report_smtp_in;
static struct dict report_smtp_out;
static struct smtp_events {
const char *event;
} smtp_events[] = {
{ "link-connect" },
{ "link-disconnect" },
{ "link-greeting" },
{ "link-identify" },
{ "link-tls" },
{ "link-auth" },
{ "tx-reset" },
{ "tx-begin" },
{ "tx-mail" },
{ "tx-rcpt" },
{ "tx-envelope" },
{ "tx-data" },
{ "tx-commit" },
{ "tx-rollback" },
{ "protocol-client" },
{ "protocol-server" },
{ "filter-report" },
{ "filter-response" },
{ "timeout" },
};
static int processors_inited = 0;
static struct dict processors;
struct processor_instance {
char *name;
struct io *io;
struct io *errfd;
int ready;
uint32_t subsystems;
};
static void processor_io(struct io *, int, void *);
static void processor_errfd(struct io *, int, void *);
void lka_filter_process_response(const char *, const char *);
int
lka_proc_ready(void)
{
void *iter;
struct processor_instance *pi;
iter = NULL;
while (dict_iter(&processors, &iter, NULL, (void **)&pi))
if (!pi->ready)
return 0;
return 1;
}
static void
lka_proc_config(struct processor_instance *pi)
{
io_printf(pi->io, "config|smtpd-version|%s\n", SMTPD_VERSION);
io_printf(pi->io, "config|smtp-session-timeout|%d\n", SMTPD_SESSION_TIMEOUT);
if (pi->subsystems & FILTER_SUBSYSTEM_SMTP_IN)
io_printf(pi->io, "config|subsystem|smtp-in\n");
if (pi->subsystems & FILTER_SUBSYSTEM_SMTP_OUT)
io_printf(pi->io, "config|subsystem|smtp-out\n");
io_printf(pi->io, "config|admd|%s\n",
env->sc_admd != NULL ? env->sc_admd : env->sc_hostname);
io_printf(pi->io, "config|ready\n");
}
void
lka_proc_forked(const char *name, uint32_t subsystems, int fd)
{
struct processor_instance *processor;
if (!processors_inited) {
dict_init(&processors);
processors_inited = 1;
}
processor = xcalloc(1, sizeof *processor);
processor->name = xstrdup(name);
processor->io = io_new();
processor->subsystems = subsystems;
io_set_nonblocking(fd);
io_set_fd(processor->io, fd);
io_set_callback(processor->io, processor_io, processor->name);
dict_xset(&processors, name, processor);
}
void
lka_proc_errfd(const char *name, int fd)
{
struct processor_instance *processor;
processor = dict_xget(&processors, name);
io_set_nonblocking(fd);
processor->errfd = io_new();
io_set_fd(processor->errfd, fd);
io_set_callback(processor->errfd, processor_errfd, processor->name);
lka_proc_config(processor);
}
struct io *
lka_proc_get_io(const char *name)
{
struct processor_instance *processor;
processor = dict_xget(&processors, name);
return processor->io;
}
static void
processor_register(const char *name, const char *line)
{
struct processor_instance *processor;
processor = dict_xget(&processors, name);
if (strcmp(line, "register|ready") == 0) {
processor->ready = 1;
return;
}
if (strncmp(line, "register|report|", 16) == 0) {
lka_report_register_hook(name, line+16);
return;
}
if (strncmp(line, "register|filter|", 16) == 0) {
lka_filter_register_hook(name, line+16);
return;
}
fatalx("Invalid register line received: %s", line);
}
static void
processor_io(struct io *io, int evt, void *arg)
{
struct processor_instance *processor;
const char *name = arg;
char *line = NULL;
ssize_t len;
switch (evt) {
case IO_DATAIN:
while ((line = io_getline(io, &len)) != NULL) {
if (strncmp("register|", line, 9) == 0) {
processor_register(name, line);
continue;
}
processor = dict_xget(&processors, name);
if (!processor->ready)
fatalx("Non-register message before register|"
"ready: %s", line);
else if (strncmp(line, "filter-result|", 14) == 0 ||
strncmp(line, "filter-dataline|", 16) == 0)
lka_filter_process_response(name, line);
else if (strncmp(line, "report|", 7) == 0)
lka_report_proc(name, line);
else
fatalx("Invalid filter message type: %s", line);
}
}
}
static void
processor_errfd(struct io *io, int evt, void *arg)
{
const char *name = arg;
char *line = NULL;
ssize_t len;
switch (evt) {
case IO_DATAIN:
while ((line = io_getline(io, &len)) != NULL)
log_warnx("%s: %s", name, line);
}
}
void
lka_filter_init(void)
{
void *iter;
const char *name;
struct filter *filter;
struct filter_config *filter_config;
size_t i;
char buffer[LINE_MAX]; /* for traces */
dict_init(&filters);
dict_init(&filter_chains);
/* first pass, allocate and init individual filters */
iter = NULL;
while (dict_iter(env->sc_filters_dict, &iter, &name, (void **)&filter_config)) {
switch (filter_config->filter_type) {
case FILTER_TYPE_BUILTIN:
filter = xcalloc(1, sizeof(*filter));
filter->name = name;
filter->phases |= (1<<filter_config->phase);
filter->config = filter_config;
dict_set(&filters, name, filter);
log_trace(TRACE_FILTERS, "filters init type=builtin, name=%s, hooks=%08x",
name, filter->phases);
break;
case FILTER_TYPE_PROC:
filter = xcalloc(1, sizeof(*filter));
filter->name = name;
filter->proc = filter_config->proc;
filter->config = filter_config;
dict_set(&filters, name, filter);
log_trace(TRACE_FILTERS, "filters init type=proc, name=%s, proc=%s",
name, filter_config->proc);
break;
case FILTER_TYPE_CHAIN:
break;
}
}
/* second pass, allocate and init filter chains but don't build yet */
iter = NULL;
while (dict_iter(env->sc_filters_dict, &iter, &name, (void **)&filter_config)) {
switch (filter_config->filter_type) {
case FILTER_TYPE_CHAIN:
filter = xcalloc(1, sizeof(*filter));
filter->name = name;
filter->chain = xcalloc(filter_config->chain_size, sizeof(void **));
filter->chain_size = filter_config->chain_size;
filter->config = filter_config;
buffer[0] = '\0';
for (i = 0; i < filter->chain_size; ++i) {
filter->chain[i] = dict_xget(&filters, filter_config->chain[i]);
if (i)
(void)strlcat(buffer, ", ", sizeof buffer);
(void)strlcat(buffer, filter->chain[i]->name, sizeof buffer);
}
log_trace(TRACE_FILTERS, "filters init type=chain, name=%s { %s }", name, buffer);
dict_set(&filters, name, filter);
break;
case FILTER_TYPE_BUILTIN:
case FILTER_TYPE_PROC:
break;
}
}
}
void
lka_filter_register_hook(const char *name, const char *hook)
{
struct filter *filter;
const char *filter_name;
void *iter;
size_t i;
if (strncasecmp(hook, "smtp-in|", 8) == 0) {
hook += 8;
}
else
fatalx("Invalid message direction: %s", hook);
for (i = 0; i < nitems(filter_execs); i++)
if (strcmp(hook, filter_execs[i].phase_name) == 0)
break;
if (i == nitems(filter_execs))
fatalx("Unrecognized report name: %s", hook);
iter = NULL;
while (dict_iter(&filters, &iter, &filter_name, (void **)&filter))
if (filter->proc && strcmp(name, filter->proc) == 0)
filter->phases |= (1<<filter_execs[i].phase);
}
void
lka_filter_ready(void)
{
struct filter *filter;
struct filter *subfilter;
const char *filter_name;
struct filter_entry *filter_entry;
struct filter_chain *filter_chain;
void *iter;
size_t i;
size_t j;
/* all filters are ready, actually build the filter chains */
iter = NULL;
while (dict_iter(&filters, &iter, &filter_name, (void **)&filter)) {
filter_chain = xcalloc(1, sizeof *filter_chain);
for (i = 0; i < nitems(filter_execs); i++)
TAILQ_INIT(&filter_chain->chain[i]);
dict_set(&filter_chains, filter_name, filter_chain);
if (filter->chain) {
for (i = 0; i < filter->chain_size; i++) {
subfilter = filter->chain[i];
for (j = 0; j < nitems(filter_execs); ++j) {
if (subfilter->phases & (1<<j)) {
filter_entry = xcalloc(1, sizeof *filter_entry);
filter_entry->id = generate_uid();
filter_entry->name = subfilter->name;
TAILQ_INSERT_TAIL(&filter_chain->chain[j],
filter_entry, entries);
}
}
}
continue;
}
for (i = 0; i < nitems(filter_execs); ++i) {
if (filter->phases & (1<<i)) {
filter_entry = xcalloc(1, sizeof *filter_entry);
filter_entry->id = generate_uid();
filter_entry->name = filter_name;
TAILQ_INSERT_TAIL(&filter_chain->chain[i],
filter_entry, entries);
}
}
}
}
int
lka_filter_proc_in_session(uint64_t reqid, const char *proc)
{
struct filter_session *fs;
struct filter *filter;
size_t i;
if ((fs = tree_get(&sessions, reqid)) == NULL)
return 0;
filter = dict_get(&filters, fs->filter_name);
if (filter == NULL || (filter->proc == NULL && filter->chain == NULL))
return 0;
if (filter->proc)
return strcmp(filter->proc, proc) == 0 ? 1 : 0;
for (i = 0; i < filter->chain_size; i++)
if (filter->chain[i]->proc &&
strcmp(filter->chain[i]->proc, proc) == 0)
return 1;
return 0;
}
void
lka_filter_begin(uint64_t reqid, const char *filter_name)
{
struct filter_session *fs;
if (!filters_inited) {
tree_init(&sessions);
filters_inited = 1;
}
fs = xcalloc(1, sizeof (struct filter_session));
fs->id = reqid;
fs->filter_name = xstrdup(filter_name);
tree_xset(&sessions, fs->id, fs);
log_trace(TRACE_FILTERS, "%016"PRIx64" filters session-begin", reqid);
}
void
lka_filter_end(uint64_t reqid)
{
struct filter_session *fs;
fs = tree_xpop(&sessions, reqid);
free(fs->rdns);
free(fs->helo);
free(fs->mail_from);
free(fs->username);
free(fs->lastparam);
free(fs->filter_name);
free(fs);
log_trace(TRACE_FILTERS, "%016"PRIx64" filters session-end", reqid);
}
void
lka_filter_data_begin(uint64_t reqid)
{
struct filter_session *fs;
int sp[2];
int fd = -1;
fs = tree_xget(&sessions, reqid);
if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
goto end;
io_set_nonblocking(sp[0]);
io_set_nonblocking(sp[1]);
fd = sp[0];
fs->io = io_new();
io_set_fd(fs->io, sp[1]);
io_set_callback(fs->io, filter_session_io, fs);
end:
m_create(p_dispatcher, IMSG_FILTER_SMTP_DATA_BEGIN, 0, 0, fd);
m_add_id(p_dispatcher, reqid);
m_add_int(p_dispatcher, fd != -1 ? 1 : 0);
m_close(p_dispatcher);
log_trace(TRACE_FILTERS, "%016"PRIx64" filters data-begin fd=%d", reqid, fd);
}
void
lka_filter_data_end(uint64_t reqid)
{
struct filter_session *fs;
fs = tree_xget(&sessions, reqid);
if (fs->io) {
io_free(fs->io);
fs->io = NULL;
}
log_trace(TRACE_FILTERS, "%016"PRIx64" filters data-end", reqid);
}
static void
filter_session_io(struct io *io, int evt, void *arg)
{
struct filter_session *fs = arg;
char *line = NULL;
ssize_t len;
log_trace(TRACE_IO, "filter session: %p: %s %s", fs, io_strevent(evt),
io_strio(io));
switch (evt) {
case IO_DATAIN:
nextline:
line = io_getline(fs->io, &len);
/* No complete line received */
if (line == NULL)
return;
filter_data(fs->id, line);
goto nextline;
}
}
void
lka_filter_process_response(const char *name, const char *line)
{
uint64_t reqid;
uint64_t token;
char *ep = NULL;
const char *kind = NULL;
const char *qid = NULL;
const char *response = NULL;
const char *parameter = NULL;
struct filter_session *fs;
kind = line;
if ((ep = strchr(kind, '|')) == NULL)
fatalx("Missing token: %s", line);
qid = ep+1;
errno = 0;
reqid = strtoull(qid, &ep, 16);
if (qid[0] == '\0' || *ep != '|')
fatalx("Invalid reqid: %s", line);
if (errno == ERANGE && reqid == ULLONG_MAX)
fatal("Invalid reqid: %s", line);
qid = ep + 1;
token = strtoull(qid, &ep, 16);
if (qid[0] == '\0' || *ep != '|')
fatalx("Invalid token: %s", line);
if (errno == ERANGE && token == ULLONG_MAX)
fatal("Invalid token: %s", line);
response = ep+1;
/* session can legitimately disappear on a resume */
if ((fs = tree_get(&sessions, reqid)) == NULL)
return;
if (strncmp(kind, "filter-dataline|", 16) == 0) {
if (fs->phase != FILTER_DATA_LINE)
fatalx("filter-dataline out of dataline phase");
filter_data_next(token, reqid, response);
return;
}
if (fs->phase == FILTER_DATA_LINE)
fatalx("filter-result in dataline phase");
if ((ep = strchr(response, '|')) != NULL)
parameter = ep + 1;
if (strcmp(response, "proceed") == 0) {
filter_protocol_next(token, reqid, 0);
return;
} else if (strcmp(response, "junk") == 0) {
if (fs->phase == FILTER_COMMIT)
fatalx("filter-reponse junk after DATA");
filter_result_junk(reqid);
return;
} else {
if (parameter == NULL)
fatalx("Missing parameter: %s", line);
if (strncmp(response, "rewrite|", 8) == 0)
filter_result_rewrite(reqid, parameter);
else if (strncmp(response, "reject|", 7) == 0)
filter_result_reject(reqid, parameter);
else if (strncmp(response, "disconnect|", 11) == 0)
filter_result_disconnect(reqid, parameter);
else
fatalx("Invalid directive: %s", line);
}
}
void
lka_filter_protocol(uint64_t reqid, enum filter_phase phase, const char *param)
{
filter_protocol(reqid, phase, param);
}
static void
filter_protocol_internal(struct filter_session *fs, uint64_t *token, uint64_t reqid, enum filter_phase phase, const char *param)
{
struct filter_chain *filter_chain;
struct filter_entry *filter_entry;
struct filter *filter;
struct timeval tv;
const char *phase_name = filter_execs[phase].phase_name;
int resume = 1;
if (!*token) {
fs->phase = phase;
resume = 0;
}
/* XXX - this sanity check requires a protocol change, stub for now */
phase = fs->phase;
if (fs->phase != phase)
fatalx("misbehaving filter");
/* based on token, identify the filter_entry we should apply */
filter_chain = dict_get(&filter_chains, fs->filter_name);
filter_entry = TAILQ_FIRST(&filter_chain->chain[fs->phase]);
if (*token) {
TAILQ_FOREACH(filter_entry, &filter_chain->chain[fs->phase], entries)
if (filter_entry->id == *token)
break;
if (filter_entry == NULL)
fatalx("misbehaving filter");
filter_entry = TAILQ_NEXT(filter_entry, entries);
}
/* no filter_entry, we either had none or reached end of chain */
if (filter_entry == NULL) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, resume=%s, "
"action=proceed",
fs->id, phase_name, resume ? "y" : "n");
filter_result_proceed(reqid);
return;
}
/* process param with current filter_entry */
*token = filter_entry->id;
filter = dict_get(&filters, filter_entry->name);
if (filter->proc) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=deferred, filter=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name);
filter_protocol_query(filter, filter_entry->id, reqid,
filter_execs[fs->phase].phase_name, param);
return; /* deferred response */
}
if (filter_execs[fs->phase].func(fs, filter, reqid, param)) {
if (filter->config->rewrite) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=rewrite, filter=%s, query=%s, response=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param,
filter->config->rewrite);
filter_result_rewrite(reqid, filter->config->rewrite);
return;
}
else if (filter->config->disconnect) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=disconnect, filter=%s, query=%s, response=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param,
filter->config->disconnect);
filter_result_disconnect(reqid, filter->config->disconnect);
return;
}
else if (filter->config->junk) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=junk, filter=%s, query=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param);
filter_result_junk(reqid);
return;
} else if (filter->config->report) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=report, filter=%s, query=%s response=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param, filter->config->report);
gettimeofday(&tv, NULL);
lka_report_filter_report(fs->id, filter->name, 1,
"smtp-in", &tv, filter->config->report);
} else if (filter->config->bypass) {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=bypass, filter=%s, query=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param);
filter_result_proceed(reqid);
return;
} else {
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=reject, filter=%s, query=%s, response=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param,
filter->config->reject);
filter_result_reject(reqid, filter->config->reject);
return;
}
}
log_trace(TRACE_FILTERS, "%016"PRIx64" filters protocol phase=%s, "
"resume=%s, action=proceed, filter=%s, query=%s",
fs->id, phase_name, resume ? "y" : "n",
filter->name,
param);
/* filter_entry resulted in proceed, try next filter */
filter_protocol_internal(fs, token, reqid, phase, param);
return;
}
static void
filter_data_internal(struct filter_session *fs, uint64_t token, uint64_t reqid, const char *line)
{
struct filter_chain *filter_chain;
struct filter_entry *filter_entry;
struct filter *filter;
if (!token)
fs->phase = FILTER_DATA_LINE;
if (fs->phase != FILTER_DATA_LINE)
fatalx("misbehaving filter");
/* based on token, identify the filter_entry we should apply */
filter_chain = dict_get(&filter_chains, fs->filter_name);
filter_entry = TAILQ_FIRST(&filter_chain->chain[fs->phase]);
if (token) {
TAILQ_FOREACH(filter_entry, &filter_chain->chain[fs->phase], entries)
if (filter_entry->id == token)
break;
if (filter_entry == NULL)
fatalx("misbehaving filter");
filter_entry = TAILQ_NEXT(filter_entry, entries);
}
/* no filter_entry, we either had none or reached end of chain */
if (filter_entry == NULL) {
io_printf(fs->io, "%s\n", line);
return;
}
/* pass data to the filter */
filter = dict_get(&filters, filter_entry->name);
filter_data_query(filter, filter_entry->id, reqid, line);
}
static void
filter_protocol(uint64_t reqid, enum filter_phase phase, const char *param)
{
struct filter_session *fs;
uint64_t token = 0;
char *nparam = NULL;
fs = tree_xget(&sessions, reqid);
switch (phase) {
case FILTER_HELO:
case FILTER_EHLO:
free(fs->helo);
fs->helo = xstrdup(param);
break;
case FILTER_MAIL_FROM:
free(fs->mail_from);
fs->mail_from = xstrdup(param + 1);
*strchr(fs->mail_from, '>') = '\0';
param = fs->mail_from;
break;
case FILTER_RCPT_TO:
nparam = xstrdup(param + 1);
*strchr(nparam, '>') = '\0';
param = nparam;
break;
case FILTER_STARTTLS:
/* TBD */
break;
default:
break;
}
free(fs->lastparam);
fs->lastparam = xstrdup(param);
filter_protocol_internal(fs, &token, reqid, phase, param);
if (nparam)
free(nparam);
}
static void
filter_protocol_next(uint64_t token, uint64_t reqid, enum filter_phase phase)
{
struct filter_session *fs;
/* session can legitimately disappear on a resume */
if ((fs = tree_get(&sessions, reqid)) == NULL)
return;
filter_protocol_internal(fs, &token, reqid, phase, fs->lastparam);
}
static void
filter_data(uint64_t reqid, const char *line)
{
struct filter_session *fs;
fs = tree_xget(&sessions, reqid);
filter_data_internal(fs, 0, reqid, line);
}
static void
filter_data_next(uint64_t token, uint64_t reqid, const char *line)
{
struct filter_session *fs;
/* session can legitimately disappear on a resume */
if ((fs = tree_get(&sessions, reqid)) == NULL)
return;
filter_data_internal(fs, token, reqid, line);
}
static void
filter_protocol_query(struct filter *filter, uint64_t token, uint64_t reqid, const char *phase, const char *param)
{
int n;
struct filter_session *fs;
struct timeval tv;
gettimeofday(&tv, NULL);
fs = tree_xget(&sessions, reqid);
if (strcmp(phase, "connect") == 0)
n = io_printf(lka_proc_get_io(filter->proc),
"filter|%s|%lld.%06ld|smtp-in|%s|%016"PRIx64"|%016"PRIx64"|%s|%s\n",
PROTOCOL_VERSION,
(long long)tv.tv_sec, (long)tv.tv_usec,
phase, reqid, token, fs->rdns, param);
else
n = io_printf(lka_proc_get_io(filter->proc),
"filter|%s|%lld.%06ld|smtp-in|%s|%016"PRIx64"|%016"PRIx64"|%s\n",
PROTOCOL_VERSION,
(long long)tv.tv_sec, (long)tv.tv_usec,
phase, reqid, token, param);
if (n == -1)
fatalx("failed to write to processor");
}
static void
filter_data_query(struct filter *filter, uint64_t token, uint64_t reqid, const char *line)
{
int n;
struct timeval tv;
gettimeofday(&tv, NULL);
n = io_printf(lka_proc_get_io(filter->proc),
"filter|%s|%lld.%06ld|smtp-in|data-line|"
"%016"PRIx64"|%016"PRIx64"|%s\n",
PROTOCOL_VERSION,
(long long)tv.tv_sec, (long)tv.tv_usec,
reqid, token, line);
if (n == -1)
fatalx("failed to write to processor");
}
static void
filter_result_proceed(uint64_t reqid)
{
m_create(p_dispatcher, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
m_add_id(p_dispatcher, reqid);
m_add_int(p_dispatcher, FILTER_PROCEED);
m_close(p_dispatcher);
}
static void
filter_result_junk(uint64_t reqid)
{
m_create(p_dispatcher, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
m_add_id(p_dispatcher, reqid);
m_add_int(p_dispatcher, FILTER_JUNK);
m_close(p_dispatcher);
}
static void
filter_result_rewrite(uint64_t reqid, const char *param)
{
m_create(p_dispatcher, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
m_add_id(p_dispatcher, reqid);
m_add_int(p_dispatcher, FILTER_REWRITE);
m_add_string(p_dispatcher, param);
m_close(p_dispatcher);
}
static void
filter_result_reject(uint64_t reqid, const char *message)
{
m_create(p_dispatcher, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
m_add_id(p_dispatcher, reqid);
m_add_int(p_dispatcher, FILTER_REJECT);
m_add_string(p_dispatcher, message);
m_close(p_dispatcher);
}
static void
filter_result_disconnect(uint64_t reqid, const char *message)
{
m_create(p_dispatcher, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1);
m_add_id(p_dispatcher, reqid);
m_add_int(p_dispatcher, FILTER_DISCONNECT);
m_add_string(p_dispatcher, message);
m_close(p_dispatcher);
}
/* below is code for builtin filters */
static int
filter_check_rdns_table(struct filter *filter, enum table_service kind, const char *key)
{
int ret = 0;
if (filter->config->rdns_table == NULL)
return 0;
if (table_match(filter->config->rdns_table, kind, key) > 0)
ret = 1;
return filter->config->not_rdns_table < 0 ? !ret : ret;
}
static int
filter_check_rdns_regex(struct filter *filter, const char *key)
{
int ret = 0;
if (filter->config->rdns_regex == NULL)
return 0;
if (table_match(filter->config->rdns_regex, K_REGEX, key) > 0)
ret = 1;
return filter->config->not_rdns_regex < 0 ? !ret : ret;
}
static int
filter_check_src_table(struct filter *filter, enum table_service kind, const char *key)
{
int ret = 0;
if (filter->config->src_table == NULL)
return 0;
if (table_match(filter->config->src_table, kind, key) > 0)
ret = 1;
return filter->config->not_src_table < 0 ? !ret : ret;
}
static int
filter_check_src_regex(struct filter *filter, const char *key)
{
int ret = 0;
if (filter->config->src_regex == NULL)
return 0;
if (table_match(filter->config->src_regex, K_REGEX, key) > 0)
ret = 1;
return filter->config->not_src_regex < 0 ? !ret : ret;
}
static int
filter_check_helo_table(struct filter *filter, enum table_service kind, const char *key)
{
int ret = 0;
if (filter->config->helo_table == NULL)
return 0;
if (table_match(filter->config->helo_table, kind, key) > 0)
ret = 1;
return filter->config->not_helo_table < 0 ? !ret : ret;
}
static int
filter_check_helo_regex(struct filter *filter, const char *key)
{
int ret = 0;
if (filter->config->helo_regex == NULL)
return 0;
if (table_match(filter->config->helo_regex, K_REGEX, key) > 0)
ret = 1;
return filter->config->not_helo_regex < 0 ? !ret : ret;
}
static int
filter_check_auth(struct filter *filter, const char *username)
{
int ret = 0;
if (!filter->config->auth)
return 0;
ret = username ? 1 : 0;
return filter->config->not_auth < 0 ? !ret : ret;
}
static int
filter_check_auth_table(struct filter *filter, enum table_service kind, const char *key)
{
int ret = 0;
if (filter->config->auth_table == NULL)
return 0;
if (key && table_match(filter->config->auth_table, kind, key) > 0)
ret = 1;
return filter->config->not_auth_table < 0 ? !ret : ret;
}
static int
filter_check_auth_regex(struct filter *filter, const char *key)
{
int ret = 0;
if (filter->config->auth_regex == NULL)
return 0;
if (key && table_match(filter->config->auth_regex, K_REGEX, key) > 0)
ret = 1;
return filter->config->not_auth_regex < 0 ? !ret : ret;
}
static int
filter_check_mail_from_table(struct filter *filter, enum table_service kind, const char *key)
{
int ret = 0;
if (filter->config->mail_from_table == NULL)
return 0;
if (table_match(filter->config->mail_from_table, kind, key) > 0)
ret = 1;
return filter->config->not_mail_from_table < 0 ? !ret : ret;
}
static int
filter_check_mail_from_regex(struct filter *filter, const char *key)
{
int ret = 0;
if (filter->config->mail_from_regex == NULL)
return 0;
if (table_match(filter->config->mail_from_regex, K_REGEX, key) > 0)
ret = 1;
return filter->config->not_mail_from_regex < 0 ? !ret : ret;
}
static int
filter_check_rcpt_to_table(struct filter *filter, enum table_service kind, const char *key)
{
int ret = 0;
if (filter->config->rcpt_to_table == NULL)
return 0;
if (table_match(filter->config->rcpt_to_table, kind, key) > 0)
ret = 1;
return filter->config->not_rcpt_to_table < 0 ? !ret : ret;
}
static int
filter_check_rcpt_to_regex(struct filter *filter, const char *key)
{
int ret = 0;
if (filter->config->rcpt_to_regex == NULL)
return 0;
if (table_match(filter->config->rcpt_to_regex, K_REGEX, key) > 0)
ret = 1;
return filter->config->not_rcpt_to_regex < 0 ? !ret : ret;
}
static int
filter_check_fcrdns(struct filter *filter, int fcrdns)
{
int ret = 0;
if (!filter->config->fcrdns)
return 0;
ret = fcrdns == 1;
return filter->config->not_fcrdns < 0 ? !ret : ret;
}
static int
filter_check_rdns(struct filter *filter, const char *hostname)
{
int ret = 0;
struct netaddr netaddr;
if (!filter->config->rdns)
return 0;
/* this is a hack until smtp session properly deals with lack of rdns */
ret = strcmp("<unknown>", hostname);
if (ret == 0)
return filter->config->not_rdns < 0 ? !ret : ret;
/* if text_to_netaddress succeeds,
* we don't have an rDNS so the filter should match
*/
ret = !text_to_netaddr(&netaddr, hostname);
return filter->config->not_rdns < 0 ? !ret : ret;
}
static int
filter_builtins_notimpl(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return 0;
}
static int
filter_builtins_global(struct filter_session *fs, struct filter *filter, uint64_t reqid)
{
return filter_check_fcrdns(filter, fs->fcrdns) ||
filter_check_rdns(filter, fs->rdns) ||
filter_check_rdns_table(filter, K_DOMAIN, fs->rdns) ||
filter_check_rdns_regex(filter, fs->rdns) ||
filter_check_src_table(filter, K_NETADDR, ss_to_text(&fs->ss_src)) ||
filter_check_src_regex(filter, ss_to_text(&fs->ss_src)) ||
filter_check_helo_table(filter, K_DOMAIN, fs->helo) ||
filter_check_helo_regex(filter, fs->helo) ||
filter_check_auth(filter, fs->username) ||
filter_check_auth_table(filter, K_STRING, fs->username) ||
filter_check_auth_table(filter, K_CREDENTIALS, fs->username) ||
filter_check_auth_regex(filter, fs->username) ||
filter_check_mail_from_table(filter, K_MAILADDR, fs->mail_from) ||
filter_check_mail_from_regex(filter, fs->mail_from);
}
static int
filter_builtins_connect(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return filter_builtins_global(fs, filter, reqid);
}
static int
filter_builtins_helo(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return filter_builtins_global(fs, filter, reqid);
}
static int
filter_builtins_mail_from(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return filter_builtins_global(fs, filter, reqid);
}
static int
filter_builtins_rcpt_to(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return filter_builtins_global(fs, filter, reqid) ||
filter_check_rcpt_to_table(filter, K_MAILADDR, param) ||
filter_check_rcpt_to_regex(filter, param);
}
static int
filter_builtins_data(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return filter_builtins_global(fs, filter, reqid);
}
static int
filter_builtins_commit(struct filter_session *fs, struct filter *filter, uint64_t reqid, const char *param)
{
return filter_builtins_global(fs, filter, reqid);
}
static void
report_smtp_broadcast(uint64_t, const char *, struct timeval *, const char *,
const char *, ...) __attribute__((__format__ (printf, 5, 6)));
void
lka_report_init(void)
{
struct reporters *tailq;
size_t i;
dict_init(&report_smtp_in);
dict_init(&report_smtp_out);
for (i = 0; i < nitems(smtp_events); ++i) {
tailq = xcalloc(1, sizeof (struct reporters));
TAILQ_INIT(tailq);
dict_xset(&report_smtp_in, smtp_events[i].event, tailq);
tailq = xcalloc(1, sizeof (struct reporters));
TAILQ_INIT(tailq);
dict_xset(&report_smtp_out, smtp_events[i].event, tailq);
}
}
void
lka_report_register_hook(const char *name, const char *hook)
{
struct dict *subsystem;
struct reporter_proc *rp;
struct reporters *tailq;
void *iter;
size_t i;
if (strncmp(hook, "smtp-in|", 8) == 0) {
subsystem = &report_smtp_in;
hook += 8;
}
else if (strncmp(hook, "smtp-out|", 9) == 0) {
subsystem = &report_smtp_out;
hook += 9;
}
else
fatalx("Invalid message direction: %s", hook);
if (strcmp(hook, "*") == 0) {
iter = NULL;
while (dict_iter(subsystem, &iter, NULL, (void **)&tailq)) {
rp = xcalloc(1, sizeof *rp);
rp->name = xstrdup(name);
TAILQ_INSERT_TAIL(tailq, rp, entries);
}
return;
}
for (i = 0; i < nitems(smtp_events); i++)
if (strcmp(hook, smtp_events[i].event) == 0)
break;
if (i == nitems(smtp_events))
fatalx("Unrecognized report name: %s", hook);
tailq = dict_get(subsystem, hook);
rp = xcalloc(1, sizeof *rp);
rp->name = xstrdup(name);
TAILQ_INSERT_TAIL(tailq, rp, entries);
}
static void
report_smtp_broadcast(uint64_t reqid, const char *direction, struct timeval *tv, const char *event,
const char *format, ...)
{
va_list ap;
struct dict *d;
struct reporters *tailq;
struct reporter_proc *rp;
if (strcmp("smtp-in", direction) == 0)
d = &report_smtp_in;
else if (strcmp("smtp-out", direction) == 0)
d = &report_smtp_out;
else
fatalx("unexpected direction: %s", direction);
tailq = dict_xget(d, event);
TAILQ_FOREACH(rp, tailq, entries) {
if (!lka_filter_proc_in_session(reqid, rp->name))
continue;
va_start(ap, format);
if (io_printf(lka_proc_get_io(rp->name),
"report|%s|%lld.%06ld|%s|%s|%016"PRIx64"%s",
PROTOCOL_VERSION, (long long)tv->tv_sec, (long)tv->tv_usec,
direction, event, reqid,
format[0] != '\n' ? "|" : "") == -1 ||
io_vprintf(lka_proc_get_io(rp->name), format, ap) == -1)
fatalx("failed to write to processor");
va_end(ap);
}
}
void
lka_report_smtp_link_connect(const char *direction, struct timeval *tv, uint64_t reqid, const char *rdns,
int fcrdns,
const struct sockaddr_storage *ss_src,
const struct sockaddr_storage *ss_dest)
{
struct filter_session *fs;
char src[NI_MAXHOST + 5];
char dest[NI_MAXHOST + 5];
uint16_t src_port = 0;
uint16_t dest_port = 0;
const char *fcrdns_str;
if (ss_src->ss_family == AF_INET)
src_port = ntohs(((const struct sockaddr_in *)ss_src)->sin_port);
else if (ss_src->ss_family == AF_INET6)
src_port = ntohs(((const struct sockaddr_in6 *)ss_src)->sin6_port);
if (ss_dest->ss_family == AF_INET)
dest_port = ntohs(((const struct sockaddr_in *)ss_dest)->sin_port);
else if (ss_dest->ss_family == AF_INET6)
dest_port = ntohs(((const struct sockaddr_in6 *)ss_dest)->sin6_port);
if (strcmp(ss_to_text(ss_src), "local") == 0) {
(void)snprintf(src, sizeof src, "unix:%s", SMTPD_SOCKET);
(void)snprintf(dest, sizeof dest, "unix:%s", SMTPD_SOCKET);
} else {
(void)snprintf(src, sizeof src, "%s:%d", ss_to_text(ss_src), src_port);
(void)snprintf(dest, sizeof dest, "%s:%d", ss_to_text(ss_dest), dest_port);
}
switch (fcrdns) {
case 1:
fcrdns_str = "pass";
break;
case 0:
fcrdns_str = "fail";
break;
default:
fcrdns_str = "error";
break;
}
fs = tree_xget(&sessions, reqid);
fs->rdns = xstrdup(rdns);
fs->fcrdns = fcrdns;
fs->ss_src = *ss_src;
fs->ss_dest = *ss_dest;
report_smtp_broadcast(reqid, direction, tv, "link-connect",
"%s|%s|%s|%s\n", rdns, fcrdns_str, src, dest);
}
void
lka_report_smtp_link_disconnect(const char *direction, struct timeval *tv, uint64_t reqid)
{
report_smtp_broadcast(reqid, direction, tv, "link-disconnect", "\n");
}
void
lka_report_smtp_link_greeting(const char *direction, uint64_t reqid,
struct timeval *tv, const char *domain)
{
report_smtp_broadcast(reqid, direction, tv, "link-greeting", "%s\n",
domain);
}
void
lka_report_smtp_link_auth(const char *direction, struct timeval *tv, uint64_t reqid,
const char *username, const char *result)
{
struct filter_session *fs;
if (strcmp(result, "pass") == 0) {
fs = tree_xget(&sessions, reqid);
fs->username = xstrdup(username);
}
report_smtp_broadcast(reqid, direction, tv, "link-auth", "%s|%s\n",
result, username);
}
void
lka_report_smtp_link_identify(const char *direction, struct timeval *tv,
uint64_t reqid, const char *method, const char *heloname)
{
report_smtp_broadcast(reqid, direction, tv, "link-identify", "%s|%s\n",
method, heloname);
}
void
lka_report_smtp_link_tls(const char *direction, struct timeval *tv, uint64_t reqid, const char *ciphers)
{
report_smtp_broadcast(reqid, direction, tv, "link-tls", "%s\n",
ciphers);
}
void
lka_report_smtp_tx_reset(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid)
{
report_smtp_broadcast(reqid, direction, tv, "tx-reset", "%08x\n",
msgid);
}
void
lka_report_smtp_tx_begin(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid)
{
report_smtp_broadcast(reqid, direction, tv, "tx-begin", "%08x\n",
msgid);
}
void
lka_report_smtp_tx_mail(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, const char *address, int ok)
{
const char *result;
switch (ok) {
case 1:
result = "ok";
break;
case 0:
result = "permfail";
break;
default:
result = "tempfail";
break;
}
report_smtp_broadcast(reqid, direction, tv, "tx-mail", "%08x|%s|%s\n",
msgid, result, address);
}
void
lka_report_smtp_tx_rcpt(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, const char *address, int ok)
{
const char *result;
switch (ok) {
case 1:
result = "ok";
break;
case 0:
result = "permfail";
break;
default:
result = "tempfail";
break;
}
report_smtp_broadcast(reqid, direction, tv, "tx-rcpt", "%08x|%s|%s\n",
msgid, result, address);
}
void
lka_report_smtp_tx_envelope(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, uint64_t evpid)
{
report_smtp_broadcast(reqid, direction, tv, "tx-envelope",
"%08x|%016"PRIx64"\n", msgid, evpid);
}
void
lka_report_smtp_tx_data(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, int ok)
{
const char *result;
switch (ok) {
case 1:
result = "ok";
break;
case 0:
result = "permfail";
break;
default:
result = "tempfail";
break;
}
report_smtp_broadcast(reqid, direction, tv, "tx-data", "%08x|%s\n",
msgid, result);
}
void
lka_report_smtp_tx_commit(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid, size_t msgsz)
{
report_smtp_broadcast(reqid, direction, tv, "tx-commit", "%08x|%zd\n",
msgid, msgsz);
}
void
lka_report_smtp_tx_rollback(const char *direction, struct timeval *tv, uint64_t reqid, uint32_t msgid)
{
report_smtp_broadcast(reqid, direction, tv, "tx-rollback", "%08x\n",
msgid);
}
void
lka_report_smtp_protocol_client(const char *direction, struct timeval *tv, uint64_t reqid, const char *command)
{
report_smtp_broadcast(reqid, direction, tv, "protocol-client", "%s\n",
command);
}
void
lka_report_smtp_protocol_server(const char *direction, struct timeval *tv, uint64_t reqid, const char *response)
{
report_smtp_broadcast(reqid, direction, tv, "protocol-server", "%s\n",
response);
}
void
lka_report_smtp_filter_response(const char *direction, struct timeval *tv, uint64_t reqid,
int phase, int response, const char *param)
{
const char *phase_name;
const char *response_name;
switch (phase) {
case FILTER_CONNECT:
phase_name = "connected";
break;
case FILTER_HELO:
phase_name = "helo";
break;
case FILTER_EHLO:
phase_name = "ehlo";
break;
case FILTER_STARTTLS:
phase_name = "tls";
break;
case FILTER_AUTH:
phase_name = "auth";
break;
case FILTER_MAIL_FROM:
phase_name = "mail-from";
break;
case FILTER_RCPT_TO:
phase_name = "rcpt-to";
break;
case FILTER_DATA:
phase_name = "data";
break;
case FILTER_DATA_LINE:
phase_name = "data-line";
break;
case FILTER_RSET:
phase_name = "rset";
break;
case FILTER_QUIT:
phase_name = "quit";
break;
case FILTER_NOOP:
phase_name = "noop";
break;
case FILTER_HELP:
phase_name = "help";
break;
case FILTER_WIZ:
phase_name = "wiz";
break;
case FILTER_COMMIT:
phase_name = "commit";
break;
default:
phase_name = "";
}
switch (response) {
case FILTER_PROCEED:
response_name = "proceed";
break;
case FILTER_JUNK:
response_name = "junk";
break;
case FILTER_REWRITE:
response_name = "rewrite";
break;
case FILTER_REJECT:
response_name = "reject";
break;
case FILTER_DISCONNECT:
response_name = "disconnect";
break;
default:
response_name = "";
}
report_smtp_broadcast(reqid, direction, tv, "filter-response",
"%s|%s%s%s\n", phase_name, response_name, param ? "|" : "",
param ? param : "");
}
void
lka_report_smtp_timeout(const char *direction, struct timeval *tv, uint64_t reqid)
{
report_smtp_broadcast(reqid, direction, tv, "timeout", "\n");
}
void
lka_report_filter_report(uint64_t reqid, const char *name, int builtin,
const char *direction, struct timeval *tv, const char *message)
{
report_smtp_broadcast(reqid, direction, tv, "filter-report",
"%s|%s|%s\n", builtin ? "builtin" : "proc",
name, message);
}
void
lka_report_proc(const char *name, const char *line)
{
char buffer[LINE_MAX];
struct timeval tv;
char *ep, *sp, *direction;
uint64_t reqid;
if (strlcpy(buffer, line + 7, sizeof(buffer)) >= sizeof(buffer))
fatalx("Invalid report: line too long: %s", line);
errno = 0;
tv.tv_sec = strtoll(buffer, &ep, 10);
if (ep[0] != '.' || errno != 0)
fatalx("Invalid report: invalid time: %s", line);
sp = ep + 1;
tv.tv_usec = strtol(sp, &ep, 10);
if (ep[0] != '|' || errno != 0)
fatalx("Invalid report: invalid time: %s", line);
if (ep - sp != 6)
fatalx("Invalid report: invalid time: %s", line);
direction = ep + 1;
if (strncmp(direction, "smtp-in|", 8) == 0) {
direction[7] = '\0';
direction += 7;
#if 0
} else if (strncmp(direction, "smtp-out|", 9) == 0) {
direction[8] = '\0';
direction += 8;
#endif
} else
fatalx("Invalid report: invalid direction: %s", line);
reqid = strtoull(sp, &ep, 16);
if (ep[0] != '|' || errno != 0)
fatalx("Invalid report: invalid reqid: %s", line);
sp = ep + 1;
lka_report_filter_report(reqid, name, 0, direction, &tv, sp);
}
|
openbsd/src
|
usr.sbin/smtpd/lka_filter.c
|
lka_filter.c
|
c
| 43,758
|
c
|
en
|
code
| 2,915
|
github-code
|
19
|
11342113594
|
#include <string.h>
#include <math.h>
#include "vec.h"
#include "drend.h"
#include "render.h"
const float fov_x = 90.0;
void
R_Init (void)
{
camera.center_x = vid.w / 2.0;
camera.center_y = vid.h / 2.0;
camera.fov_x = fov_x * (M_PI / 180.0);
camera.dist = (vid.w / 2.0) / tan(camera.fov_x / 2.0);
camera.fov_y = 2.0 * atan((vid.h / 2.0) / camera.dist);
Vec_Clear (camera.pos);
camera.altitude = 0.0;
camera.angle = 0.0;
S_SpanInit ();
}
void
R_Shutdown (void)
{
S_SpanCleanup ();
}
static void
CalcCamera (void)
{
double s, c;
float n[2];
float cam2world[2][2];
Vec_RotationMatrix (-camera.angle, cam2world);
s = sin (camera.fov_x / 2.0);
c = cos (camera.fov_x / 2.0);
n[0] = -c;
n[1] = s;
Vec_Transform (cam2world, n, camera.vplanes[VPLANE_LEFT].normal);
camera.vplanes[VPLANE_LEFT].dist = Vec_Dot (camera.vplanes[VPLANE_LEFT].normal, camera.pos);
n[0] = c;
n[1] = s;
Vec_Transform (cam2world, n, camera.vplanes[VPLANE_RIGHT].normal);
camera.vplanes[VPLANE_RIGHT].dist = Vec_Dot (camera.vplanes[VPLANE_RIGHT].normal, camera.pos);
/* world-to-camera transformation matrix */
Vec_RotationMatrix (camera.angle, camera.xform);
}
/*
* Traverse the world and set up structures to prepare drawing to the
* frame buffer.
*/
void
R_DrawScene (void)
{
CalcCamera ();
R_DrawWall (NULL);
//...
}
static void
PutPixel (int x, int y, int c)
{
if (x >= 0 && x < vid.w && y >= 0 && y < vid.h)
{
// vid.rows[y][x] = c & 0xffff;
S_ClipAndEmitSpan (x, y, y);
}
}
static void
RenderPoint (float x, float y, float z)
{
float v[2], local[2], out[2];
v[0] = x;
v[1] = z;
{
struct viewplane_s *p;
p = &camera.vplanes[VPLANE_LEFT];
if (Vec_Dot(v, p->normal) - p->dist < (1 / 32.0))
return;
p = &camera.vplanes[VPLANE_RIGHT];
if (Vec_Dot(v, p->normal) - p->dist < (1 / 32.0))
return;
}
Vec_Subtract (v, camera.pos, local);
Vec_Transform (camera.xform, local, out);
if (out[1] > 0.0)
{
int sx = camera.center_x - camera.dist * (out[0] / out[1]) + 0.5;
int sy = camera.center_y - camera.dist * ((y - camera.altitude) / out[1]) + 0.5;
PutPixel (sx, sy, 0xffff);
}
}
/*
* Draw to the frame buffer.
*/
void
R_RenderScene (void)
{
if (1)
{
int x, z;
for (x = -50; x < 50; x++)
{
float scale = 4.0;
for (z = -50; z < 50; z++)
RenderPoint(x*scale, 0, z*scale);
}
}
if (1)
S_RenderGSpans ();
}
|
fielder/drend
|
r_main.c
|
r_main.c
|
c
| 2,384
|
c
|
en
|
code
| 0
|
github-code
|
19
|
16806571687
|
#include "main.h"
/**
* main - the entry point to the program. Prints all args on a new line.
* @argc: returns the number of arguments passed during run time
* @argv: array of space sperated arguments passed to CLI during runtime
* Return: returns zero indicating successful.
*/
int main(int argc, char *argv[])
{
int j;
for (j = 0; j < argc; j++)
{
printf("%s\n", argv[j]);
}
return (0);
}
|
JosiahUfono/alx-low_level_programming
|
0x0A-argc_argv/2-args.c
|
2-args.c
|
c
| 405
|
c
|
en
|
code
| 0
|
github-code
|
19
|
72168737643
|
#include <stdint.h>
#include "gba.h"
#include "timer.h"
#include "irq.h"
#include "peripherals/peripherals.h"
#include "mem.h"
#include "linker.h"
#include "utils.h"
#include "swifunctions.h"
#include "dma.h"
#define WRAM0_BEGIN 0x02000000
#define WRAM0_SIZE 0x40000
#define WRAM1_BEGIN 0x03000000
#define WRAM1_SIZE 0x8000
#define PALETTE_RAM_BEGIN 0x05000000
#define PALETTE_RAM_SIZE 0x400
#define VRAM_BEGIN 0x06000000
#define VRAM_SIZE 0x18000
#define OAM_BEGIN 0x07000000
#define OAM_SIZE 0x400
#define SRAM_GAMEPAK_BEGIN 0x0E000000
#define SRAM_GAMEPAK_SIZE 0x10000
static void *wram1;
static void patchBios(uint32_t *biosdata)
{
// Replace GBA SVC vector entry by System SVC vector entry
uint32_t *gbaSvcVector = biosdata + (0x1c8 >> 2);
/* Patch custom bios functions */
// Replace IntrWait (svc 0x04)
gbaSvcVector[4] = (uint32_t)SWI_IntrWait;
// Replace VBlankIntrWait (svc 0x05)
gbaSvcVector[5] = (uint32_t)SWI_VBlankIntrWait;
// Replace "return from interrupt" instruction of IRQ handler
biosdata[0x13c >> 2] = 0xe12fff1e; // bx lr
}
void GBALoadComponents(void)
{
unsigned int i;
void *alignedGbaBios = Memalloc(GBA_BIOS_SIZE, 0x1000);
void *wram0 = Memcalloc(WRAM0_SIZE, 0x1000);
wram1 = Memcalloc(WRAM1_SIZE, 0x1000);
void *paletteRam = Memcalloc(PALETTE_RAM_SIZE, 0x1000);
void *vram = Memcalloc(VRAM_SIZE, 0x1000);
void *oam = Memcalloc(OAM_SIZE, 0x1000);
void *sramGamePak = Memcalloc(SRAM_GAMEPAK_SIZE, 0x1000);
DMACopy32(alignedGbaBios, (void*)GBABIOS_BEGIN,
(GBABIOS_END - GBABIOS_BEGIN) >> 2);
// Code modifications
patchBios(alignedGbaBios);
// Map BIOS
MMUPopulateRange(0x00000000, (uint32_t) alignedGbaBios, GBA_BIOS_SIZE,
READWRITE);
// Map ROM and its mirrors
for(i = 0; i < 3; ++i)
MMUPopulateRange(0x08000000 + i * 0x02000000, (uint32_t) GBAROM_BEGIN,
GBA_ROM_SIZE, READWRITE);
// Map GBA memories
MMUPopulateRange(WRAM0_BEGIN, (uint32_t) wram0, WRAM0_SIZE, READWRITE);
#if 0
// WRAM1
// 1. The "first part" of WRAM1 should be accessible at any time
MMUPopulateRange(WRAM1_BEGIN, (uint32_t) wram1, WRAM1_SIZE - 0x1000,
READWRITE);
// 2. The last page of WRAM1 should be accessible via identity-mapped
// address (system purpose)
MMUPopulateRange(((uint32_t)wram1) + 0x7000, ((uint32_t) wram1) + 0x7000,
0x1000, READWRITE);
// 3. The last page of WRAM1 should be readonly to the user so that an
// interrupt is generated when user code tries to write to 0x3007FF8
MMUPopulateRange(WRAM1_BEGIN + 0x7000, ((uint32_t) wram1) + 0x7000, 0x1000,
READONLY);
#else
MMUPopulateRange(WRAM1_BEGIN, (uint32_t) wram1, WRAM1_SIZE, READWRITE);
MMUPopulateRange(((uint32_t)wram1), ((uint32_t)wram1), WRAM1_SIZE,
READWRITE);
#endif
MMUPopulateRange(PALETTE_RAM_BEGIN, (uint32_t) paletteRam, PALETTE_RAM_SIZE,
READWRITE);
MMUPopulateRange(VRAM_BEGIN, (uint32_t) vram, VRAM_SIZE, READWRITE);
MMUPopulateRange(OAM_BEGIN, (uint32_t) oam, OAM_SIZE, READWRITE);
MMUPopulateRange(SRAM_GAMEPAK_BEGIN, (uint32_t) sramGamePak,
SRAM_GAMEPAK_SIZE, READWRITE);
// Map GBA mirrored memories
MMUPopulateRange(WRAM1_BEGIN + 0x00FFF000, ((uint32_t) wram1) + 0x00007000,
0x1000, READONLY);
}
void GBARun(void)
{
//KeypadInit();
//KeypadReset();
TimerEnableLCD();
IRQEnable();
__asm__ volatile("push {lr}\n"
"ldr pc, =#0x08000000\n"
"pop {lr}\n");
}
static void synchronizeInterruptFlags(void)
{
// Clear the flag which were requested by user IRQ handler
*PERIPH16(0x202) &= ~GBAGetIF();
//*interruptCheckFlagPtr = 0;
}
void GBACallIRQ(void)
{
extern uint32_t irqsp;
register uint32_t tmp;
register uint32_t spsr;
__asm__ volatile("mrs %0, spsr" : "=r"(spsr));
if((spsr & 0x1f) == 0x12)
for(;;);
// CPSR mode should be already 0x12
/*
__asm__ volatile("mov r3, #0x4000000\n"
"mov lr, pc\n"
"ldr pc, [r3, #-4]"); // Pointer to first instruction of
// user IRQ handler @ 0x4000000-4
*/
__asm__ volatile("mov %0, sp" : "=r"(tmp));
__asm__ volatile("ldr sp, %0" :: "m"(irqsp));
__asm__ volatile("mov lr, pc\n"
" b 0x128" ::: "lr");
__asm__ volatile("mov sp, %0" :: "r"(tmp));
synchronizeInterruptFlags();
}
void GBASetIF(uint16_t flags)
{
((uint16_t*)wram1)[0x7FF8 >> 1] |= flags;
}
void GBAClearIF(uint16_t flags)
{
((uint16_t*)wram1)[0x7FF8 >> 1] &= ~flags;
}
uint16_t GBAGetIF(void)
{
return ((uint16_t*)wram1)[0x7FF8 >> 1];
}
void GBASetInterruptFlags(uint16_t flags)
{
volatile uint16_t *ptr = PERIPH16(0x202);
uint16_t gbaIF = *ptr | flags;
GBAClearIF(flags);
*ptr = gbaIF;
}
void GBAClearInterruptFlags(uint16_t flags)
{
volatile uint16_t *ptr = PERIPH16(0x202);
uint16_t gbaIF = *ptr & ~flags;
// Set Interrupt Check Flag @0x3007FF8
GBASetIF(flags);
*ptr = gbaIF;
}
|
gberthou/AdvanceOS
|
gba.c
|
gba.c
|
c
| 5,353
|
c
|
en
|
code
| 47
|
github-code
|
19
|
42288322895
|
#include "hof.h"
int load(struct player list[]){
return 0;
}
bool save(const struct player list[], const int size){
FILE *fscore=fopen(HOF_FILE,"w");
if(fscore==NULL){
return false;
}
for(size_text i=0;i<size;i++){
fprintf(fscore,"%s %d\n",list[i].name,list[i].score);
}
fclose(fscore);
return true;
}
bool add_player(struct player list[], int* size, const struct player player){
return 0;
}
|
mattkanuch/repo
|
C/boardgame/hof.c
|
hof.c
|
c
| 422
|
c
|
en
|
code
| 0
|
github-code
|
19
|
28908620667
|
/*************************************************************
* at328-0.c - Demonstrate simple I/O functions of ATmega328
*
* Program loops turning PC0 on and off as fast as possible.
*
* The program should generate code in the loop consisting of
* LOOP: SBI PORTC,0 (2 cycles)
* CBI PORTC,0 (2 cycles)
* RJMP LOOP (2 cycles)
*
* PC0 will be low for 4 / XTAL freq
* PC0 will be high for 2 / XTAL freq
* A 9.8304MHz clock gives a loop period of about 600 nanoseconds.
*
* Revision History
* Date Author Description
* 09/14/12 A. Weber Initial Release
* 11/18/13 A. Weber Renamed for ATmega328P
*************************************************************/
#include <avr/io.h>
#include <util/delay.h>
void serial_init ( unsigned short ubrr ) {
UBRR0 = ubrr;// Set baud rate
UCSR0B |= (1 << TXEN0 ); // Turn on transmitter
UCSR0B |= (1 << RXEN0 ); // Turn on receiver
UCSR0C = (3 << UCSZ00 ); // Set for async . operation , no parity ,
// one stop bit , 8 data bits
}
void serial_out ( char ch )
{
while (( UCSR0A & (1<<UDRE0 )) == 0);
UDR0 = ch ;
}
char serial_in ()
{
while ( !( UCSR0A & (1 << RXC0 )) );
return UDR0 ;
}
int main(void)
{
serial_init(63);
unsigned char test = 'a';
while(1){
char in = serial_in();
if(in == 'a' || in == 'e' || in == 'i' || in == 'o' || in == 'u'){
serial_out('v');
}
else{
serial_out('n');
}
}
return 0; /* never reached */
}
|
pjanish/GardeningPlus
|
lab4/at328-0.c
|
at328-0.c
|
c
| 1,508
|
c
|
en
|
code
| 0
|
github-code
|
19
|
21543171940
|
//==============================================================================
// DatabaseTester.h
// Created July 17 2012
//==============================================================================
#ifndef DATABASE_TESTER
#define DATABASE_TESTER
#include "Database.h"
#include "Random.h"
//==============================================================================
// Struct DatabaseTester
//==============================================================================
struct DatabaseTester {
public:
PhotoDatabase _db1;
PhotoDatabase _db2;
XorShift32 _rand;
unsigned _save1; // number of times _db1 has been saved to plaintext
unsigned _save2; // number of times _db2 has been saved to plaintext
public:
DatabaseTester (unsigned initialCapacity): _db1(initialCapacity), _db2(initialCapacity), _save1(0), _save2(0) {}
void setRootDir (std::string rootDir) { _db1.setRootDir(rootDir); _db2.setRootDir(rootDir); }
void setPanoDir (std::string panoDir) { _db1.setPanoDir(panoDir); _db2.setPanoDir(panoDir); }
void setRandState (unsigned x, unsigned y) { _db1.setRandState(x, y); _db2.setRandState(x, y); }
void setTesterRandState (unsigned x, unsigned y) { _rand.setState(x, y); }
// adds n panoramas (just metadata - no jpg) populated with random data
void addRandomEntries (unsigned n);
// adds between 0 and n random tags to each panorama
void addRandomTags (unsigned n);
// deletes between 0 and min{#tags, n} tags from each panorama
void deleteRandomTags (unsigned n);
bool save1 ();
bool load2 ();
bool savePlaintext1 ();
bool savePlaintext2 ();
};
#endif // DATABASE_TESTER
|
hunterowens/StreetScope
|
legacy/database/DatabaseTester.h
|
DatabaseTester.h
|
h
| 1,668
|
c
|
en
|
code
| 0
|
github-code
|
19
|
43725484914
|
//
// NSString+Utils.h
// LZZJson2OCObject
//
// Created by zizheng lu on 2020/9/10.
// Copyright ยฉ 2020 Chemm. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (Utils)
/// ๆ นๆฎ้ฉผๅณฐๅฝๅๆๅๅญ็ฌฆไธฒ
-(NSArray *)seperateByUppercaseWord;
/// ่ฝฌๆ็ฉบๆ ผ้ฎๅๅ็ๅฅๅญ
-(NSString *)formatToOneLineByUppercaseWord;
@end
NS_ASSUME_NONNULL_END
|
luzizheng/LZZJson2OCObject
|
LZZJson2OCObject/NSString+Utils.h
|
NSString+Utils.h
|
h
| 416
|
c
|
en
|
code
| 1
|
github-code
|
19
|
8260290882
|
#include <stdio.h>
#include <stdlib.h>
int ft_atoi(char *str)
{
int sum;
int sign;
int found;
sum = 0;
sign = 1;
found = 1;
while (*str == ' ' || *str == '\t' || *str == '\n' || *str == '\f' || *str == '\r')
str++;
if (*str == '-')
sign = -1;
if (*str == '-' || *str == '+')
str++;
while (*str && found)
{
if (*str >= '0' && *str <= '9')
sum = sum * 10 + *str - '0';
else
found = 0;
str++;
}
return (sign * sum);
}
int main(void)
{
char *s = "#";
printf("%d %d", ft_atoi(s), atoi(s));
return (0);
}
|
julekgwa/exams
|
exam_prac_01/ft_atoi.c
|
ft_atoi.c
|
c
| 537
|
c
|
en
|
code
| 7
|
github-code
|
19
|
26661206363
|
/*
Array -->
Array is collection of same data type
Array elements have continous memory location
index start with 0
index ending with length-1
*/
#include<stdio.h>
void main()
{
int a[5];
int b[5];
int c[5];
printf("Enter elements for 1st array: ");
for(int i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("Enter elements for 2nd array: ");
for(int i=0;i<5;i++)
{
scanf("%d",&b[i]);
}
printf("1st array: \n");
for(int i=0;i<5;i++)
{
printf("%d ",a[i]);
}
printf("\n2nd array:\n ");
for(int i=0;i<5;i++)
{
printf("%d ",b[i]);
}
printf("\nSum of two array:\n ");
for(int i=0;i<5;i++)
{
c[i]=a[i]-b[i];
printf("%d ",c[i]);
}
}
/*
1. Initialize array and print the array.
2. take all input from user and store into array and print that array.
3. take two array from user and print sum of two array.
4. sum of all elements of array (1 2 4 5 3 --> 15)
5. count negative numbers from array.( -2 , -3, 5, 6 , -8 ,3 ) -->3
6. count total number of odd and even numbers from array.(1 2 3 5 6 7 8)
odd count = 4
even count = 3
7. count total number of odd and even numbers from array.(1 2 3 5 6 7 8)
odd count = 4
even count = 3 and store odd and even numbers into two seprate array.
8. search element from array. take input from user.
A -( 1 5 2 6 9 4 8)
user - 6 --> found at index 3
user - 10 --> not found
9. print reverse array.(1 2 3 6 7 ) --> 7 6 3 2 1
10. reverse array in memory using another array.
11. reverse array in memory without using extra array.
*/
|
ShrutiPethani123/ManageTeam
|
Array.c
|
Array.c
|
c
| 1,642
|
c
|
en
|
code
| 0
|
github-code
|
19
|
74073878762
|
#ifndef STACK2_H
#define STACK2_H
// 12161756 ์ค์ฑํธ
// ๊ธฐ์กด stack.h์์ ์ถ๊ฐ๋ ๋ถ๋ถ(์๋ 3์ค)
int getOpNum(char); // token์ ๋ฐ์ ๊ทธ์ ๋ง๋ ์ซ์๋ฅผ ๋ฐํํ๋ ํจ์
bool confirm(char*); // ์ค์ํ๊ธฐ์ ๋ฐฐ์ด์ ๋ฐ์ ํผ์ฐ์ฐ์์ > ์ฐ์ฐ์์์ผ๋ true๋ฅผ ๋ฆฌํดํ๋ ํจ์
void convert(char*); // ์ค์ํ๊ธฐ์ ๋ฐฐ์ด์ ๋ฐ์ ํ์ํ๊ธฐ์์ผ๋ก ์ถ๋ ฅํ๋ ํจ์
#include <iostream>
#include <string>
using namespace std;
// 12161756 ์ค์ฑํธ
// ์์ธ์ฒ๋ฆฌ class
class RuntimeException{
private:
string errorMsg;
public:
RuntimeException(const string & err){
errorMsg = err;
}
string getMessage() const{
return errorMsg;
}
};
inline std::ostream& operator<<(std::ostream& out, const RuntimeException& e){
return out << e.getMessage();
}
class StackEmpty : public RuntimeException{
public:
StackEmpty(const string& err) :RuntimeException(err){}
};
class StackFull : public RuntimeException{
public:
StackFull(const string& err) :RuntimeException(err){}
};
// 12161756 ์ค์ฑํธ
// ArrayStack class
template <typename E>
class ArrayStack {
enum { DEF_CAPACITY = 100 };
public:
ArrayStack(int cap = DEF_CAPACITY); // ๊ธฐ๋ณธ ์ฉ๋์ 100์ผ๋ก ํ๋ ์์ฑ์
~ArrayStack();
int size() const; // ์คํ์ด ์ผ๋ง๋งํผ ์ฐจ์๋์ง ์๋ ค์ฃผ๋ ํจ์
bool empty() const; // ์คํ์ด ๋น์๋์ง True or False๋ก ๋ฐํํ๋ ํจ์
const E& top() const throw(StackEmpty); // ์ต์์ ์์๋ฅผ ์๋ ค์ฃผ๋ top
void push(const E& e) throw(StackFull); // ๋ฐ์ ๊ฐ์ ์คํ ์ต์์์ ์ฑ์ฐ๋ push
void pop() throw(StackEmpty); // ์ต์์ ์์๋ฅผ ์ญ์ ํ๋ pop
int input(E str);
int getStrSize(E str);
void print(E str);
private:
E* S;
int capacity;
int t;
};
template <typename E> void ArrayStack<E>::print(E str){
cout << str;
}
template <typename E> int ArrayStack<E>::input(E str)
{
for (int i = 0; i < getStrSize(str); i++)
{
if (str[i] == "("){
push(str[i]);
}
else if (str[i] == ")"){
while (top() != "("){
print(top());
pop();
}
print(top()); pop();
}
else if (str[i] == "+" || "-"){
}
}
}
template <typename E> int ArrayStack<E>::getStrSize(E str)
{
int size = 0;
while (str[size] != NULL){
size++;
}
return size;
}
template <typename E> ArrayStack<E>::ArrayStack(int cap)
:S(new E[cap]), capacity(cap), t(-1){}
template <typename E> ArrayStack<E>::~ArrayStack(){
delete[] S;
}
template <typename E> int ArrayStack<E>::size() const{
return (t + 1);
}
template <typename E> bool ArrayStack<E>::empty() const{
return (t < 0);
}
template <typename E>
const E& ArrayStack<E>::top() const throw(StackEmpty){
try{
if (empty())
throw StackEmpty("์ค๋ฅ : ๋น ์คํ์์ top์ ์คํํ์์ต๋๋ค.");
}
catch (StackEmpty &e){
cout << e.getMessage() << endl;
}
return S[t];
}
template <typename E>
void ArrayStack<E>::push(const E& e) throw(StackFull){
try{
if (size() == capacity)
throw StackFull("์ค๋ฅ : ํ ์คํ์์ push๋ฅผ ์คํํ์์ต๋๋ค.");
}
catch (StackFull &e){
cout << e.getMessage() << endl;
}
S[++t] = e;
}
template <typename E>
void ArrayStack<E>::pop() throw(StackEmpty){
try{
if (empty())
throw StackEmpty("์ค๋ฅ : ๋น ์คํ์์ pop์ ์คํํ์์ต๋๋ค.");
}
catch (StackEmpty &e){
cout << e.getMessage() << endl;
}
--t;
}
#endif
|
grympan/Data_Structure
|
HW2/HW2_12161756_์ค์ฑํธ_2/stack2.h
|
stack2.h
|
h
| 3,220
|
c
|
ko
|
code
| 0
|
github-code
|
19
|
17431574267
|
#include "main.h"
/**
* _strcat - function
* @dest: param
* @src: param
* Return: 0
*/
char *_strcat(char *dest, char *src)
{
int blessing;
int leo;
for (blessing = 0; dest[blessing] != '\0'; blessing++)
{
;
}
for (leo = 0; src[leo] != 0; leo++)
{
dest[blessing] = src[leo];
blessing++;
}
dest[blessing] = '\0';
return (dest);
}
|
Grace-codes9/alx-low_level_programming
|
0x06-pointers_arrays_strings/0-strcat.c
|
0-strcat.c
|
c
| 353
|
c
|
en
|
code
| 0
|
github-code
|
19
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.