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 <[email protected]>
*
* 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
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 4