code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
simple drupal module to display user profile information in balloon #how to install 1.extract the module and in sites/all/module dir and enable the module 2. config the module as need
zeet2020/user-info-balloon
README.md
Markdown
gpl-2.0
191
/******************************************************************************\ CAMotics is an Open-Source simulation and CAM software. Copyright (C) 2011-2019 Joseph Coffland <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. \******************************************************************************/ #pragma once #include <cbang/SmartPointer.h> #include <QDialog> namespace Ui {class DonateDialog;} namespace CAMotics { class DonateDialog : public QDialog { Q_OBJECT; cb::SmartPointer<Ui::DonateDialog> ui; public: DonateDialog(QWidget *parent); QString getVersion() const; void onStartup(); // From QDialog int exec(); // From QWidget void showEvent(QShowEvent *event); }; }
CauldronDevelopmentLLC/OpenSCAM
src/camotics/qt/DonateDialog.h
C
gpl-2.0
1,362
#include<stdio.h> int main() { double r,pi=3.14159; scanf("%lf",&r); printf("A=%.4lf\n",pi*r*r); return 0; }
GreenJoey/My-Simple-Programs
Competive Programming/C/uri/1002.c
C
gpl-2.0
113
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest04982") public class BenchmarkTest04982 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheParameter("foo"); String bar; String guess = "ABC"; char switchTarget = guess.charAt(1); // condition 'B', which is safe // Simple case statement that assigns param to bar on conditions 'A' or 'C' switch (switchTarget) { case 'A': bar = param; break; case 'B': bar = "bob"; break; case 'C': case 'D': bar = param; break; default: bar = "bob's your uncle"; break; } Object[] obj = { bar, "b"}; response.getWriter().printf("notfoo",obj); } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest04982.java
Java
gpl-2.0
2,239
<?php /* Copyright (c) 2007 BeVolunteer This file is part of BW Rox. BW Rox is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. BW Rox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/> or write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ $words = new MOD_words(); ?> <div id="teaser" class="clearfix"> <div class="subcolumns"> <div class="c62l"> <div class="subcl"> <h1 class="slogan"><span id="something" ><?php echo $words->get('IndexPageTeaserReal1a');?></span> <span id="real" ><?php echo $words->get('IndexPageTeaserReal1b');?></span>&nbsp;</h1> <h2><?php echo $words->get('IndexPageTeaserReal2');?></h2> <a class="bigbutton float_left" href="signup" onclick="this.blur();"><span><?php echo $words->get('signup_now');?></span></a> <a class="bigbutton float_left" href="tour" onclick="this.blur();"><span><?php echo $words->get('tour_take');?></span></a> </div> <!-- subcl --> </div> <!-- c50l --> <div class="c38r"> <div class="subcr"> <div id="slideshow-content"> <div class="slide" id="slide1"> <img src="images/tour/share4_small.jpg" alt="share" /> </div> <div class="slide" id="slide2" style="display: none;"> <img src="images/tour/syrien.jpg" alt="syria" /> </div> <div class="slide" id="slide3" style="display: none;"> <img src="images/tour/mountain1.jpg" alt="mountain" /> </div> <div class="slide" id="slide4" style="display: none;"> <img src="images/tour/river.jpg" alt="river" /> </div> <div class="slide" id="slide5" style="display: none;"> <img src="images/tour/dancing2.jpg" alt="dancing" /> </div> <div class="slide" id="slide6" style="display: none;"> <img src="images/tour/mountain2.jpg" alt="river" /> </div> <div class="slide" id="slide7" style="display: none;"> <img src="images/tour/people.jpg" alt="river" /> </div> <div class="slide" id="slide8" style="display: none;"> <img src="images/tour/people2.jpg" alt="river" /> </div> <p class="small photodesc"> (cc) <?=$words->get('StartPageListofPhotographers');?> </p> </div> </div> <!-- subcr --> </div> <!-- c50r --> </div> <!-- subcolumns --> <script type="text/javascript"> <!-- function realeffect() { new Effect.toggle('real', 'appear', {duration: 2}) } $('real').hide(); $('something').hide(); window.onload = function () { new Effect.toggle('something', 'appear', {duration: 2}); setTimeout('realeffect()',2000); start_slideshow(1, 8, 10000); }; // --> </script> <script type="text/javascript"> function start_slideshow(start_frame, end_frame, delay) { setTimeout(switch_slides(start_frame,start_frame,end_frame, delay), delay); } function switch_slides(frame, start_frame, end_frame, delay) { return (function() { Effect.Fade('slide' + frame); if (frame == end_frame) { frame = start_frame; } else { frame = frame + 1; } setTimeout("Effect.Appear('slide" + frame + "');", 950); setTimeout(switch_slides(frame, start_frame, end_frame, delay), delay + 950); }) } </script> </div>
BeWelcome/rox.prototypes
templates/apps/rox/teaser.php
PHP
gpl-2.0
4,007
using UnityEngine; using System.Collections; public class MapCollisionsDetector : MonoBehaviour { // Use this for initialization void Start () { } void FixedUpdate() { } /*void OnCollisionEnter(Collision collision) { foreach(var contact in collision.contacts) print (contact.otherCollider.gameObject.name); }*/ }
Reminouche/TCG
Assets/MapCollisionsDetector.cs
C#
gpl-2.0
340
/* Copyright (C) 2015 Panagiotis Roubatsis This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* Created by Panagiotis Roubatsis Description: Load and apply GLSL shaders to irrlicht nodes. */ #ifndef GLSL_SHADER_H #define GLSL_SHADER_H #include "Shader.h" #include <iostream> #include <irrlicht.h> class GlslShader : public Shader { private: irr::video::E_MATERIAL_TYPE _materialType; bool _isLoaded; public: GlslShader(); GlslShader(std::string fileName, irr::video::IGPUProgrammingServices* gpu, int type); void load(std::string fileName, irr::video::IGPUProgrammingServices* gpu, int type); void apply(irr::scene::ISceneNode* node); }; #endif
proubatsis/Procedural-City
Procedural City/GlslShader.h
C
gpl-2.0
1,342
/************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ package com.espertech.esper.epl.join.pollindex; import com.espertech.esper.epl.join.table.EventTable; import com.espertech.esper.epl.join.table.UnindexedEventTableList; import com.espertech.esper.epl.join.table.PropertyIndexedEventTable; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EventType; import java.util.Arrays; import java.util.List; /** * Strategy for building an index out of poll-results knowing the properties to base the index on. */ public class PollResultIndexingStrategyIndex implements PollResultIndexingStrategy { private final int streamNum; private final EventType eventType; private final String[] propertyNames; /** * Ctor. * @param streamNum is the stream number of the indexed stream * @param eventType is the event type of the indexed stream * @param propertyNames is the property names to be indexed */ public PollResultIndexingStrategyIndex(int streamNum, EventType eventType, String[] propertyNames) { this.streamNum = streamNum; this.eventType = eventType; this.propertyNames = propertyNames; } public EventTable index(List<EventBean> pollResult, boolean isActiveCache) { if (!isActiveCache) { return new UnindexedEventTableList(pollResult); } PropertyIndexedEventTable table = new PropertyIndexedEventTable(streamNum, eventType, propertyNames); table.add(pollResult.toArray(new EventBean[pollResult.size()])); return table; } public String toQueryPlan() { return this.getClass().getSimpleName() + " properties " + Arrays.toString(propertyNames); } }
intelie/esper
esper/src/main/java/com/espertech/esper/epl/join/pollindex/PollResultIndexingStrategyIndex.java
Java
gpl-2.0
2,448
variable_name =============
judasnow/variable_name
README.md
Markdown
gpl-2.0
28
/* * ALSA SoC Voice Codec Interface for TI DAVINCI processor * * Copyright (C) 2010 Texas Instruments. * * Author: Miguel Aguilar <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/mfd/davinci_voicecodec.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/initval.h> #include <sound/soc.h> #include "davinci-pcm.h" #include "davinci-i2s.h" #include "davinci-vcif.h" #define MOD_REG_BIT(val, mask, set) do { \ if (set) { \ val |= mask; \ } else { \ val &= ~mask; \ } \ } while (0) struct davinci_vcif_dev { struct davinci_vc *davinci_vc; struct davinci_pcm_dma_params dma_params[2]; }; static void davinci_vcif_start(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct davinci_vcif_dev *davinci_vcif_dev = rtd->dai->cpu_dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; u32 w; /* Start the sample generator and enable transmitter/receiver */ w = readl(davinci_vc->base + DAVINCI_VC_CTRL); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTDAC, 0); else MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTADC, 0); writel(w, davinci_vc->base + DAVINCI_VC_CTRL); } static void davinci_vcif_stop(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct davinci_vcif_dev *davinci_vcif_dev = rtd->dai->cpu_dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; u32 w; /* Reset transmitter/receiver and sample rate/frame sync generators */ w = readl(davinci_vc->base + DAVINCI_VC_CTRL); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTDAC, 1); else MOD_REG_BIT(w, DAVINCI_VC_CTRL_RSTADC, 1); writel(w, davinci_vc->base + DAVINCI_VC_CTRL); } static int davinci_vcif_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct davinci_vcif_dev *davinci_vcif_dev = dai->private_data; struct davinci_vc *davinci_vc = davinci_vcif_dev->davinci_vc; struct davinci_pcm_dma_params *dma_params = &davinci_vcif_dev->dma_params[substream->stream]; u32 w; /* Restart the codec before setup */ davinci_vcif_stop(substream); davinci_vcif_start(substream); /* General line settings */ writel(DAVINCI_VC_CTRL_MASK, davinci_vc->base + DAVINCI_VC_CTRL); writel(DAVINCI_VC_INT_MASK, davinci_vc->base + DAVINCI_VC_INTCLR); writel(DAVINCI_VC_INT_MASK, davinci_vc->base + DAVINCI_VC_INTEN); w = readl(davinci_vc->base + DAVINCI_VC_CTRL); /* Determine xfer data type */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_U8: dma_params->data_type = 0; MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_BITS_8 | DAVINCI_VC_CTRL_RD_UNSIGNED | DAVINCI_VC_CTRL_WD_BITS_8 | DAVINCI_VC_CTRL_WD_UNSIGNED, 1); break; case SNDRV_PCM_FORMAT_S8: dma_params->data_type = 1; MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_BITS_8 | DAVINCI_VC_CTRL_WD_BITS_8, 1); MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_UNSIGNED | DAVINCI_VC_CTRL_WD_UNSIGNED, 0); break; case SNDRV_PCM_FORMAT_S16_LE: dma_params->data_type = 2; MOD_REG_BIT(w, DAVINCI_VC_CTRL_RD_BITS_8 | DAVINCI_VC_CTRL_RD_UNSIGNED | DAVINCI_VC_CTRL_WD_BITS_8 | DAVINCI_VC_CTRL_WD_UNSIGNED, 0); break; default: printk(KERN_WARNING "davinci-vcif: unsupported PCM format"); return -EINVAL; } dma_params->acnt = dma_params->data_type; writel(w, davinci_vc->base + DAVINCI_VC_CTRL); return 0; } static int davinci_vcif_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { int ret = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: davinci_vcif_start(substream); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: davinci_vcif_stop(substream); break; default: ret = -EINVAL; } return ret; } #define DAVINCI_VCIF_RATES SNDRV_PCM_RATE_8000_48000 static struct snd_soc_dai_ops davinci_vcif_dai_ops = { .trigger = davinci_vcif_trigger, .hw_params = davinci_vcif_hw_params, }; struct snd_soc_dai davinci_vcif_dai = { .name = "davinci-vcif", .playback = { .channels_min = 1, .channels_max = 2, .rates = DAVINCI_VCIF_RATES, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .capture = { .channels_min = 1, .channels_max = 2, .rates = DAVINCI_VCIF_RATES, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .ops = &davinci_vcif_dai_ops, }; EXPORT_SYMBOL_GPL(davinci_vcif_dai); static int davinci_vcif_probe(struct platform_device *pdev) { struct davinci_vc *davinci_vc = platform_get_drvdata(pdev); struct davinci_vcif_dev *davinci_vcif_dev; int ret; davinci_vcif_dev = kzalloc(sizeof(struct davinci_vcif_dev), GFP_KERNEL); if (!davinci_vc) { dev_dbg(&pdev->dev, "could not allocate memory for private data\n"); return -ENOMEM; } /* DMA tx params */ davinci_vcif_dev->davinci_vc = davinci_vc; davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].channel = davinci_vc->davinci_vcif.dma_tx_channel; davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].dma_addr = davinci_vc->davinci_vcif.dma_tx_addr; /* DMA rx params */ davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].channel = davinci_vc->davinci_vcif.dma_rx_channel; davinci_vcif_dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].dma_addr = davinci_vc->davinci_vcif.dma_rx_addr; davinci_vcif_dai.dev = &pdev->dev; davinci_vcif_dai.capture.dma_data = davinci_vcif_dev->dma_params; davinci_vcif_dai.playback.dma_data = davinci_vcif_dev->dma_params; davinci_vcif_dai.private_data = davinci_vcif_dev; ret = snd_soc_register_dai(&davinci_vcif_dai); if (ret != 0) { dev_err(&pdev->dev, "could not register dai\n"); goto fail; } return 0; fail: kfree(davinci_vcif_dev); return ret; } static int davinci_vcif_remove(struct platform_device *pdev) { snd_soc_unregister_dai(&davinci_vcif_dai); return 0; } static struct platform_driver davinci_vcif_driver = { .probe = davinci_vcif_probe, .remove = davinci_vcif_remove, .driver = { .name = "davinci_vcif", .owner = THIS_MODULE, }, }; static int __init davinci_vcif_init(void) { return platform_driver_probe(&davinci_vcif_driver, davinci_vcif_probe); } module_init(davinci_vcif_init); static void __exit davinci_vcif_exit(void) { platform_driver_unregister(&davinci_vcif_driver); } module_exit(davinci_vcif_exit); MODULE_AUTHOR("Miguel Aguilar"); MODULE_DESCRIPTION("Texas Instruments DaVinci ASoC Voice Codec Interface"); MODULE_LICENSE("GPL");
bticino/linux
sound/soc/davinci/davinci-vcif.c
C
gpl-2.0
7,528
package com.ht.halo.hibernate3.base; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map.Entry; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.ht.halo.hibernate3.HaloDao; import com.ht.halo.map.HaloMap; public class MyEntityUtils { private static final Log logger = LogFactory.getLog(MyEntityUtils.class); /** * @Title: setEntity * @Description: TODO Action层 设置实体某字段值 map转entity * @param entity * @param parameters */ public static Object setEntity(Object entity,HaloMap parameter){ if(null!=parameter){ for (Entry<String, ?> entry : parameter.entrySet()) { try { BeanUtils.setProperty(entity, entry.getKey(), entry.getValue()); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } // MyBeanUtils.setFieldValue(entity, entry.getKey(), entry.getValue()); } } return entity; } public static <T> T toEntity(Class<T> clazz, HaloMap map) { T obj = null; try { BeanInfo beanInfo = Introspector.getBeanInfo(clazz); obj = clazz.newInstance(); // 创建 JavaBean 对象 // 给 JavaBean 对象的属性赋值 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (map.containsKey(propertyName)) { // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。 Object value = map.get(propertyName); if ("".equals(value)) { value = null; } Object[] args = new Object[1]; args[0] = value; try { descriptor.getWriteMethod().invoke(obj, args); } catch (InvocationTargetException e) { logger.warn("字段映射失败"); } } } } catch (IllegalAccessException e) { logger.error("实例化 JavaBean 失败"); } catch (IntrospectionException e) { logger.error("分析类属性失败"); } catch (IllegalArgumentException e) { logger.error("映射错误"); } catch (InstantiationException e) { logger.error("实例化 JavaBean 失败"); } return (T) obj; } public static HaloMap toHaloMap(Object bean) { Class<? extends Object> clazz = bean.getClass(); HaloMap returnMap = new HaloMap(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (null != propertyName) { propertyName = propertyName.toString(); } if(null==result){ continue; } if (null != result) { result = result.toString(); } returnMap.put(propertyName, result); } } } catch (IntrospectionException e) { logger.error("分析类属性失败"); } catch (IllegalAccessException e) { logger.error("实例化 JavaBean 失败"); } catch (IllegalArgumentException e) { logger.error("映射错误"); } catch (InvocationTargetException e) { logger.error("调用属性的 setter 方法失败"); } return returnMap; } public static HaloMap toFindHaloMap(Object bean) { Class<? extends Object> clazz = bean.getClass(); HaloMap returnMap = new HaloMap(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (null != propertyName) { propertyName = propertyName.toString(); } if(null==result){ continue; } if (null != result) { result = result.toString(); } if(propertyName.equals("json")){ continue; } returnMap.put(propertyName+HaloDao.MYSPACE+HaloDao.PRM, result); } } } catch (IntrospectionException e) { logger.error("分析类属性失败"); } catch (IllegalAccessException e) { logger.error("实例化 JavaBean 失败"); } catch (IllegalArgumentException e) { logger.error("映射错误"); } catch (InvocationTargetException e) { logger.error("调用属性的 setter 方法失败"); } return returnMap; } }
VonChange/haloDao-Hibernate3
src/main/java/com/ht/halo/hibernate3/base/MyEntityUtils.java
Java
gpl-2.0
6,670
import os import unittest import tempfile from git import Repo from oeqa.utils.commands import get_bb_var from oe.buildhistory_analysis import blob_to_dict, compare_dict_blobs class TestBlobParsing(unittest.TestCase): def setUp(self): import time self.repo_path = tempfile.mkdtemp(prefix='selftest-buildhistory', dir=get_bb_var('TOPDIR')) self.repo = Repo.init(self.repo_path) self.test_file = "test" self.var_map = {} def tearDown(self): import shutil shutil.rmtree(self.repo_path) def commit_vars(self, to_add={}, to_remove = [], msg="A commit message"): if len(to_add) == 0 and len(to_remove) == 0: return for k in to_remove: self.var_map.pop(x,None) for k in to_add: self.var_map[k] = to_add[k] with open(os.path.join(self.repo_path, self.test_file), 'w') as repo_file: for k in self.var_map: repo_file.write("%s = %s\n" % (k, self.var_map[k])) self.repo.git.add("--all") self.repo.git.commit(message=msg) def test_blob_to_dict(self): """ Test convertion of git blobs to dictionary """ valuesmap = { "foo" : "1", "bar" : "2" } self.commit_vars(to_add = valuesmap) blob = self.repo.head.commit.tree.blobs[0] self.assertEqual(valuesmap, blob_to_dict(blob), "commit was not translated correctly to dictionary") def test_compare_dict_blobs(self): """ Test comparisson of dictionaries extracted from git blobs """ changesmap = { "foo-2" : ("2", "8"), "bar" : ("","4"), "bar-2" : ("","5")} self.commit_vars(to_add = { "foo" : "1", "foo-2" : "2", "foo-3" : "3" }) blob1 = self.repo.heads.master.commit.tree.blobs[0] self.commit_vars(to_add = { "foo-2" : "8", "bar" : "4", "bar-2" : "5" }) blob2 = self.repo.heads.master.commit.tree.blobs[0] change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file), blob1, blob2, False, False) var_changes = { x.fieldname : (x.oldvalue, x.newvalue) for x in change_records} self.assertEqual(changesmap, var_changes, "Changes not reported correctly") def test_compare_dict_blobs_default(self): """ Test default values for comparisson of git blob dictionaries """ defaultmap = { x : ("default", "1") for x in ["PKG", "PKGE", "PKGV", "PKGR"]} self.commit_vars(to_add = { "foo" : "1" }) blob1 = self.repo.heads.master.commit.tree.blobs[0] self.commit_vars(to_add = { "PKG" : "1", "PKGE" : "1", "PKGV" : "1", "PKGR" : "1" }) blob2 = self.repo.heads.master.commit.tree.blobs[0] change_records = compare_dict_blobs(os.path.join(self.repo_path, self.test_file), blob1, blob2, False, False) var_changes = {} for x in change_records: oldvalue = "default" if ("default" in x.oldvalue) else x.oldvalue var_changes[x.fieldname] = (oldvalue, x.newvalue) self.assertEqual(defaultmap, var_changes, "Defaults not set properly")
schleichdi2/OPENNFR-6.1-CORE
opennfr-openembedded-core/meta/lib/oeqa/selftest/oelib/buildhistory.py
Python
gpl-2.0
3,191
/* * Copyright (c) 2001-2002 by David Brownell * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifdef __KERNEL__ #include <linux/rwsem.h> /* This file contains declarations of usbcore internals that are mostly * used or exposed by Host Controller Drivers. */ /* * USB Packet IDs (PIDs) */ #define USB_PID_UNDEF_0 0xf0 #define USB_PID_OUT 0xe1 #define USB_PID_ACK 0xd2 #define USB_PID_DATA0 0xc3 #define USB_PID_PING 0xb4 /* USB 2.0 */ #define USB_PID_SOF 0xa5 #define USB_PID_NYET 0x96 /* USB 2.0 */ #define USB_PID_DATA2 0x87 /* USB 2.0 */ #define USB_PID_SPLIT 0x78 /* USB 2.0 */ #define USB_PID_IN 0x69 #define USB_PID_NAK 0x5a #define USB_PID_DATA1 0x4b #define USB_PID_PREAMBLE 0x3c /* Token mode */ #define USB_PID_ERR 0x3c /* USB 2.0: handshake mode */ #define USB_PID_SETUP 0x2d #define USB_PID_STALL 0x1e #define USB_PID_MDATA 0x0f /* USB 2.0 */ /*-------------------------------------------------------------------------*/ /* * USB Host Controller Driver (usb_hcd) framework * * Since "struct usb_bus" is so thin, you can't share much code in it. * This framework is a layer over that, and should be more sharable. * * @authorized_default: Specifies if new devices are authorized to * connect by default or they require explicit * user space authorization; this bit is settable * through /sys/class/usb_host/X/authorized_default. * For the rest is RO, so we don't lock to r/w it. */ /*-------------------------------------------------------------------------*/ struct usb_hcd { /* * housekeeping */ struct usb_bus self; /* hcd is-a bus */ struct kref kref; /* reference counter */ const char *product_desc; /* product/vendor string */ char irq_descr[24]; /* driver + bus # */ struct timer_list rh_timer; /* drives root-hub polling */ struct urb *status_urb; /* the current status urb */ #ifdef CONFIG_PM struct work_struct wakeup_work; /* for remote wakeup */ #endif /* * hardware info/state */ const struct hc_driver *driver; /* hw-specific hooks */ /* Flags that need to be manipulated atomically */ unsigned long flags; #define HCD_FLAG_HW_ACCESSIBLE 0x00000001 #define HCD_FLAG_SAW_IRQ 0x00000002 unsigned rh_registered:1;/* is root hub registered? */ /* The next flag is a stopgap, to be removed when all the HCDs * support the new root-hub polling mechanism. */ unsigned uses_new_polling:1; unsigned poll_rh:1; /* poll for rh status? */ unsigned poll_pending:1; /* status has changed? */ unsigned wireless:1; /* Wireless USB HCD */ unsigned authorized_default:1; int irq; /* irq allocated */ void __iomem *regs; /* device memory/io */ u64 rsrc_start; /* memory/io resource start */ u64 rsrc_len; /* memory/io resource length */ unsigned power_budget; /* in mA, 0 = no limit */ #define HCD_BUFFER_POOLS 4 struct dma_pool *pool [HCD_BUFFER_POOLS]; int state; # define __ACTIVE 0x01 # define __SUSPEND 0x04 # define __TRANSIENT 0x80 # define HC_STATE_HALT 0 # define HC_STATE_RUNNING (__ACTIVE) # define HC_STATE_QUIESCING (__SUSPEND|__TRANSIENT|__ACTIVE) # define HC_STATE_RESUMING (__SUSPEND|__TRANSIENT) # define HC_STATE_SUSPENDED (__SUSPEND) #define HC_IS_RUNNING(state) ((state) & __ACTIVE) #define HC_IS_SUSPENDED(state) ((state) & __SUSPEND) /* more shared queuing code would be good; it should support * smarter scheduling, handle transaction translators, etc; * input size of periodic table to an interrupt scheduler. * (ohci 32, uhci 1024, ehci 256/512/1024). */ /* The HC driver's private data is stored at the end of * this structure. */ unsigned long hcd_priv[0] __attribute__ ((aligned (sizeof(unsigned long)))); }; /* 2.4 does this a bit differently ... */ static inline struct usb_bus *hcd_to_bus (struct usb_hcd *hcd) { return &hcd->self; } static inline struct usb_hcd *bus_to_hcd (struct usb_bus *bus) { return container_of(bus, struct usb_hcd, self); } struct hcd_timeout { /* timeouts we allocate */ struct list_head timeout_list; struct timer_list timer; }; /*-------------------------------------------------------------------------*/ struct hc_driver { const char *description; /* "ehci-hcd" etc */ const char *product_desc; /* product/vendor string */ size_t hcd_priv_size; /* size of private data */ /* irq handler */ irqreturn_t (*irq) (struct usb_hcd *hcd); int flags; #define HCD_MEMORY 0x0001 /* HC regs use memory (else I/O) */ #define HCD_USB11 0x0010 /* USB 1.1 */ #define HCD_USB2 0x0020 /* USB 2.0 */ /* called to init HCD and root hub */ int (*reset) (struct usb_hcd *hcd); int (*start) (struct usb_hcd *hcd); /* NOTE: these suspend/resume calls relate to the HC as * a whole, not just the root hub; they're for PCI bus glue. */ /* called after suspending the hub, before entering D3 etc */ int (*suspend) (struct usb_hcd *hcd, pm_message_t message); /* called after entering D0 (etc), before resuming the hub */ int (*resume) (struct usb_hcd *hcd); /* cleanly make HCD stop writing memory and doing I/O */ void (*stop) (struct usb_hcd *hcd); /* shutdown HCD */ void (*shutdown) (struct usb_hcd *hcd); /* return current frame number */ int (*get_frame_number) (struct usb_hcd *hcd); /* manage i/o requests, device state */ int (*urb_enqueue)(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags); int (*urb_dequeue)(struct usb_hcd *hcd, struct urb *urb, int status); /* hw synch, freeing endpoint resources that urb_dequeue can't */ void (*endpoint_disable)(struct usb_hcd *hcd, struct usb_host_endpoint *ep); /* root hub support */ int (*hub_status_data) (struct usb_hcd *hcd, char *buf); int (*hub_control) (struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength); int (*bus_suspend)(struct usb_hcd *); int (*bus_resume)(struct usb_hcd *); int (*start_port_reset)(struct usb_hcd *, unsigned port_num); void (*hub_irq_enable)(struct usb_hcd *); /* Needed only if port-change IRQs are level-triggered */ #ifdef CONFIG_KDB_USB /* KDB poll function for this HC */ int (*kdb_poll_char)(struct urb *urb); #endif /* CONFIG_KDB_USB */ }; extern int usb_hcd_link_urb_to_ep(struct usb_hcd *hcd, struct urb *urb); extern int usb_hcd_check_unlink_urb(struct usb_hcd *hcd, struct urb *urb, int status); extern void usb_hcd_unlink_urb_from_ep(struct usb_hcd *hcd, struct urb *urb); extern int usb_hcd_submit_urb (struct urb *urb, gfp_t mem_flags); extern int usb_hcd_unlink_urb (struct urb *urb, int status); extern void usb_hcd_giveback_urb(struct usb_hcd *hcd, struct urb *urb, int status); extern void usb_hcd_flush_endpoint(struct usb_device *udev, struct usb_host_endpoint *ep); extern void usb_hcd_disable_endpoint(struct usb_device *udev, struct usb_host_endpoint *ep); extern int usb_hcd_get_frame_number (struct usb_device *udev); extern struct usb_hcd *usb_create_hcd (const struct hc_driver *driver, struct device *dev, char *bus_name); extern struct usb_hcd *usb_get_hcd (struct usb_hcd *hcd); extern void usb_put_hcd (struct usb_hcd *hcd); extern int usb_add_hcd(struct usb_hcd *hcd, unsigned int irqnum, unsigned long irqflags); extern void usb_remove_hcd(struct usb_hcd *hcd); struct platform_device; extern void usb_hcd_platform_shutdown(struct platform_device* dev); #ifdef CONFIG_PCI struct pci_dev; struct pci_device_id; extern int usb_hcd_pci_probe (struct pci_dev *dev, const struct pci_device_id *id); extern void usb_hcd_pci_remove (struct pci_dev *dev); #ifdef CONFIG_PM extern int usb_hcd_pci_suspend (struct pci_dev *dev, pm_message_t state); extern int usb_hcd_pci_resume (struct pci_dev *dev); #endif /* CONFIG_PM */ extern void usb_hcd_pci_shutdown (struct pci_dev *dev); #endif /* CONFIG_PCI */ /* pci-ish (pdev null is ok) buffer alloc/mapping support */ int hcd_buffer_create (struct usb_hcd *hcd); void hcd_buffer_destroy (struct usb_hcd *hcd); void *hcd_buffer_alloc (struct usb_bus *bus, size_t size, gfp_t mem_flags, dma_addr_t *dma); void hcd_buffer_free (struct usb_bus *bus, size_t size, void *addr, dma_addr_t dma); /* generic bus glue, needed for host controllers that don't use PCI */ extern irqreturn_t usb_hcd_irq (int irq, void *__hcd); extern void usb_hc_died (struct usb_hcd *hcd); extern void usb_hcd_poll_rh_status(struct usb_hcd *hcd); /* -------------------------------------------------------------------------- */ /* Enumeration is only for the hub driver, or HCD virtual root hubs */ extern struct usb_device *usb_alloc_dev(struct usb_device *parent, struct usb_bus *, unsigned port); extern int usb_new_device(struct usb_device *dev); extern void usb_disconnect(struct usb_device **); extern int usb_get_configuration(struct usb_device *dev); extern void usb_destroy_configuration(struct usb_device *dev); /*-------------------------------------------------------------------------*/ /* * HCD Root Hub support */ #include "hub.h" /* (shifted) direction/type/recipient from the USB 2.0 spec, table 9.2 */ #define DeviceRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8) #define DeviceOutRequest \ ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8) #define InterfaceRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) #define EndpointRequest \ ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) #define EndpointOutRequest \ ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8) /* class requests from the USB 2.0 hub spec, table 11-15 */ /* GetBusState and SetHubDescriptor are optional, omitted */ #define ClearHubFeature (0x2000 | USB_REQ_CLEAR_FEATURE) #define ClearPortFeature (0x2300 | USB_REQ_CLEAR_FEATURE) #define GetHubDescriptor (0xa000 | USB_REQ_GET_DESCRIPTOR) #define GetHubStatus (0xa000 | USB_REQ_GET_STATUS) #define GetPortStatus (0xa300 | USB_REQ_GET_STATUS) #define SetHubFeature (0x2000 | USB_REQ_SET_FEATURE) #define SetPortFeature (0x2300 | USB_REQ_SET_FEATURE) /*-------------------------------------------------------------------------*/ /* * Generic bandwidth allocation constants/support */ #define FRAME_TIME_USECS 1000L #define BitTime(bytecount) (7 * 8 * bytecount / 6) /* with integer truncation */ /* Trying not to use worst-case bit-stuffing of (7/6 * 8 * bytecount) = 9.33 * bytecount */ /* bytecount = data payload byte count */ #define NS_TO_US(ns) ((ns + 500L) / 1000L) /* convert & round nanoseconds to microseconds */ /* * Full/low speed bandwidth allocation constants/support. */ #define BW_HOST_DELAY 1000L /* nanoseconds */ #define BW_HUB_LS_SETUP 333L /* nanoseconds */ /* 4 full-speed bit times (est.) */ #define FRAME_TIME_BITS 12000L /* frame = 1 millisecond */ #define FRAME_TIME_MAX_BITS_ALLOC (90L * FRAME_TIME_BITS / 100L) #define FRAME_TIME_MAX_USECS_ALLOC (90L * FRAME_TIME_USECS / 100L) /* * Ceiling [nano/micro]seconds (typical) for that many bytes at high speed * ISO is a bit less, no ACK ... from USB 2.0 spec, 5.11.3 (and needed * to preallocate bandwidth) */ #define USB2_HOST_DELAY 5 /* nsec, guess */ #define HS_NSECS(bytes) ( ((55 * 8 * 2083) \ + (2083UL * (3 + BitTime(bytes))))/1000 \ + USB2_HOST_DELAY) #define HS_NSECS_ISO(bytes) ( ((38 * 8 * 2083) \ + (2083UL * (3 + BitTime(bytes))))/1000 \ + USB2_HOST_DELAY) #define HS_USECS(bytes) NS_TO_US (HS_NSECS(bytes)) #define HS_USECS_ISO(bytes) NS_TO_US (HS_NSECS_ISO(bytes)) extern long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount); /*-------------------------------------------------------------------------*/ extern void usb_set_device_state(struct usb_device *udev, enum usb_device_state new_state); /*-------------------------------------------------------------------------*/ /* exported only within usbcore */ extern struct list_head usb_bus_list; extern struct mutex usb_bus_list_lock; extern wait_queue_head_t usb_kill_urb_queue; extern void usb_enable_root_hub_irq (struct usb_bus *bus); extern int usb_find_interface_driver (struct usb_device *dev, struct usb_interface *interface); #define usb_endpoint_out(ep_dir) (!((ep_dir) & USB_DIR_IN)) #ifdef CONFIG_PM extern void usb_hcd_resume_root_hub (struct usb_hcd *hcd); extern void usb_root_hub_lost_power (struct usb_device *rhdev); extern int hcd_bus_suspend(struct usb_device *rhdev); extern int hcd_bus_resume(struct usb_device *rhdev); #else static inline void usb_hcd_resume_root_hub(struct usb_hcd *hcd) { return; } #endif /* CONFIG_PM */ /* * USB device fs stuff */ #ifdef CONFIG_USB_DEVICEFS /* * these are expected to be called from the USB core/hub thread * with the kernel lock held */ extern void usbfs_update_special (void); extern int usbfs_init(void); extern void usbfs_cleanup(void); #else /* CONFIG_USB_DEVICEFS */ static inline void usbfs_update_special (void) {} static inline int usbfs_init(void) { return 0; } static inline void usbfs_cleanup(void) { } #endif /* CONFIG_USB_DEVICEFS */ /*-------------------------------------------------------------------------*/ #if defined(CONFIG_USB_MON) struct usb_mon_operations { void (*urb_submit)(struct usb_bus *bus, struct urb *urb); void (*urb_submit_error)(struct usb_bus *bus, struct urb *urb, int err); void (*urb_complete)(struct usb_bus *bus, struct urb *urb, int status); /* void (*urb_unlink)(struct usb_bus *bus, struct urb *urb); */ }; extern struct usb_mon_operations *mon_ops; static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) { if (bus->monitored) (*mon_ops->urb_submit)(bus, urb); } static inline void usbmon_urb_submit_error(struct usb_bus *bus, struct urb *urb, int error) { if (bus->monitored) (*mon_ops->urb_submit_error)(bus, urb, error); } static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb, int status) { if (bus->monitored) (*mon_ops->urb_complete)(bus, urb, status); } int usb_mon_register(struct usb_mon_operations *ops); void usb_mon_deregister(void); #else static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) {} static inline void usbmon_urb_submit_error(struct usb_bus *bus, struct urb *urb, int error) {} static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb, int status) {} #endif /* CONFIG_USB_MON */ /*-------------------------------------------------------------------------*/ /* hub.h ... DeviceRemovable in 2.4.2-ac11, gone in 2.4.10 */ // bleech -- resurfaced in 2.4.11 or 2.4.12 #define bitmap DeviceRemovable /*-------------------------------------------------------------------------*/ /* random stuff */ #define RUN_CONTEXT (in_irq () ? "in_irq" \ : (in_interrupt () ? "in_interrupt" : "can sleep")) /* This rwsem is for use only by the hub driver and ehci-hcd. * Nobody else should touch it. */ extern struct rw_semaphore ehci_cf_port_reset_rwsem; #endif /* __KERNEL__ */
blakearnold/MPR
drivers/usb/core/hcd.h
C
gpl-2.0
15,632
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import re from PyQt5 import QtWidgets from picard import config from picard.plugin import ExtensionPoint class OptionsCheckError(Exception): def __init__(self, title, info): self.title = title self.info = info class OptionsPage(QtWidgets.QWidget): PARENT = None SORT_ORDER = 1000 ACTIVE = True STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }" STYLESHEET = "QLabel { qproperty-wordWrap: true; }" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setStyleSheet(self.STYLESHEET) def info(self): raise NotImplementedError def check(self): pass def load(self): pass def save(self): pass def restore_defaults(self): try: options = self.options except AttributeError: return old_options = {} for option in options: if option.section == 'setting': old_options[option.name] = config.setting[option.name] config.setting[option.name] = option.default self.load() # Restore the config values incase the user doesn't save after restoring defaults for key in old_options: config.setting[key] = old_options[key] def display_error(self, error): dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self) dialog.exec_() def init_regex_checker(self, regex_edit, regex_error): """ regex_edit : a widget supporting text() and textChanged() methods, ie QLineEdit regex_error : a widget supporting setStyleSheet() and setText() methods, ie. QLabel """ def check(): try: re.compile(regex_edit.text()) except re.error as e: raise OptionsCheckError(_("Regex Error"), string_(e)) def live_checker(text): regex_error.setStyleSheet("") regex_error.setText("") try: check() except OptionsCheckError as e: regex_error.setStyleSheet(self.STYLESHEET_ERROR) regex_error.setText(e.info) regex_edit.textChanged.connect(live_checker) _pages = ExtensionPoint() def register_options_page(page_class): _pages.register(page_class.__module__, page_class)
samj1912/picard
picard/ui/options/__init__.py
Python
gpl-2.0
3,282
/* MI Command Set - disassemble commands. Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Contributed by Cygnus Solutions (a Red Hat company). This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "target.h" #include "value.h" #include "mi-cmds.h" #include "mi-getopt.h" #include "gdb_string.h" #include "ui-out.h" #include "disasm.h" /* The arguments to be passed on the command line and parsed here are: either: START-ADDRESS: address to start the disassembly at. END-ADDRESS: address to end the disassembly at. or: FILENAME: The name of the file where we want disassemble from. LINE: The line around which we want to disassemble. It will disassemble the function that contins that line. HOW_MANY: Number of disassembly lines to display. In mixed mode, it is the number of disassembly lines only, not counting the source lines. always required: MODE: 0 or 1 for disassembly only, or mixed source and disassembly, respectively. */ void mi_cmd_disassemble (char *command, char **argv, int argc) { CORE_ADDR start; int mixed_source_and_assembly; struct symtab *s; /* Which options have we processed ... */ int file_seen = 0; int line_seen = 0; int num_seen = 0; int start_seen = 0; int end_seen = 0; /* ... and their corresponding value. */ char *file_string = NULL; int line_num = -1; int how_many = -1; CORE_ADDR low = 0; CORE_ADDR high = 0; /* Options processing stuff. */ int optind = 0; char *optarg; enum opt { FILE_OPT, LINE_OPT, NUM_OPT, START_OPT, END_OPT }; static struct mi_opt opts[] = { {"f", FILE_OPT, 1}, {"l", LINE_OPT, 1}, {"n", NUM_OPT, 1}, {"s", START_OPT, 1}, {"e", END_OPT, 1}, { 0, 0, 0 } }; /* Get the options with their arguments. Keep track of what we encountered. */ while (1) { int opt = mi_getopt ("mi_cmd_disassemble", argc, argv, opts, &optind, &optarg); if (opt < 0) break; switch ((enum opt) opt) { case FILE_OPT: file_string = xstrdup (optarg); file_seen = 1; break; case LINE_OPT: line_num = atoi (optarg); line_seen = 1; break; case NUM_OPT: how_many = atoi (optarg); num_seen = 1; break; case START_OPT: low = parse_and_eval_address (optarg); start_seen = 1; break; case END_OPT: high = parse_and_eval_address (optarg); end_seen = 1; break; } } argv += optind; argc -= optind; /* Allow only filename + linenum (with how_many which is not required) OR start_addr + and_addr */ if (!((line_seen && file_seen && num_seen && !start_seen && !end_seen) || (line_seen && file_seen && !num_seen && !start_seen && !end_seen) || (!line_seen && !file_seen && !num_seen && start_seen && end_seen))) error ("mi_cmd_disassemble: Usage: ( [-f filename -l linenum [-n howmany]] | [-s startaddr -e endaddr]) [--] mixed_mode."); if (argc != 1) error ("mi_cmd_disassemble: Usage: [-f filename -l linenum [-n howmany]] [-s startaddr -e endaddr] [--] mixed_mode."); mixed_source_and_assembly = atoi (argv[0]); if ((mixed_source_and_assembly != 0) && (mixed_source_and_assembly != 1)) error (_("mi_cmd_disassemble: Mixed_mode argument must be 0 or 1.")); /* We must get the function beginning and end where line_num is contained. */ if (line_seen && file_seen) { s = lookup_symtab (file_string); if (s == NULL) error (_("mi_cmd_disassemble: Invalid filename.")); if (!find_line_pc (s, line_num, &start)) error (_("mi_cmd_disassemble: Invalid line number")); if (find_pc_partial_function (start, NULL, &low, &high) == 0) error (_("mi_cmd_disassemble: No function contains specified address")); } gdb_disassembly (uiout, file_string, line_num, mixed_source_and_assembly, how_many, low, high); }
sergiodj/gdb-sergio
gdb/mi/mi-cmd-disas.c
C
gpl-2.0
4,527
/** ****************************************************************************** * @file TIM/TIM_TimeBase/Src/main.c * @author MCD Application Team * @version V1.2.3 * @date 09-October-2015 * @brief This sample code shows how to use STM32F4xx TIM HAL API to generate * a time base. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * 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 STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup TIM_TimeBase * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Timer handler declaration */ TIM_HandleTypeDef TimHandle; uint32_t uwPrescalerValue = 0; /* Private function prototypes -----------------------------------------------*/ static void SystemClock_Config(void); static void Error_Handler(void); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Global MSP (MCU Support Package) initialization */ HAL_Init(); /* Configure the system clock to 168 MHz */ SystemClock_Config(); /* Configure LED1 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /*##-1- Configure the TIM peripheral #######################################*/ /* ----------------------------------------------------------------------- In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), since APB1 prescaler is different from 1. TIM3CLK = 2 * PCLK1 PCLK1 = HCLK / 4 => TIM3CLK = HCLK / 2 = SystemCoreClock /2 To get TIM3 counter clock at 10 KHz, the Prescaler is computed as following: Prescaler = (TIM3CLK / TIM3 counter clock) - 1 Prescaler = ((SystemCoreClock /2) /10 KHz) - 1 Note: SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file. Each time the core clock (HCLK) changes, user had to update SystemCoreClock variable value. Otherwise, any configuration based on this variable will be incorrect. This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetSysClockFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency ----------------------------------------------------------------------- */ /* Compute the prescaler value to have TIM3 counter clock equal to 10 KHz */ uwPrescalerValue = (uint32_t) ((SystemCoreClock /2) / 10000) - 1; /* Set TIMx instance */ TimHandle.Instance = TIMx; /* Initialize TIM3 peripheral as follow: + Period = 10000 - 1 + Prescaler = ((SystemCoreClock/2)/10000) - 1 + ClockDivision = 0 + Counter direction = Up */ TimHandle.Init.Period = 10000 - 1; TimHandle.Init.Prescaler = uwPrescalerValue; TimHandle.Init.ClockDivision = 0; TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; if(HAL_TIM_Base_Init(&TimHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*##-2- Start the TIM Base generation in interrupt mode ####################*/ /* Start Channel1 */ if(HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK) { /* Starting Error */ Error_Handler(); } /* Infinite loop */ while (1) { } } /** * @brief Period elapsed callback in non blocking mode * @param htim : TIM handle * @retval None */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { BSP_LED_Toggle(LED1); } /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ static void Error_Handler(void) { /* Turn LED3 on */ BSP_LED_On(LED3); while(1) { } } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 168000000 * HCLK(Hz) = 168000000 * AHB Prescaler = 1 * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 25000000 * PLL_M = 25 * PLL_N = 336 * PLL_P = 2 * PLL_Q = 7 * VDD(V) = 3.3 * Main regulator output voltage = Scale1 mode * Flash Latency(WS) = 5 * @param None * @retval None */ static void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; /* Enable Power Control clock */ __HAL_RCC_PWR_CLK_ENABLE(); /* The voltage scaling allows optimizing the power consumption when the device is clocked below the maximum system frequency, to update the voltage scaling value regarding system frequency refer to product datasheet. */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /* Enable HSE Oscillator and activate PLL with HSE as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 25; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 7; HAL_RCC_OscConfig(&RCC_OscInitStruct); /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); /* STM32F405x/407x/415x/417x Revision Z devices: prefetch is supported */ if (HAL_GetREVID() == 0x1001) { /* Enable the Flash prefetch */ __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); } } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
kamfor/STMF4
STM/Projects/STM324xG_EVAL/Examples/TIM/TIM_TimeBase/Src/main.c
C
gpl-2.0
9,525
<?php /* * DynamicHub * * Copyright (C) 2015-2016 LegendsOfMCPE * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author LegendsOfMCPE */ namespace DynamicHub\Module\Match; class MatchBaseConfig{ // players public $maxPlayers; public $semiMaxPlayers; public $minPlayers; // time, in seconds public $minWaitTime; public $maxWaitTime; public $maxMatchTime; public $maxPrepTime; // positions public $playerJoinPositions = []; public $spectatorJoinPositions = []; public function getNextPlayerJoinPosition(){ if(next($this->playerJoinPositions) === false){ reset($this->playerJoinPositions); } return current($this->playerJoinPositions); } public function getNextSpectatorJoinPosition(){ if(next($this->spectatorJoinPositions) === false){ reset($this->spectatorJoinPositions); } return current($this->spectatorJoinPositions); } }
LegendOfMCPE/DynamicHub
DynamicHub/src/DynamicHub/Module/Match/MatchBaseConfig.php
PHP
gpl-2.0
1,090
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LogicaDeNegocios")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Intel Corporation")] [assembly: AssemblyProduct("LogicaDeNegocios")] [assembly: AssemblyCopyright("Copyright © Intel Corporation 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("979b681f-8f57-479b-a119-c830ef08f826")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
pabloariasmora/BattlePong
BattlePong/LogicaDeNegocios/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,442
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>schrodinger.application.desmond.replica_sid_generator.ProteinReport</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.application-module.html">Package&nbsp;application</a> :: <a href="schrodinger.application.desmond-module.html">Package&nbsp;desmond</a> :: <a href="schrodinger.application.desmond.replica_sid_generator-module.html">Module&nbsp;replica_sid_generator</a> :: Class&nbsp;ProteinReport </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.application.desmond.replica_sid_generator.ProteinReport-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class ProteinReport</h1><p class="nomargin-top"></p> <pre class="base-tree"> <a href="object-class.html">object</a> --+ | <strong class="uidshort">ProteinReport</strong> </pre> <hr /> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.application.desmond.replica_sid_generator.ProteinReport-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">cms_st</span>)</span><br /> x.__init__(...) initializes x; see help(type(x)) for signature</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="export"></a><span class="summary-sig-name">export</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_hot_atoms"></a><span class="summary-sig-name">get_hot_atoms</span>(<span class="summary-sig-arg">self</span>)</span><br /> Returns number of atoms in the hot region</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_residues"></a><span class="summary-sig-name">get_residues</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_number_atoms"></a><span class="summary-sig-name">get_number_atoms</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="get_protein"></a><span class="summary-sig-name">get_protein</span>(<span class="summary-sig-arg">self</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__delattr__">__delattr__</a></code>, <code><a href="object-class.html#__format__">__format__</a></code>, <code><a href="object-class.html#__getattribute__">__getattribute__</a></code>, <code><a href="object-class.html#__hash__">__hash__</a></code>, <code><a href="object-class.html#__new__">__new__</a></code>, <code><a href="object-class.html#__reduce__">__reduce__</a></code>, <code><a href="object-class.html#__reduce_ex__">__reduce_ex__</a></code>, <code><a href="object-class.html#__repr__">__repr__</a></code>, <code><a href="object-class.html#__setattr__">__setattr__</a></code>, <code><a href="object-class.html#__sizeof__">__sizeof__</a></code>, <code><a href="object-class.html#__str__">__str__</a></code>, <code><a href="object-class.html#__subclasshook__">__subclasshook__</a></code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="object-class.html">object</a></code></b>: <code><a href="object-class.html#__class__">__class__</a></code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">cms_st</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>x.__init__(...) initializes x; see help(type(x)) for signature</p> <dl class="fields"> <dt>Overrides: object.__init__ <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >2015-2Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sat May 9 06:31:10 2015 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
platinhom/ManualHom
Schrodinger/Schrodinger_2015-2_docs/python_api/api/schrodinger.application.desmond.replica_sid_generator.ProteinReport-class.html
HTML
gpl-2.0
12,025
<?php /* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * Service definition for Pagespeedonline (v1). * * <p> * Lets you analyze the performance of a web page and get tailored suggestions to make that page faster. * </p> * * <p> * For more information about this service, see the API * <a href="https://developers.google.com/speed/docs/insights/v1/getting_started" target="_blank">Documentation</a> * </p> * * @author Google, Inc. */ class GoogleGAL_Service_Pagespeedonline extends GoogleGAL_Service { public $pagespeedapi; /** * Constructs the internal representation of the Pagespeedonline service. * * @param GoogleGAL_Client $client */ public function __construct(GoogleGAL_Client $client) { parent::__construct($client); $this->servicePath = 'pagespeedonline/v1/'; $this->version = 'v1'; $this->serviceName = 'pagespeedonline'; $this->pagespeedapi = new GoogleGAL_Service_Pagespeedonline_Pagespeedapi_Resource( $this, $this->serviceName, 'pagespeedapi', array( 'methods' => array( 'runpagespeed' => array( 'path' => 'runPagespeed', 'httpMethod' => 'GET', 'parameters' => array( 'url' => array( 'location' => 'query', 'type' => 'string', 'required' => true, ), 'screenshot' => array( 'location' => 'query', 'type' => 'boolean', ), 'locale' => array( 'location' => 'query', 'type' => 'string', ), 'snapshots' => array( 'location' => 'query', 'type' => 'boolean', ), 'strategy' => array( 'location' => 'query', 'type' => 'string', ), 'rule' => array( 'location' => 'query', 'type' => 'string', 'repeated' => true, ), 'filter_third_party_resources' => array( 'location' => 'query', 'type' => 'boolean', ), ), ), ) ) ); } } /** * The "pagespeedapi" collection of methods. * Typical usage is: * <code> * $pagespeedonlineService = new GoogleGAL_Service_Pagespeedonline(...); * $pagespeedapi = $pagespeedonlineService->pagespeedapi; * </code> */ class GoogleGAL_Service_Pagespeedonline_Pagespeedapi_Resource extends GoogleGAL_Service_Resource { /** * Runs Page Speed analysis on the page at the specified URL, and returns a Page * Speed score, a list of suggestions to make that page faster, and other * information. (pagespeedapi.runpagespeed) * * @param string $url * The URL to fetch and analyze * @param array $optParams Optional parameters. * * @opt_param bool screenshot * Indicates if binary data containing a screenshot should be included * @opt_param string locale * The locale used to localize formatted results * @opt_param bool snapshots * Indicates if binary data containing snapshot images should be included * @opt_param string strategy * The analysis strategy to use * @opt_param string rule * A Page Speed rule to run; if none are given, all rules are run * @opt_param bool filter_third_party_resources * Indicates if third party resources should be filtered out before PageSpeed analysis. * @return GoogleGAL_Service_Pagespeedonline_Result */ public function runpagespeed($url, $optParams = array()) { $params = array('url' => $url); $params = array_merge($params, $optParams); return $this->call('runpagespeed', array($params), "GoogleGAL_Service_Pagespeedonline_Result"); } } class GoogleGAL_Service_Pagespeedonline_Result extends GoogleGAL_Collection { protected $formattedResultsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResults'; protected $formattedResultsDataType = ''; public $id; public $invalidRules; public $kind; protected $pageStatsType = 'GoogleGAL_Service_Pagespeedonline_ResultPageStats'; protected $pageStatsDataType = ''; public $responseCode; public $score; protected $screenshotType = 'GoogleGAL_Service_Pagespeedonline_ResultScreenshot'; protected $screenshotDataType = ''; public $title; protected $versionType = 'GoogleGAL_Service_Pagespeedonline_ResultVersion'; protected $versionDataType = ''; public function setFormattedResults(GoogleGAL_Service_Pagespeedonline_ResultFormattedResults $formattedResults) { $this->formattedResults = $formattedResults; } public function getFormattedResults() { return $this->formattedResults; } public function setId($id) { $this->id = $id; } public function getId() { return $this->id; } public function setInvalidRules($invalidRules) { $this->invalidRules = $invalidRules; } public function getInvalidRules() { return $this->invalidRules; } public function setKind($kind) { $this->kind = $kind; } public function getKind() { return $this->kind; } public function setPageStats(GoogleGAL_Service_Pagespeedonline_ResultPageStats $pageStats) { $this->pageStats = $pageStats; } public function getPageStats() { return $this->pageStats; } public function setResponseCode($responseCode) { $this->responseCode = $responseCode; } public function getResponseCode() { return $this->responseCode; } public function setScore($score) { $this->score = $score; } public function getScore() { return $this->score; } public function setScreenshot(GoogleGAL_Service_Pagespeedonline_ResultScreenshot $screenshot) { $this->screenshot = $screenshot; } public function getScreenshot() { return $this->screenshot; } public function setTitle($title) { $this->title = $title; } public function getTitle() { return $this->title; } public function setVersion(GoogleGAL_Service_Pagespeedonline_ResultVersion $version) { $this->version = $version; } public function getVersion() { return $this->version; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResults extends GoogleGAL_Model { public $locale; protected $ruleResultsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElement'; protected $ruleResultsDataType = 'map'; public function setLocale($locale) { $this->locale = $locale; } public function getLocale() { return $this->locale; } public function setRuleResults($ruleResults) { $this->ruleResults = $ruleResults; } public function getRuleResults() { return $this->ruleResults; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElement extends GoogleGAL_Collection { public $localizedRuleName; public $ruleImpact; protected $urlBlocksType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocks'; protected $urlBlocksDataType = 'array'; public function setLocalizedRuleName($localizedRuleName) { $this->localizedRuleName = $localizedRuleName; } public function getLocalizedRuleName() { return $this->localizedRuleName; } public function setRuleImpact($ruleImpact) { $this->ruleImpact = $ruleImpact; } public function getRuleImpact() { return $this->ruleImpact; } public function setUrlBlocks($urlBlocks) { $this->urlBlocks = $urlBlocks; } public function getUrlBlocks() { return $this->urlBlocks; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocks extends GoogleGAL_Collection { protected $headerType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader'; protected $headerDataType = ''; protected $urlsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrls'; protected $urlsDataType = 'array'; public function setHeader(GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader $header) { $this->header = $header; } public function getHeader() { return $this->header; } public function setUrls($urls) { $this->urls = $urls; } public function getUrls() { return $this->urls; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeader extends GoogleGAL_Collection { protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeaderArgs'; protected $argsDataType = 'array'; public $format; public function setArgs($args) { $this->args = $args; } public function getArgs() { return $this->args; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksHeaderArgs extends GoogleGAL_Model { public $type; public $value; public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrls extends GoogleGAL_Collection { protected $detailsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetails'; protected $detailsDataType = 'array'; protected $resultType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult'; protected $resultDataType = ''; public function setDetails($details) { $this->details = $details; } public function getDetails() { return $this->details; } public function setResult(GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult $result) { $this->result = $result; } public function getResult() { return $this->result; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetails extends GoogleGAL_Collection { protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetailsArgs'; protected $argsDataType = 'array'; public $format; public function setArgs($args) { $this->args = $args; } public function getArgs() { return $this->args; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsDetailsArgs extends GoogleGAL_Model { public $type; public $value; public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResult extends GoogleGAL_Collection { protected $argsType = 'GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResultArgs'; protected $argsDataType = 'array'; public $format; public function setArgs($args) { $this->args = $args; } public function getArgs() { return $this->args; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } } class GoogleGAL_Service_Pagespeedonline_ResultFormattedResultsRuleResultsElementUrlBlocksUrlsResultArgs extends GoogleGAL_Model { public $type; public $value; public function setType($type) { $this->type = $type; } public function getType() { return $this->type; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } } class GoogleGAL_Service_Pagespeedonline_ResultPageStats extends GoogleGAL_Model { public $cssResponseBytes; public $flashResponseBytes; public $htmlResponseBytes; public $imageResponseBytes; public $javascriptResponseBytes; public $numberCssResources; public $numberHosts; public $numberJsResources; public $numberResources; public $numberStaticResources; public $otherResponseBytes; public $textResponseBytes; public $totalRequestBytes; public function setCssResponseBytes($cssResponseBytes) { $this->cssResponseBytes = $cssResponseBytes; } public function getCssResponseBytes() { return $this->cssResponseBytes; } public function setFlashResponseBytes($flashResponseBytes) { $this->flashResponseBytes = $flashResponseBytes; } public function getFlashResponseBytes() { return $this->flashResponseBytes; } public function setHtmlResponseBytes($htmlResponseBytes) { $this->htmlResponseBytes = $htmlResponseBytes; } public function getHtmlResponseBytes() { return $this->htmlResponseBytes; } public function setImageResponseBytes($imageResponseBytes) { $this->imageResponseBytes = $imageResponseBytes; } public function getImageResponseBytes() { return $this->imageResponseBytes; } public function setJavascriptResponseBytes($javascriptResponseBytes) { $this->javascriptResponseBytes = $javascriptResponseBytes; } public function getJavascriptResponseBytes() { return $this->javascriptResponseBytes; } public function setNumberCssResources($numberCssResources) { $this->numberCssResources = $numberCssResources; } public function getNumberCssResources() { return $this->numberCssResources; } public function setNumberHosts($numberHosts) { $this->numberHosts = $numberHosts; } public function getNumberHosts() { return $this->numberHosts; } public function setNumberJsResources($numberJsResources) { $this->numberJsResources = $numberJsResources; } public function getNumberJsResources() { return $this->numberJsResources; } public function setNumberResources($numberResources) { $this->numberResources = $numberResources; } public function getNumberResources() { return $this->numberResources; } public function setNumberStaticResources($numberStaticResources) { $this->numberStaticResources = $numberStaticResources; } public function getNumberStaticResources() { return $this->numberStaticResources; } public function setOtherResponseBytes($otherResponseBytes) { $this->otherResponseBytes = $otherResponseBytes; } public function getOtherResponseBytes() { return $this->otherResponseBytes; } public function setTextResponseBytes($textResponseBytes) { $this->textResponseBytes = $textResponseBytes; } public function getTextResponseBytes() { return $this->textResponseBytes; } public function setTotalRequestBytes($totalRequestBytes) { $this->totalRequestBytes = $totalRequestBytes; } public function getTotalRequestBytes() { return $this->totalRequestBytes; } } class GoogleGAL_Service_Pagespeedonline_ResultScreenshot extends GoogleGAL_Model { public $data; public $height; public $mimeType; public $width; public function setData($data) { $this->data = $data; } public function getData() { return $this->data; } public function setHeight($height) { $this->height = $height; } public function getHeight() { return $this->height; } public function setMimeType($mimeType) { $this->mimeType = $mimeType; } public function getMimeType() { return $this->mimeType; } public function setWidth($width) { $this->width = $width; } public function getWidth() { return $this->width; } } class GoogleGAL_Service_Pagespeedonline_ResultVersion extends GoogleGAL_Model { public $major; public $minor; public function setMajor($major) { $this->major = $major; } public function getMajor() { return $this->major; } public function setMinor($minor) { $this->minor = $minor; } public function getMinor() { return $this->minor; } }
mrengy/flip2014
wp-content/plugins/google-apps-login/core/Google/Service/Pagespeedonline.php
PHP
gpl-2.0
17,220
/* SPDX-License-Identifier: LGPL-2.1+ */ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include <errno.h> #include <sys/epoll.h> #include <sys/stat.h> #include <unistd.h> #include "libudev.h" #include "alloc-util.h" #include "dbus-swap.h" #include "escape.h" #include "exit-status.h" #include "fd-util.h" #include "format-util.h" #include "fstab-util.h" #include "parse-util.h" #include "path-util.h" #include "process-util.h" #include "special.h" #include "string-table.h" #include "string-util.h" #include "swap.h" #include "udev-util.h" #include "unit-name.h" #include "unit.h" #include "virt.h" static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = { [SWAP_DEAD] = UNIT_INACTIVE, [SWAP_ACTIVATING] = UNIT_ACTIVATING, [SWAP_ACTIVATING_DONE] = UNIT_ACTIVE, [SWAP_ACTIVE] = UNIT_ACTIVE, [SWAP_DEACTIVATING] = UNIT_DEACTIVATING, [SWAP_DEACTIVATING_SIGTERM] = UNIT_DEACTIVATING, [SWAP_DEACTIVATING_SIGKILL] = UNIT_DEACTIVATING, [SWAP_FAILED] = UNIT_FAILED }; static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata); static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata); static bool SWAP_STATE_WITH_PROCESS(SwapState state) { return IN_SET(state, SWAP_ACTIVATING, SWAP_ACTIVATING_DONE, SWAP_DEACTIVATING, SWAP_DEACTIVATING_SIGTERM, SWAP_DEACTIVATING_SIGKILL); } static void swap_unset_proc_swaps(Swap *s) { assert(s); if (!s->from_proc_swaps) return; s->parameters_proc_swaps.what = mfree(s->parameters_proc_swaps.what); s->from_proc_swaps = false; } static int swap_set_devnode(Swap *s, const char *devnode) { Hashmap *swaps; Swap *first; int r; assert(s); r = hashmap_ensure_allocated(&UNIT(s)->manager->swaps_by_devnode, &path_hash_ops); if (r < 0) return r; swaps = UNIT(s)->manager->swaps_by_devnode; if (s->devnode) { first = hashmap_get(swaps, s->devnode); LIST_REMOVE(same_devnode, first, s); if (first) hashmap_replace(swaps, first->devnode, first); else hashmap_remove(swaps, s->devnode); s->devnode = mfree(s->devnode); } if (devnode) { s->devnode = strdup(devnode); if (!s->devnode) return -ENOMEM; first = hashmap_get(swaps, s->devnode); LIST_PREPEND(same_devnode, first, s); return hashmap_replace(swaps, first->devnode, first); } return 0; } static void swap_init(Unit *u) { Swap *s = SWAP(u); assert(s); assert(UNIT(s)->load_state == UNIT_STUB); s->timeout_usec = u->manager->default_timeout_start_usec; s->exec_context.std_output = u->manager->default_std_output; s->exec_context.std_error = u->manager->default_std_error; s->parameters_proc_swaps.priority = s->parameters_fragment.priority = -1; s->control_command_id = _SWAP_EXEC_COMMAND_INVALID; u->ignore_on_isolate = true; } static void swap_unwatch_control_pid(Swap *s) { assert(s); if (s->control_pid <= 0) return; unit_unwatch_pid(UNIT(s), s->control_pid); s->control_pid = 0; } static void swap_done(Unit *u) { Swap *s = SWAP(u); assert(s); swap_unset_proc_swaps(s); swap_set_devnode(s, NULL); s->what = mfree(s->what); s->parameters_fragment.what = mfree(s->parameters_fragment.what); s->parameters_fragment.options = mfree(s->parameters_fragment.options); s->exec_runtime = exec_runtime_unref(s->exec_runtime, false); exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX); s->control_command = NULL; dynamic_creds_unref(&s->dynamic_creds); swap_unwatch_control_pid(s); s->timer_event_source = sd_event_source_unref(s->timer_event_source); } static int swap_arm_timer(Swap *s, usec_t usec) { int r; assert(s); if (s->timer_event_source) { r = sd_event_source_set_time(s->timer_event_source, usec); if (r < 0) return r; return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT); } if (usec == USEC_INFINITY) return 0; r = sd_event_add_time( UNIT(s)->manager->event, &s->timer_event_source, CLOCK_MONOTONIC, usec, 0, swap_dispatch_timer, s); if (r < 0) return r; (void) sd_event_source_set_description(s->timer_event_source, "swap-timer"); return 0; } static int swap_add_device_dependencies(Swap *s) { assert(s); if (!s->what) return 0; if (!s->from_fragment) return 0; if (is_device_path(s->what)) return unit_add_node_dependency(UNIT(s), s->what, MANAGER_IS_SYSTEM(UNIT(s)->manager), UNIT_BINDS_TO, UNIT_DEPENDENCY_FILE); else /* File based swap devices need to be ordered after * systemd-remount-fs.service, since they might need a * writable file system. */ return unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, NULL, true, UNIT_DEPENDENCY_FILE); } static int swap_add_default_dependencies(Swap *s) { int r; assert(s); if (!UNIT(s)->default_dependencies) return 0; if (!MANAGER_IS_SYSTEM(UNIT(s)->manager)) return 0; if (detect_container() > 0) return 0; /* swap units generated for the swap dev links are missing the * ordering dep against the swap target. */ r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SWAP_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT); if (r < 0) return r; return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true, UNIT_DEPENDENCY_DEFAULT); } static int swap_verify(Swap *s) { _cleanup_free_ char *e = NULL; int r; if (UNIT(s)->load_state != UNIT_LOADED) return 0; r = unit_name_from_path(s->what, ".swap", &e); if (r < 0) return log_unit_error_errno(UNIT(s), r, "Failed to generate unit name from path: %m"); if (!unit_has_name(UNIT(s), e)) { log_unit_error(UNIT(s), "Value of What= and unit name do not match, not loading."); return -EINVAL; } if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) { log_unit_error(UNIT(s), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load."); return -EINVAL; } return 0; } static int swap_load_devnode(Swap *s) { _cleanup_udev_device_unref_ struct udev_device *d = NULL; struct stat st; const char *p; assert(s); if (stat(s->what, &st) < 0 || !S_ISBLK(st.st_mode)) return 0; d = udev_device_new_from_devnum(UNIT(s)->manager->udev, 'b', st.st_rdev); if (!d) return 0; p = udev_device_get_devnode(d); if (!p) return 0; return swap_set_devnode(s, p); } static int swap_load(Unit *u) { int r; Swap *s = SWAP(u); assert(s); assert(u->load_state == UNIT_STUB); /* Load a .swap file */ if (SWAP(u)->from_proc_swaps) r = unit_load_fragment_and_dropin_optional(u); else r = unit_load_fragment_and_dropin(u); if (r < 0) return r; if (u->load_state == UNIT_LOADED) { if (UNIT(s)->fragment_path) s->from_fragment = true; if (!s->what) { if (s->parameters_fragment.what) s->what = strdup(s->parameters_fragment.what); else if (s->parameters_proc_swaps.what) s->what = strdup(s->parameters_proc_swaps.what); else { r = unit_name_to_path(u->id, &s->what); if (r < 0) return r; } if (!s->what) return -ENOMEM; } path_kill_slashes(s->what); if (!UNIT(s)->description) { r = unit_set_description(u, s->what); if (r < 0) return r; } r = unit_require_mounts_for(UNIT(s), s->what, UNIT_DEPENDENCY_IMPLICIT); if (r < 0) return r; r = swap_add_device_dependencies(s); if (r < 0) return r; r = swap_load_devnode(s); if (r < 0) return r; r = unit_patch_contexts(u); if (r < 0) return r; r = unit_add_exec_dependencies(u, &s->exec_context); if (r < 0) return r; r = unit_set_default_slice(u); if (r < 0) return r; r = swap_add_default_dependencies(s); if (r < 0) return r; } return swap_verify(s); } static int swap_setup_unit( Manager *m, const char *what, const char *what_proc_swaps, int priority, bool set_flags) { _cleanup_free_ char *e = NULL; bool delete = false; Unit *u = NULL; int r; SwapParameters *p; assert(m); assert(what); assert(what_proc_swaps); r = unit_name_from_path(what, ".swap", &e); if (r < 0) return log_unit_error_errno(u, r, "Failed to generate unit name from path: %m"); u = manager_get_unit(m, e); if (u && SWAP(u)->from_proc_swaps && !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps)) { log_error("Swap %s appeared twice with different device paths %s and %s", e, SWAP(u)->parameters_proc_swaps.what, what_proc_swaps); return -EEXIST; } if (!u) { delete = true; r = unit_new_for_name(m, sizeof(Swap), e, &u); if (r < 0) goto fail; SWAP(u)->what = strdup(what); if (!SWAP(u)->what) { r = -ENOMEM; goto fail; } unit_add_to_load_queue(u); } else delete = false; p = &SWAP(u)->parameters_proc_swaps; if (!p->what) { p->what = strdup(what_proc_swaps); if (!p->what) { r = -ENOMEM; goto fail; } } if (set_flags) { SWAP(u)->is_active = true; SWAP(u)->just_activated = !SWAP(u)->from_proc_swaps; } SWAP(u)->from_proc_swaps = true; p->priority = priority; unit_add_to_dbus_queue(u); return 0; fail: log_unit_warning_errno(u, r, "Failed to load swap unit: %m"); if (delete) unit_free(u); return r; } static int swap_process_new(Manager *m, const char *device, int prio, bool set_flags) { _cleanup_udev_device_unref_ struct udev_device *d = NULL; struct udev_list_entry *item = NULL, *first = NULL; const char *dn; struct stat st; int r; assert(m); r = swap_setup_unit(m, device, device, prio, set_flags); if (r < 0) return r; /* If this is a block device, then let's add duplicates for * all other names of this block device */ if (stat(device, &st) < 0 || !S_ISBLK(st.st_mode)) return 0; d = udev_device_new_from_devnum(m->udev, 'b', st.st_rdev); if (!d) return 0; /* Add the main device node */ dn = udev_device_get_devnode(d); if (dn && !streq(dn, device)) swap_setup_unit(m, dn, device, prio, set_flags); /* Add additional units for all symlinks */ first = udev_device_get_devlinks_list_entry(d); udev_list_entry_foreach(item, first) { const char *p; /* Don't bother with the /dev/block links */ p = udev_list_entry_get_name(item); if (streq(p, device)) continue; if (path_startswith(p, "/dev/block/")) continue; if (stat(p, &st) >= 0) if (!S_ISBLK(st.st_mode) || st.st_rdev != udev_device_get_devnum(d)) continue; swap_setup_unit(m, p, device, prio, set_flags); } return r; } static void swap_set_state(Swap *s, SwapState state) { SwapState old_state; Swap *other; assert(s); old_state = s->state; s->state = state; if (!SWAP_STATE_WITH_PROCESS(state)) { s->timer_event_source = sd_event_source_unref(s->timer_event_source); swap_unwatch_control_pid(s); s->control_command = NULL; s->control_command_id = _SWAP_EXEC_COMMAND_INVALID; } if (state != old_state) log_unit_debug(UNIT(s), "Changed %s -> %s", swap_state_to_string(old_state), swap_state_to_string(state)); unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true); /* If there other units for the same device node have a job queued it might be worth checking again if it is runnable now. This is necessary, since swap_start() refuses operation with EAGAIN if there's already another job for the same device node queued. */ LIST_FOREACH_OTHERS(same_devnode, other, s) if (UNIT(other)->job) job_add_to_run_queue(UNIT(other)->job); } static int swap_coldplug(Unit *u) { Swap *s = SWAP(u); SwapState new_state = SWAP_DEAD; int r; assert(s); assert(s->state == SWAP_DEAD); if (s->deserialized_state != s->state) new_state = s->deserialized_state; else if (s->from_proc_swaps) new_state = SWAP_ACTIVE; if (new_state == s->state) return 0; if (s->control_pid > 0 && pid_is_unwaited(s->control_pid) && SWAP_STATE_WITH_PROCESS(new_state)) { r = unit_watch_pid(UNIT(s), s->control_pid); if (r < 0) return r; r = swap_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec)); if (r < 0) return r; } if (!IN_SET(new_state, SWAP_DEAD, SWAP_FAILED)) { (void) unit_setup_dynamic_creds(u); (void) unit_setup_exec_runtime(u); } swap_set_state(s, new_state); return 0; } static void swap_dump(Unit *u, FILE *f, const char *prefix) { char buf[FORMAT_TIMESPAN_MAX]; Swap *s = SWAP(u); SwapParameters *p; assert(s); assert(f); if (s->from_proc_swaps) p = &s->parameters_proc_swaps; else if (s->from_fragment) p = &s->parameters_fragment; else p = NULL; fprintf(f, "%sSwap State: %s\n" "%sResult: %s\n" "%sWhat: %s\n" "%sFrom /proc/swaps: %s\n" "%sFrom fragment: %s\n", prefix, swap_state_to_string(s->state), prefix, swap_result_to_string(s->result), prefix, s->what, prefix, yes_no(s->from_proc_swaps), prefix, yes_no(s->from_fragment)); if (s->devnode) fprintf(f, "%sDevice Node: %s\n", prefix, s->devnode); if (p) fprintf(f, "%sPriority: %i\n" "%sOptions: %s\n", prefix, p->priority, prefix, strempty(p->options)); fprintf(f, "%sTimeoutSec: %s\n", prefix, format_timespan(buf, sizeof(buf), s->timeout_usec, USEC_PER_SEC)); if (s->control_pid > 0) fprintf(f, "%sControl PID: "PID_FMT"\n", prefix, s->control_pid); exec_context_dump(&s->exec_context, f, prefix); kill_context_dump(&s->kill_context, f, prefix); cgroup_context_dump(&s->cgroup_context, f, prefix); } static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) { ExecParameters exec_params = { .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN, .stdin_fd = -1, .stdout_fd = -1, .stderr_fd = -1, }; pid_t pid; int r; assert(s); assert(c); assert(_pid); r = unit_prepare_exec(UNIT(s)); if (r < 0) return r; r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec)); if (r < 0) goto fail; manager_set_exec_params(UNIT(s)->manager, &exec_params); unit_set_exec_params(UNIT(s), &exec_params); r = exec_spawn(UNIT(s), c, &s->exec_context, &exec_params, s->exec_runtime, &s->dynamic_creds, &pid); if (r < 0) goto fail; r = unit_watch_pid(UNIT(s), pid); if (r < 0) /* FIXME: we need to do something here */ goto fail; *_pid = pid; return 0; fail: s->timer_event_source = sd_event_source_unref(s->timer_event_source); return r; } static void swap_enter_dead(Swap *s, SwapResult f) { assert(s); if (s->result == SWAP_SUCCESS) s->result = f; if (s->result != SWAP_SUCCESS) log_unit_warning(UNIT(s), "Failed with result '%s'.", swap_result_to_string(s->result)); swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD); s->exec_runtime = exec_runtime_unref(s->exec_runtime, true); exec_context_destroy_runtime_directory(&s->exec_context, UNIT(s)->manager->prefix[EXEC_DIRECTORY_RUNTIME]); unit_unref_uid_gid(UNIT(s), true); dynamic_creds_destroy(&s->dynamic_creds); } static void swap_enter_active(Swap *s, SwapResult f) { assert(s); if (s->result == SWAP_SUCCESS) s->result = f; swap_set_state(s, SWAP_ACTIVE); } static void swap_enter_dead_or_active(Swap *s, SwapResult f) { assert(s); if (s->from_proc_swaps) swap_enter_active(s, f); else swap_enter_dead(s, f); } static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) { int r; KillOperation kop; assert(s); if (s->result == SWAP_SUCCESS) s->result = f; if (state == SWAP_DEACTIVATING_SIGTERM) kop = KILL_TERMINATE; else kop = KILL_KILL; r = unit_kill_context(UNIT(s), &s->kill_context, kop, -1, s->control_pid, false); if (r < 0) goto fail; if (r > 0) { r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec)); if (r < 0) goto fail; swap_set_state(s, state); } else if (state == SWAP_DEACTIVATING_SIGTERM && s->kill_context.send_sigkill) swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_SUCCESS); else swap_enter_dead_or_active(s, SWAP_SUCCESS); return; fail: log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m"); swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES); } static void swap_enter_activating(Swap *s) { _cleanup_free_ char *opts = NULL; int r; assert(s); unit_warn_leftover_processes(UNIT(s)); s->control_command_id = SWAP_EXEC_ACTIVATE; s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE; if (s->from_fragment) { int priority = -1; r = fstab_find_pri(s->parameters_fragment.options, &priority); if (r < 0) log_warning_errno(r, "Failed to parse swap priority \"%s\", ignoring: %m", s->parameters_fragment.options); else if (r == 1 && s->parameters_fragment.priority >= 0) log_warning("Duplicate swap priority configuration by Priority and Options fields."); if (r <= 0 && s->parameters_fragment.priority >= 0) { if (s->parameters_fragment.options) r = asprintf(&opts, "%s,pri=%i", s->parameters_fragment.options, s->parameters_fragment.priority); else r = asprintf(&opts, "pri=%i", s->parameters_fragment.priority); if (r < 0) goto fail; } } r = exec_command_set(s->control_command, "/sbin/swapon", NULL); if (r < 0) goto fail; if (s->parameters_fragment.options || opts) { r = exec_command_append(s->control_command, "-o", opts ? : s->parameters_fragment.options, NULL); if (r < 0) goto fail; } r = exec_command_append(s->control_command, s->what, NULL); if (r < 0) goto fail; swap_unwatch_control_pid(s); r = swap_spawn(s, s->control_command, &s->control_pid); if (r < 0) goto fail; swap_set_state(s, SWAP_ACTIVATING); return; fail: log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapon' task: %m"); swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES); } static void swap_enter_deactivating(Swap *s) { int r; assert(s); s->control_command_id = SWAP_EXEC_DEACTIVATE; s->control_command = s->exec_command + SWAP_EXEC_DEACTIVATE; r = exec_command_set(s->control_command, "/sbin/swapoff", s->what, NULL); if (r < 0) goto fail; swap_unwatch_control_pid(s); r = swap_spawn(s, s->control_command, &s->control_pid); if (r < 0) goto fail; swap_set_state(s, SWAP_DEACTIVATING); return; fail: log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapoff' task: %m"); swap_enter_dead_or_active(s, SWAP_FAILURE_RESOURCES); } static int swap_start(Unit *u) { Swap *s = SWAP(u), *other; int r; assert(s); /* We cannot fulfill this request right now, try again later please! */ if (IN_SET(s->state, SWAP_DEACTIVATING, SWAP_DEACTIVATING_SIGTERM, SWAP_DEACTIVATING_SIGKILL)) return -EAGAIN; /* Already on it! */ if (s->state == SWAP_ACTIVATING) return 0; assert(IN_SET(s->state, SWAP_DEAD, SWAP_FAILED)); if (detect_container() > 0) return -EPERM; /* If there's a job for another swap unit for the same node * running, then let's not dispatch this one for now, and wait * until that other job has finished. */ LIST_FOREACH_OTHERS(same_devnode, other, s) if (UNIT(other)->job && UNIT(other)->job->state == JOB_RUNNING) return -EAGAIN; r = unit_start_limit_test(u); if (r < 0) { swap_enter_dead(s, SWAP_FAILURE_START_LIMIT_HIT); return r; } r = unit_acquire_invocation_id(u); if (r < 0) return r; s->result = SWAP_SUCCESS; u->reset_accounting = true; swap_enter_activating(s); return 1; } static int swap_stop(Unit *u) { Swap *s = SWAP(u); assert(s); switch (s->state) { case SWAP_DEACTIVATING: case SWAP_DEACTIVATING_SIGTERM: case SWAP_DEACTIVATING_SIGKILL: /* Already on it */ return 0; case SWAP_ACTIVATING: case SWAP_ACTIVATING_DONE: /* There's a control process pending, directly enter kill mode */ swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_SUCCESS); return 0; case SWAP_ACTIVE: if (detect_container() > 0) return -EPERM; swap_enter_deactivating(s); return 1; default: assert_not_reached("Unexpected state."); } } static int swap_serialize(Unit *u, FILE *f, FDSet *fds) { Swap *s = SWAP(u); assert(s); assert(f); assert(fds); unit_serialize_item(u, f, "state", swap_state_to_string(s->state)); unit_serialize_item(u, f, "result", swap_result_to_string(s->result)); if (s->control_pid > 0) unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid); if (s->control_command_id >= 0) unit_serialize_item(u, f, "control-command", swap_exec_command_to_string(s->control_command_id)); return 0; } static int swap_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) { Swap *s = SWAP(u); assert(s); assert(fds); if (streq(key, "state")) { SwapState state; state = swap_state_from_string(value); if (state < 0) log_unit_debug(u, "Failed to parse state value: %s", value); else s->deserialized_state = state; } else if (streq(key, "result")) { SwapResult f; f = swap_result_from_string(value); if (f < 0) log_unit_debug(u, "Failed to parse result value: %s", value); else if (f != SWAP_SUCCESS) s->result = f; } else if (streq(key, "control-pid")) { pid_t pid; if (parse_pid(value, &pid) < 0) log_unit_debug(u, "Failed to parse control-pid value: %s", value); else s->control_pid = pid; } else if (streq(key, "control-command")) { SwapExecCommand id; id = swap_exec_command_from_string(value); if (id < 0) log_unit_debug(u, "Failed to parse exec-command value: %s", value); else { s->control_command_id = id; s->control_command = s->exec_command + id; } } else log_unit_debug(u, "Unknown serialization key: %s", key); return 0; } _pure_ static UnitActiveState swap_active_state(Unit *u) { assert(u); return state_translation_table[SWAP(u)->state]; } _pure_ static const char *swap_sub_state_to_string(Unit *u) { assert(u); return swap_state_to_string(SWAP(u)->state); } _pure_ static bool swap_check_gc(Unit *u) { Swap *s = SWAP(u); assert(s); return s->from_proc_swaps; } static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) { Swap *s = SWAP(u); SwapResult f; assert(s); assert(pid >= 0); if (pid != s->control_pid) return; s->control_pid = 0; if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL)) f = SWAP_SUCCESS; else if (code == CLD_EXITED) f = SWAP_FAILURE_EXIT_CODE; else if (code == CLD_KILLED) f = SWAP_FAILURE_SIGNAL; else if (code == CLD_DUMPED) f = SWAP_FAILURE_CORE_DUMP; else assert_not_reached("Unknown code"); if (s->result == SWAP_SUCCESS) s->result = f; if (s->control_command) { exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status); s->control_command = NULL; s->control_command_id = _SWAP_EXEC_COMMAND_INVALID; } log_unit_full(u, f == SWAP_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0, "Swap process exited, code=%s status=%i", sigchld_code_to_string(code), status); switch (s->state) { case SWAP_ACTIVATING: case SWAP_ACTIVATING_DONE: if (f == SWAP_SUCCESS || s->from_proc_swaps) swap_enter_active(s, f); else swap_enter_dead(s, f); break; case SWAP_DEACTIVATING: case SWAP_DEACTIVATING_SIGKILL: case SWAP_DEACTIVATING_SIGTERM: swap_enter_dead_or_active(s, f); break; default: assert_not_reached("Uh, control process died at wrong time."); } /* Notify clients about changed exit status */ unit_add_to_dbus_queue(u); } static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) { Swap *s = SWAP(userdata); assert(s); assert(s->timer_event_source == source); switch (s->state) { case SWAP_ACTIVATING: case SWAP_ACTIVATING_DONE: log_unit_warning(UNIT(s), "Activation timed out. Stopping."); swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT); break; case SWAP_DEACTIVATING: log_unit_warning(UNIT(s), "Deactivation timed out. Stopping."); swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT); break; case SWAP_DEACTIVATING_SIGTERM: if (s->kill_context.send_sigkill) { log_unit_warning(UNIT(s), "Swap process timed out. Killing."); swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT); } else { log_unit_warning(UNIT(s), "Swap process timed out. Skipping SIGKILL. Ignoring."); swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT); } break; case SWAP_DEACTIVATING_SIGKILL: log_unit_warning(UNIT(s), "Swap process still around after SIGKILL. Ignoring."); swap_enter_dead_or_active(s, SWAP_FAILURE_TIMEOUT); break; default: assert_not_reached("Timeout at wrong time."); } return 0; } static int swap_load_proc_swaps(Manager *m, bool set_flags) { unsigned i; int r = 0; assert(m); rewind(m->proc_swaps); (void) fscanf(m->proc_swaps, "%*s %*s %*s %*s %*s\n"); for (i = 1;; i++) { _cleanup_free_ char *dev = NULL, *d = NULL; int prio = 0, k; k = fscanf(m->proc_swaps, "%ms " /* device/file */ "%*s " /* type of swap */ "%*s " /* swap size */ "%*s " /* used */ "%i\n", /* priority */ &dev, &prio); if (k != 2) { if (k == EOF) break; log_warning("Failed to parse /proc/swaps:%u.", i); continue; } if (cunescape(dev, UNESCAPE_RELAX, &d) < 0) return log_oom(); device_found_node(m, d, true, DEVICE_FOUND_SWAP, set_flags); k = swap_process_new(m, d, prio, set_flags); if (k < 0) r = k; } return r; } static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) { Manager *m = userdata; Unit *u; int r; assert(m); assert(revents & EPOLLPRI); r = swap_load_proc_swaps(m, true); if (r < 0) { log_error_errno(r, "Failed to reread /proc/swaps: %m"); /* Reset flags, just in case, for late calls */ LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) { Swap *swap = SWAP(u); swap->is_active = swap->just_activated = false; } return 0; } manager_dispatch_load_queue(m); LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_SWAP]) { Swap *swap = SWAP(u); if (!swap->is_active) { /* This has just been deactivated */ swap_unset_proc_swaps(swap); switch (swap->state) { case SWAP_ACTIVE: swap_enter_dead(swap, SWAP_SUCCESS); break; default: /* Fire again */ swap_set_state(swap, swap->state); break; } if (swap->what) device_found_node(m, swap->what, false, DEVICE_FOUND_SWAP, true); } else if (swap->just_activated) { /* New swap entry */ switch (swap->state) { case SWAP_DEAD: case SWAP_FAILED: (void) unit_acquire_invocation_id(UNIT(swap)); swap_enter_active(swap, SWAP_SUCCESS); break; case SWAP_ACTIVATING: swap_set_state(swap, SWAP_ACTIVATING_DONE); break; default: /* Nothing really changed, but let's * issue an notification call * nonetheless, in case somebody is * waiting for this. */ swap_set_state(swap, swap->state); break; } } /* Reset the flags for later calls */ swap->is_active = swap->just_activated = false; } return 1; } static Unit *swap_following(Unit *u) { Swap *s = SWAP(u); Swap *other, *first = NULL; assert(s); /* If the user configured the swap through /etc/fstab or * a device unit, follow that. */ if (s->from_fragment) return NULL; LIST_FOREACH_OTHERS(same_devnode, other, s) if (other->from_fragment) return UNIT(other); /* Otherwise, make everybody follow the unit that's named after * the swap device in the kernel */ if (streq_ptr(s->what, s->devnode)) return NULL; LIST_FOREACH_AFTER(same_devnode, other, s) if (streq_ptr(other->what, other->devnode)) return UNIT(other); LIST_FOREACH_BEFORE(same_devnode, other, s) { if (streq_ptr(other->what, other->devnode)) return UNIT(other); first = other; } /* Fall back to the first on the list */ return UNIT(first); } static int swap_following_set(Unit *u, Set **_set) { Swap *s = SWAP(u), *other; Set *set; int r; assert(s); assert(_set); if (LIST_JUST_US(same_devnode, s)) { *_set = NULL; return 0; } set = set_new(NULL); if (!set) return -ENOMEM; LIST_FOREACH_OTHERS(same_devnode, other, s) { r = set_put(set, other); if (r < 0) goto fail; } *_set = set; return 1; fail: set_free(set); return r; } static void swap_shutdown(Manager *m) { assert(m); m->swap_event_source = sd_event_source_unref(m->swap_event_source); m->proc_swaps = safe_fclose(m->proc_swaps); m->swaps_by_devnode = hashmap_free(m->swaps_by_devnode); } static void swap_enumerate(Manager *m) { int r; assert(m); if (!m->proc_swaps) { m->proc_swaps = fopen("/proc/swaps", "re"); if (!m->proc_swaps) { if (errno == ENOENT) log_debug("Not swap enabled, skipping enumeration"); else log_error_errno(errno, "Failed to open /proc/swaps: %m"); return; } r = sd_event_add_io(m->event, &m->swap_event_source, fileno(m->proc_swaps), EPOLLPRI, swap_dispatch_io, m); if (r < 0) { log_error_errno(r, "Failed to watch /proc/swaps: %m"); goto fail; } /* Dispatch this before we dispatch SIGCHLD, so that * we always get the events from /proc/swaps before * the SIGCHLD of /sbin/swapon. */ r = sd_event_source_set_priority(m->swap_event_source, SD_EVENT_PRIORITY_NORMAL-10); if (r < 0) { log_error_errno(r, "Failed to change /proc/swaps priority: %m"); goto fail; } (void) sd_event_source_set_description(m->swap_event_source, "swap-proc"); } r = swap_load_proc_swaps(m, false); if (r < 0) goto fail; return; fail: swap_shutdown(m); } int swap_process_device_new(Manager *m, struct udev_device *dev) { struct udev_list_entry *item = NULL, *first = NULL; _cleanup_free_ char *e = NULL; const char *dn; Unit *u; int r = 0; assert(m); assert(dev); dn = udev_device_get_devnode(dev); if (!dn) return 0; r = unit_name_from_path(dn, ".swap", &e); if (r < 0) return r; u = manager_get_unit(m, e); if (u) r = swap_set_devnode(SWAP(u), dn); first = udev_device_get_devlinks_list_entry(dev); udev_list_entry_foreach(item, first) { _cleanup_free_ char *n = NULL; int q; q = unit_name_from_path(udev_list_entry_get_name(item), ".swap", &n); if (q < 0) return q; u = manager_get_unit(m, n); if (u) { q = swap_set_devnode(SWAP(u), dn); if (q < 0) r = q; } } return r; } int swap_process_device_remove(Manager *m, struct udev_device *dev) { const char *dn; int r = 0; Swap *s; dn = udev_device_get_devnode(dev); if (!dn) return 0; while ((s = hashmap_get(m->swaps_by_devnode, dn))) { int q; q = swap_set_devnode(s, NULL); if (q < 0) r = q; } return r; } static void swap_reset_failed(Unit *u) { Swap *s = SWAP(u); assert(s); if (s->state == SWAP_FAILED) swap_set_state(s, SWAP_DEAD); s->result = SWAP_SUCCESS; } static int swap_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) { return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error); } static int swap_get_timeout(Unit *u, usec_t *timeout) { Swap *s = SWAP(u); usec_t t; int r; if (!s->timer_event_source) return 0; r = sd_event_source_get_time(s->timer_event_source, &t); if (r < 0) return r; if (t == USEC_INFINITY) return 0; *timeout = t; return 1; } static bool swap_supported(void) { static int supported = -1; /* If swap support is not available in the kernel, or we are * running in a container we don't support swap units, and any * attempts to starting one should fail immediately. */ if (supported < 0) supported = access("/proc/swaps", F_OK) >= 0 && detect_container() <= 0; return supported; } static int swap_control_pid(Unit *u) { Swap *s = SWAP(u); assert(s); return s->control_pid; } static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = { [SWAP_EXEC_ACTIVATE] = "ExecActivate", [SWAP_EXEC_DEACTIVATE] = "ExecDeactivate", }; DEFINE_STRING_TABLE_LOOKUP(swap_exec_command, SwapExecCommand); static const char* const swap_result_table[_SWAP_RESULT_MAX] = { [SWAP_SUCCESS] = "success", [SWAP_FAILURE_RESOURCES] = "resources", [SWAP_FAILURE_TIMEOUT] = "timeout", [SWAP_FAILURE_EXIT_CODE] = "exit-code", [SWAP_FAILURE_SIGNAL] = "signal", [SWAP_FAILURE_CORE_DUMP] = "core-dump", [SWAP_FAILURE_START_LIMIT_HIT] = "start-limit-hit", }; DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult); const UnitVTable swap_vtable = { .object_size = sizeof(Swap), .exec_context_offset = offsetof(Swap, exec_context), .cgroup_context_offset = offsetof(Swap, cgroup_context), .kill_context_offset = offsetof(Swap, kill_context), .exec_runtime_offset = offsetof(Swap, exec_runtime), .dynamic_creds_offset = offsetof(Swap, dynamic_creds), .sections = "Unit\0" "Swap\0" "Install\0", .private_section = "Swap", .init = swap_init, .load = swap_load, .done = swap_done, .coldplug = swap_coldplug, .dump = swap_dump, .start = swap_start, .stop = swap_stop, .kill = swap_kill, .get_timeout = swap_get_timeout, .serialize = swap_serialize, .deserialize_item = swap_deserialize_item, .active_state = swap_active_state, .sub_state_to_string = swap_sub_state_to_string, .check_gc = swap_check_gc, .sigchld_event = swap_sigchld_event, .reset_failed = swap_reset_failed, .control_pid = swap_control_pid, .bus_vtable = bus_swap_vtable, .bus_set_property = bus_swap_set_property, .bus_commit_properties = bus_swap_commit_properties, .following = swap_following, .following_set = swap_following_set, .enumerate = swap_enumerate, .shutdown = swap_shutdown, .supported = swap_supported, .status_message_formats = { .starting_stopping = { [0] = "Activating swap %s...", [1] = "Deactivating swap %s...", }, .finished_start_job = { [JOB_DONE] = "Activated swap %s.", [JOB_FAILED] = "Failed to activate swap %s.", [JOB_TIMEOUT] = "Timed out activating swap %s.", }, .finished_stop_job = { [JOB_DONE] = "Deactivated swap %s.", [JOB_FAILED] = "Failed deactivating swap %s.", [JOB_TIMEOUT] = "Timed out deactivating swap %s.", }, }, };
neheb/systemd
src/core/swap.c
C
gpl-2.0
46,326
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="<?php gp_keywords(); ?>"> <meta name="keywords" content="<?php gp_keywords(); ?>" /> <meta name="description" itemprop="description" content="<?php gp_description(); ?>" /> <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/dist/css/main.css"/> <title><?php wp_title( '_', true, 'right' ); bloginfo( 'name' ); ?></title> </head> <body> <header class="head-s"> <div class="r"> <a href="/book_tag" class="l" title="搜索"><i class="icon-search"></i></a> <a href="/" class="l" title="首页"><i class="icon-home"></i></a> </div> <a href="/" class="l"><i class="icon-pre"></i></a> <h3>帮助文档</h3> </header> <div class="content"> <div class="help-box"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php the_content( __( '<p class="serif">Read the rest of this page &rarr;</p>', 'gampress' ) ); ?> <?php endwhile; endif; ?> </div> </div> <?php get_footer();?>
kuibobo/GamPress
wp-content/plugins/gampress-ext/themes/eBooks/page.php
PHP
gpl-2.0
1,338
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <title>8v18.GitHub.io by 8v18</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen"> <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen"> </head> <body> <section class="page-header"> <h1 class="project-name">8v18.GitHub.io</h1> <h2 class="project-tagline"></h2> </section> <section class="main-content"> <h3> <a id="welcome-to-github-pages" class="anchor" href="#welcome-to-github-pages" aria-hidden="true"><span class="octicon octicon-link"></span></a>Welcome to GitHub Pages.</h3> <p>This automatic page generator is the easiest way to create beautiful pages for all of your projects. Author your page content here <a href="https://guides.github.com/features/mastering-markdown/">using GitHub Flavored Markdown</a>, select a template crafted by a designer, and publish. After your page is generated, you can check out the new <code>gh-pages</code> branch locally. If you’re using GitHub Desktop, simply sync your repository and you’ll see the new branch.</p> <h3> <a id="designer-templates" class="anchor" href="#designer-templates" aria-hidden="true"><span class="octicon octicon-link"></span></a>Designer Templates</h3> <p>We’ve crafted some handsome templates for you to use. Go ahead and click 'Continue to layouts' to browse through them. You can easily go back to edit your page before publishing. After publishing your page, you can revisit the page generator and switch to another theme. Your Page content will be preserved.</p> <h3> <a id="creating-pages-manually" class="anchor" href="#creating-pages-manually" aria-hidden="true"><span class="octicon octicon-link"></span></a>Creating pages manually</h3> <p>If you prefer to not use the automatic generator, push a branch named <code>gh-pages</code> to your repository to create a page manually. In addition to supporting regular HTML content, GitHub Pages support Jekyll, a simple, blog aware static site generator. Jekyll makes it easy to create site-wide headers and footers without having to copy them across every page. It also offers intelligent blog support and other advanced templating features.</p> <h3> <a id="authors-and-contributors" class="anchor" href="#authors-and-contributors" aria-hidden="true"><span class="octicon octicon-link"></span></a>Authors and Contributors</h3> <p>You can <a href="https://github.com/blog/821" class="user-mention">@mention</a> a GitHub username to generate a link to their profile. The resulting <code>&lt;a&gt;</code> element will link to the contributor’s GitHub Profile. For example: In 2007, Chris Wanstrath (<a href="https://github.com/defunkt" class="user-mention">@defunkt</a>), PJ Hyett (<a href="https://github.com/pjhyett" class="user-mention">@pjhyett</a>), and Tom Preston-Werner (<a href="https://github.com/mojombo" class="user-mention">@mojombo</a>) founded GitHub.</p> <h3> <a id="support-or-contact" class="anchor" href="#support-or-contact" aria-hidden="true"><span class="octicon octicon-link"></span></a>Support or Contact</h3> <p>Having trouble with Pages? Check out our <a href="https://help.github.com/pages">documentation</a> or <a href="https://github.com/contact">contact support</a> and we’ll help you sort it out.</p> <footer class="site-footer"> <span class="site-footer-credits">This page was generated by <a href="https://pages.github.com">GitHub Pages</a> using the <a href="https://github.com/jasonlong/cayman-theme">Cayman theme</a> by <a href="https://twitter.com/jasonlong">Jason Long</a>.</span> </footer> </section> </body> </html>
8v18/8v18.github.io
index.html
HTML
gpl-2.0
4,003
<<<<<<< HEAD <p>The <strong>view type</strong> describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.</p> <dl> <dt><strong>Normal</strong></dt> <dd>Normal views are stored in your database and are completely local to your system.</dd> <dt><strong>Default</strong></dt> <dd>Default views are stored only in code and are not anywhere in your database. They may be <strong>enabled</strong> or <strong>disabled</strong> but you may not completely remove them from your system. You can <strong>override</strong> the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.</dd> <dt><strong>Overridden</strong></dt> <dd>Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you <strong>revert</strong> the view, the version in the database will be deleted, and the version that is in code will once again be used.</dd> </dl> You may store your views in code with the following procedure: <ol> <li> Create a module to store the views. </li> <li> Add the function <em>MODULENAME_views_default_views()</em> to this module. </li> <li> Export the view you wish to store in your module in code. Cut and paste that into the abovenamed function. Make sure the last line of the view is: <em>$views[$view-&gt;name] = $view;</em></li> <li> Make sure the last line of the function is <em>return $views;</em></li> <li> After you make any changes, be sure to <strong>clear the Views' cache</strong>. You may do this from the <strong>Tools</strong> menu.</li> </ol> ======= <p>The <strong>view type</strong> describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.</p> <dl> <dt><strong>Normal</strong></dt> <dd>Normal views are stored in your database and are completely local to your system.</dd> <dt><strong>Default</strong></dt> <dd>Default views are stored only in code and are not anywhere in your database. They may be <strong>enabled</strong> or <strong>disabled</strong> but you may not completely remove them from your system. You can <strong>override</strong> the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.</dd> <dt><strong>Overridden</strong></dt> <dd>Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you <strong>revert</strong> the view, the version in the database will be deleted, and the version that is in code will once again be used.</dd> </dl> You may store your views in code with the following procedure: <ol> <li> Create a module to store the views. </li> <li> Add the function <em>MODULENAME_views_default_views()</em> to this module. </li> <li> Export the view you wish to store in your module in code. Cut and paste that into the abovenamed function. Make sure the last line of the view is: <em>$views[$view-&gt;name] = $view;</em></li> <li> Make sure the last line of the function is <em>return $views;</em></li> <li> After you make any changes, be sure to <strong>clear the Views' cache</strong>. You may do this from the <strong>Tools</strong> menu.</li> </ol> >>>>>>> 6d2bfc44ff0188b46711530fc6441339db8d58cc
AbeerKhakwani/friday_asses_book_store
modules/views/help/view-type.html
HTML
gpl-2.0
3,724
/* * File: prg.c * Implements: parsing javascript program aggregate * * Copyright: Jens Låås, 2015 * Copyright license: According to GPL, see file COPYING in this directory. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include "duktape.h" #include "prg.h" static struct prg *prg_call; static struct native_mod *prg_native_modules; int prg_register(struct prg *prg, struct native_mod *native_modules) { prg_call = prg; prg_native_modules = native_modules; return 0; } struct mod *prg_storage_byname(const char *name) { struct mod *mod; for(mod = prg_call->modules; mod; mod=mod->next) { if(!strcmp(mod->fullname, name)) return mod; } return (void*)0; } struct mod *prg_storage_byid(int id) { struct mod *mod; for(mod = prg_call->modules; mod; mod=mod->next) { if(mod->id == id) return mod; } return (void*)0; } static struct mod *mod_new() { struct mod *m; m = malloc(sizeof(struct mod)); if(m) memset(m, 0, sizeof(struct mod)); return m; } int prg_wrapped_compile_execute(duk_context *ctx) { int ret; struct prg *prg = prg_call; duk_compile(ctx, 0); close(prg->fd); munmap(prg->buf, prg->size); duk_push_global_object(ctx); /* 'this' binding */ duk_call_method(ctx, 0); prg->status = duk_to_int(ctx, -1); duk_pop(ctx); // pop return value // Check if global property 'main' exists duk_push_global_object(ctx); ret = duk_get_prop_string(ctx, -1, "main"); duk_remove(ctx, -2); // remove global object // If main exists we call it if(ret && duk_get_type(ctx, -1) != DUK_TYPE_UNDEFINED) { int i; duk_push_global_object(ctx); /* 'this' binding */ for(i=1;i<prg->argc;i++) { duk_push_string(ctx, prg->argv[i]); } duk_call_method(ctx, prg->argc-1); prg->status = duk_to_int(ctx, -1); } duk_pop(ctx); return 0; // no values returned (0) } static int x(duk_context *ctx) { duk_push_string(ctx, "hello from x"); return 1; } static const duk_function_list_entry x_funcs[] = { { "x", x, 0 /* fd */ }, { NULL, NULL, 0 } }; /* Duktape.modSearch = function (id, require, exports, module) */ static int modSearch(duk_context *ctx) { struct mod *mod; struct prg *prg; int i; prg = prg_call; const char *id = duk_to_string(ctx, 0); /* * To support the native module case, the module search function can also return undefined * (or any non-string value), in which case Duktape will assume that the module was found * but has no Ecmascript source to execute. Symbols written to exports in the module search * function are the only symbols provided by the module. */ for(i=0;;i++) { if(!prg_native_modules[i].name) break; if(!strcmp(id, prg_native_modules[i].name)) { prg_native_modules[i].fn(ctx, 2, prg); duk_push_undefined(ctx); return 1; } } if(!strcmp(id, "x")) { duk_put_function_list(ctx, 2, x_funcs); duk_push_undefined(ctx); return 1; } /* * If a module is found, the module search function can return a string providing the source * code for the module. Duktape will then take care of compiling and executing the module code * so that module symbols get registered into the exports object. */ for(mod=prg->modules;mod;mod=mod->next) { if(!strcmp(mod->name, id)) { duk_push_lstring(ctx, mod->buf, mod->size); return 1; } } duk_error(ctx, DUK_ERR_ERROR, "failed to find module '%s'", id); return DUK_RET_ERROR; } int prg_push_modsearch(duk_context *ctx) { duk_get_prop_string(ctx, -1, "Duktape"); duk_push_c_function(ctx, modSearch, 4); duk_put_prop_string(ctx, -2, "modSearch"); duk_pop(ctx); // pop Duktape return 0; } int prg_parse_appfile(struct prg *prg) { char *p, *endp, *start, *m, *mainstart; off_t offset, pa_offset; struct mod *mod; int id = 1000; // read file prg->name prg->fd = open(prg->name, O_RDONLY); if(prg->fd == -1) { exit(1); } prg->size = lseek(prg->fd, 0, SEEK_END); prg->buf = mmap((void*)0, prg->size, PROT_READ, MAP_PRIVATE, prg->fd, 0); /* parse file header */ p = prg->buf; endp = prg->buf + prg->size; if(*p == '#') { while((p < endp) && (*p != '\n')) p++; if(p >= endp) { fprintf(stderr, "EOF\n"); exit(1); } p++; } mainstart = p; mod = mod_new(); mod->id = id++; for(start=p;p < endp;p++) { if(*p == '\n') { /* is this a module specification? */ for(m = start; *m == ' '; m++); if((*m >= '0') && (*m <= '9')) { mod->size = strtoul(m, &m, 10); if(!m) break; if(*m != ' ') break; m++; mod->name = strndup(m, p-m); mod->fullname = strdup(mod->name); if(!strcmp(mod->name, "total")) break; mod->next = prg->modules; prg->modules = mod; mod = mod_new(); mod->id = id++; } else break; start = p+1; } } offset = prg->size; for(mod = prg->modules; mod; mod=mod->next) { offset -= mod->size; pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1); mod->buf = mmap((void*)0, mod->size + offset - pa_offset, PROT_READ, MAP_PRIVATE, prg->fd, pa_offset); if(mod->buf == MAP_FAILED) { fprintf(stderr, "mmap failed\n"); exit(1); } mod->buf += (offset - pa_offset); } for(mod = prg->modules; mod; mod=mod->next) { char *p; if((p=strrchr(mod->name, '.'))) { if(!strcmp(p, ".js")) *p=0; } } for(mod = prg->modules; mod; mod=mod->next) { if(!strcmp(mod->name, "main")) { prg->main = mod; } else { char *p; if((p=strrchr(mod->name, '/'))) { if(!strcmp(p+1, "main")) { prg->main = mod; } } } } if(!prg->modules) { prg->main = mod_new(); prg->main->id = id++; prg->main->buf = mainstart; prg->main->size = prg->size - (mainstart - prg->buf); prg->main->name = "main"; prg->main->fullname = "main"; } if(!prg->main) { fprintf(stderr, "no main module\n"); exit(1); } return 0; } static int prg1_storage(duk_context *ctx) { const char *name = duk_to_string(ctx, 0); struct mod *mod; mod = prg_storage_byname(name); if(mod) { duk_push_object(ctx); duk_push_int(ctx, mod->id); duk_put_prop_string(ctx, -2, "id"); duk_push_int(ctx, mod->size); duk_put_prop_string(ctx, -2, "size"); duk_push_string(ctx, mod->name); duk_put_prop_string(ctx, -2, "name"); duk_push_string(ctx, mod->fullname); duk_put_prop_string(ctx, -2, "fullname"); } else { duk_push_undefined(ctx); } return 1; } static int prg1_storage_write(duk_context *ctx) { struct mod *mod; int rc = -1; int id, fd; size_t offset, len; fd = duk_to_int(ctx, 0); id = duk_to_int(ctx, 1); offset = duk_to_int(ctx, 2); len = duk_to_int(ctx, 3); mod = prg_storage_byid(id); if(mod) { rc = write(fd, mod->buf + offset, len); } duk_push_int(ctx, rc); return 1; } static int prg1_storage_buffer(duk_context *ctx) { struct mod *mod; int id; size_t offset, len; char *buf; id = duk_to_int(ctx, 0); offset = duk_to_int(ctx, 1); len = duk_to_int(ctx, 2); mod = prg_storage_byid(id); if(mod) { buf = duk_push_fixed_buffer(ctx, len); memcpy(buf, mod->buf + offset, len); } else { duk_push_undefined(ctx); } return 1; } static const duk_function_list_entry prg1_funcs[] = { { "storage", prg1_storage, 1 /* name */ }, { "storage_write", prg1_storage_write, 4 /* fd, id, offset, len */ }, { "storage_buffer", prg1_storage_buffer, 4 /* id, offset, len */ }, { NULL, NULL, 0 } }; static const duk_number_list_entry prg1_consts[] = { { NULL, 0.0 } }; int prg1_load(duk_context *ctx, int n, struct prg *prg) { duk_put_function_list(ctx, n, prg1_funcs); duk_put_number_list(ctx, n, prg1_consts); return 0; }
jelaas/sys
prg.c
C
gpl-2.0
7,575
/* * Intel XScale PXA Programmable Interrupt Controller. * * Copyright (c) 2006 Openedhand Ltd. * Copyright (c) 2006 Thorsten Zitterell * Written by Andrzej Zaborowski <[email protected]> * * This code is licenced under the GPL. */ #include "hw.h" #include "pxa.h" #define ICIP 0x00 /* Interrupt Controller IRQ Pending register */ #define ICMR 0x04 /* Interrupt Controller Mask register */ #define ICLR 0x08 /* Interrupt Controller Level register */ #define ICFP 0x0c /* Interrupt Controller FIQ Pending register */ #define ICPR 0x10 /* Interrupt Controller Pending register */ #define ICCR 0x14 /* Interrupt Controller Control register */ #define ICHP 0x18 /* Interrupt Controller Highest Priority register */ #define IPR0 0x1c /* Interrupt Controller Priority register 0 */ #define IPR31 0x98 /* Interrupt Controller Priority register 31 */ #define ICIP2 0x9c /* Interrupt Controller IRQ Pending register 2 */ #define ICMR2 0xa0 /* Interrupt Controller Mask register 2 */ #define ICLR2 0xa4 /* Interrupt Controller Level register 2 */ #define ICFP2 0xa8 /* Interrupt Controller FIQ Pending register 2 */ #define ICPR2 0xac /* Interrupt Controller Pending register 2 */ #define IPR32 0xb0 /* Interrupt Controller Priority register 32 */ #define IPR39 0xcc /* Interrupt Controller Priority register 39 */ #define PXA2XX_PIC_SRCS 40 typedef struct { CPUState *cpu_env; uint32_t int_enabled[2]; uint32_t int_pending[2]; uint32_t is_fiq[2]; uint32_t int_idle; uint32_t priority[PXA2XX_PIC_SRCS]; } PXA2xxPICState; static void pxa2xx_pic_update(void *opaque) { uint32_t mask[2]; PXA2xxPICState *s = (PXA2xxPICState *) opaque; if (s->cpu_env->halted) { mask[0] = s->int_pending[0] & (s->int_enabled[0] | s->int_idle); mask[1] = s->int_pending[1] & (s->int_enabled[1] | s->int_idle); if (mask[0] || mask[1]) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_EXITTB); } mask[0] = s->int_pending[0] & s->int_enabled[0]; mask[1] = s->int_pending[1] & s->int_enabled[1]; if ((mask[0] & s->is_fiq[0]) || (mask[1] & s->is_fiq[1])) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_FIQ); else cpu_reset_interrupt(s->cpu_env, CPU_INTERRUPT_FIQ); if ((mask[0] & ~s->is_fiq[0]) || (mask[1] & ~s->is_fiq[1])) cpu_interrupt(s->cpu_env, CPU_INTERRUPT_HARD); else cpu_reset_interrupt(s->cpu_env, CPU_INTERRUPT_HARD); } /* Note: Here level means state of the signal on a pin, not * IRQ/FIQ distinction as in PXA Developer Manual. */ static void pxa2xx_pic_set_irq(void *opaque, int irq, int level) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int int_set = (irq >= 32); irq &= 31; if (level) s->int_pending[int_set] |= 1 << irq; else s->int_pending[int_set] &= ~(1 << irq); pxa2xx_pic_update(opaque); } static inline uint32_t pxa2xx_pic_highest(PXA2xxPICState *s) { int i, int_set, irq; uint32_t bit, mask[2]; uint32_t ichp = 0x003f003f; /* Both IDs invalid */ mask[0] = s->int_pending[0] & s->int_enabled[0]; mask[1] = s->int_pending[1] & s->int_enabled[1]; for (i = PXA2XX_PIC_SRCS - 1; i >= 0; i --) { irq = s->priority[i] & 0x3f; if ((s->priority[i] & (1 << 31)) && irq < PXA2XX_PIC_SRCS) { /* Source peripheral ID is valid. */ bit = 1 << (irq & 31); int_set = (irq >= 32); if (mask[int_set] & bit & s->is_fiq[int_set]) { /* FIQ asserted */ ichp &= 0xffff0000; ichp |= (1 << 15) | irq; } if (mask[int_set] & bit & ~s->is_fiq[int_set]) { /* IRQ asserted */ ichp &= 0x0000ffff; ichp |= (1 << 31) | (irq << 16); } } } return ichp; } static uint32_t pxa2xx_pic_mem_read(void *opaque, target_phys_addr_t offset) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; switch (offset) { case ICIP: /* IRQ Pending register */ return s->int_pending[0] & ~s->is_fiq[0] & s->int_enabled[0]; case ICIP2: /* IRQ Pending register 2 */ return s->int_pending[1] & ~s->is_fiq[1] & s->int_enabled[1]; case ICMR: /* Mask register */ return s->int_enabled[0]; case ICMR2: /* Mask register 2 */ return s->int_enabled[1]; case ICLR: /* Level register */ return s->is_fiq[0]; case ICLR2: /* Level register 2 */ return s->is_fiq[1]; case ICCR: /* Idle mask */ return (s->int_idle == 0); case ICFP: /* FIQ Pending register */ return s->int_pending[0] & s->is_fiq[0] & s->int_enabled[0]; case ICFP2: /* FIQ Pending register 2 */ return s->int_pending[1] & s->is_fiq[1] & s->int_enabled[1]; case ICPR: /* Pending register */ return s->int_pending[0]; case ICPR2: /* Pending register 2 */ return s->int_pending[1]; case IPR0 ... IPR31: return s->priority[0 + ((offset - IPR0 ) >> 2)]; case IPR32 ... IPR39: return s->priority[32 + ((offset - IPR32) >> 2)]; case ICHP: /* Highest Priority register */ return pxa2xx_pic_highest(s); default: printf("%s: Bad register offset " REG_FMT "\n", __FUNCTION__, offset); return 0; } } static void pxa2xx_pic_mem_write(void *opaque, target_phys_addr_t offset, uint32_t value) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; switch (offset) { case ICMR: /* Mask register */ s->int_enabled[0] = value; break; case ICMR2: /* Mask register 2 */ s->int_enabled[1] = value; break; case ICLR: /* Level register */ s->is_fiq[0] = value; break; case ICLR2: /* Level register 2 */ s->is_fiq[1] = value; break; case ICCR: /* Idle mask */ s->int_idle = (value & 1) ? 0 : ~0; break; case IPR0 ... IPR31: s->priority[0 + ((offset - IPR0 ) >> 2)] = value & 0x8000003f; break; case IPR32 ... IPR39: s->priority[32 + ((offset - IPR32) >> 2)] = value & 0x8000003f; break; default: printf("%s: Bad register offset " REG_FMT "\n", __FUNCTION__, offset); return; } pxa2xx_pic_update(opaque); } /* Interrupt Controller Coprocessor Space Register Mapping */ static const int pxa2xx_cp_reg_map[0x10] = { [0x0 ... 0xf] = -1, [0x0] = ICIP, [0x1] = ICMR, [0x2] = ICLR, [0x3] = ICFP, [0x4] = ICPR, [0x5] = ICHP, [0x6] = ICIP2, [0x7] = ICMR2, [0x8] = ICLR2, [0x9] = ICFP2, [0xa] = ICPR2, }; static uint32_t pxa2xx_pic_cp_read(void *opaque, int op2, int reg, int crm, void *retaddr) { target_phys_addr_t offset; if (pxa2xx_cp_reg_map[reg] == -1) { printf("%s: Bad register 0x%x\n", __FUNCTION__, reg); return 0; } offset = pxa2xx_cp_reg_map[reg]; return pxa2xx_pic_mem_read(opaque, offset); } static void pxa2xx_pic_cp_write(void *opaque, int op2, int reg, int crm, uint32_t value, void *retaddr) { target_phys_addr_t offset; if (pxa2xx_cp_reg_map[reg] == -1) { printf("%s: Bad register 0x%x\n", __FUNCTION__, reg); return; } offset = pxa2xx_cp_reg_map[reg]; pxa2xx_pic_mem_write(opaque, offset, value); } static CPUReadMemoryFunc * const pxa2xx_pic_readfn[] = { pxa2xx_pic_mem_read, pxa2xx_pic_mem_read, pxa2xx_pic_mem_read, }; static CPUWriteMemoryFunc * const pxa2xx_pic_writefn[] = { pxa2xx_pic_mem_write, pxa2xx_pic_mem_write, pxa2xx_pic_mem_write, }; static void pxa2xx_pic_save(QEMUFile *f, void *opaque) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int i; for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->int_enabled[i]); for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->int_pending[i]); for (i = 0; i < 2; i ++) qemu_put_be32s(f, &s->is_fiq[i]); qemu_put_be32s(f, &s->int_idle); for (i = 0; i < PXA2XX_PIC_SRCS; i ++) qemu_put_be32s(f, &s->priority[i]); } static int pxa2xx_pic_load(QEMUFile *f, void *opaque, int version_id) { PXA2xxPICState *s = (PXA2xxPICState *) opaque; int i; for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->int_enabled[i]); for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->int_pending[i]); for (i = 0; i < 2; i ++) qemu_get_be32s(f, &s->is_fiq[i]); qemu_get_be32s(f, &s->int_idle); for (i = 0; i < PXA2XX_PIC_SRCS; i ++) qemu_get_be32s(f, &s->priority[i]); pxa2xx_pic_update(opaque); return 0; } qemu_irq *pxa2xx_pic_init(target_phys_addr_t base, CPUState *env) { PXA2xxPICState *s; int iomemtype; qemu_irq *qi; s = (PXA2xxPICState *) qemu_mallocz(sizeof(PXA2xxPICState)); if (!s) return NULL; s->cpu_env = env; s->int_pending[0] = 0; s->int_pending[1] = 0; s->int_enabled[0] = 0; s->int_enabled[1] = 0; s->is_fiq[0] = 0; s->is_fiq[1] = 0; qi = qemu_allocate_irqs(pxa2xx_pic_set_irq, s, PXA2XX_PIC_SRCS); /* Enable IC memory-mapped registers access. */ iomemtype = cpu_register_io_memory(pxa2xx_pic_readfn, pxa2xx_pic_writefn, s, DEVICE_NATIVE_ENDIAN); cpu_register_physical_memory(base, 0x00100000, iomemtype); /* Enable IC coprocessor access. */ cpu_arm_set_cp_io(env, 6, pxa2xx_pic_cp_read, pxa2xx_pic_cp_write, s); register_savevm(NULL, "pxa2xx_pic", 0, 0, pxa2xx_pic_save, pxa2xx_pic_load, s); return qi; }
XVilka/qemu
hw/pxa2xx_pic.c
C
gpl-2.0
9,607
#include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/jiffies.h> #include <asm/system.h> #include <asm/io.h> #include <asm/setup.h> #include <asm/amigaints.h> #include <asm/amigahw.h> #include <asm/amigayle.h> #include <asm/amipcmcia.h> #include "8390.h" #define DRV_NAME "apne" #define NE_BASE (dev->base_addr) #define NE_CMD 0x00 #define NE_DATAPORT 0x10 #define NE_RESET 0x1f #define NE_IO_EXTENT 0x20 #define NE_EN0_ISR 0x07 #define NE_EN0_DCFG 0x0e #define NE_EN0_RSARLO 0x08 #define NE_EN0_RSARHI 0x09 #define NE_EN0_RCNTLO 0x0a #define NE_EN0_RXCR 0x0c #define NE_EN0_TXCR 0x0d #define NE_EN0_RCNTHI 0x0b #define NE_EN0_IMR 0x0f #define NE1SM_START_PG 0x20 #define NE1SM_STOP_PG 0x40 #define NESM_START_PG 0x40 #define NESM_STOP_PG 0x80 struct net_device * __init apne_probe(int unit); static int apne_probe1(struct net_device *dev, int ioaddr); static void apne_reset_8390(struct net_device *dev); static void apne_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page); static void apne_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset); static void apne_block_output(struct net_device *dev, const int count, const unsigned char *buf, const int start_page); static irqreturn_t apne_interrupt(int irq, void *dev_id); static int init_pcmcia(void); #define IOBASE 0x300 static const char version[] = "apne.c:v1.1 7/10/98 Alain Malek ([email protected])\n"; static int apne_owned; struct net_device * __init apne_probe(int unit) { struct net_device *dev; #ifndef MANUAL_CONFIG char tuple[8]; #endif int err; if (!MACH_IS_AMIGA) return ERR_PTR(-ENODEV); if (apne_owned) return ERR_PTR(-ENODEV); if ( !(AMIGAHW_PRESENT(PCMCIA)) ) return ERR_PTR(-ENODEV); printk("Looking for PCMCIA ethernet card : "); if (!(PCMCIA_INSERTED)) { printk("NO PCMCIA card inserted\n"); return ERR_PTR(-ENODEV); } dev = alloc_ei_netdev(); if (!dev) return ERR_PTR(-ENOMEM); if (unit >= 0) { sprintf(dev->name, "eth%d", unit); netdev_boot_setup_check(dev); } pcmcia_disable_irq(); #ifndef MANUAL_CONFIG if ((pcmcia_copy_tuple(CISTPL_FUNCID, tuple, 8) < 3) || (tuple[2] != CISTPL_FUNCID_NETWORK)) { printk("not an ethernet card\n"); free_netdev(dev); return ERR_PTR(-ENODEV); } #endif printk("ethernet PCMCIA card inserted\n"); if (!init_pcmcia()) { free_netdev(dev); return ERR_PTR(-ENODEV); } if (!request_region(IOBASE, 0x20, DRV_NAME)) { free_netdev(dev); return ERR_PTR(-EBUSY); } err = apne_probe1(dev, IOBASE); if (err) { release_region(IOBASE, 0x20); free_netdev(dev); return ERR_PTR(err); } err = register_netdev(dev); if (!err) return dev; pcmcia_disable_irq(); free_irq(IRQ_AMIGA_PORTS, dev); pcmcia_reset(); release_region(IOBASE, 0x20); free_netdev(dev); return ERR_PTR(err); } static int __init apne_probe1(struct net_device *dev, int ioaddr) { int i; unsigned char SA_prom[32]; int wordlength = 2; const char *name = NULL; int start_page, stop_page; #ifndef MANUAL_HWADDR0 int neX000, ctron; #endif static unsigned version_printed; if (ei_debug && version_printed++ == 0) printk(version); printk("PCMCIA NE*000 ethercard probe"); { unsigned long reset_start_time = jiffies; outb(inb(ioaddr + NE_RESET), ioaddr + NE_RESET); while ((inb(ioaddr + NE_EN0_ISR) & ENISR_RESET) == 0) if (time_after(jiffies, reset_start_time + 2*HZ/100)) { printk(" not found (no reset ack).\n"); return -ENODEV; } outb(0xff, ioaddr + NE_EN0_ISR); } #ifndef MANUAL_HWADDR0 { struct {unsigned long value, offset; } program_seq[] = { {E8390_NODMA+E8390_PAGE0+E8390_STOP, NE_CMD}, {0x48, NE_EN0_DCFG}, {0x00, NE_EN0_RCNTLO}, {0x00, NE_EN0_RCNTHI}, {0x00, NE_EN0_IMR}, {0xFF, NE_EN0_ISR}, {E8390_RXOFF, NE_EN0_RXCR}, {E8390_TXOFF, NE_EN0_TXCR}, {32, NE_EN0_RCNTLO}, {0x00, NE_EN0_RCNTHI}, {0x00, NE_EN0_RSARLO}, {0x00, NE_EN0_RSARHI}, {E8390_RREAD+E8390_START, NE_CMD}, }; for (i = 0; i < ARRAY_SIZE(program_seq); i++) { outb(program_seq[i].value, ioaddr + program_seq[i].offset); } } for(i = 0; i < 32 ; i+=2) { SA_prom[i] = inb(ioaddr + NE_DATAPORT); SA_prom[i+1] = inb(ioaddr + NE_DATAPORT); if (SA_prom[i] != SA_prom[i+1]) wordlength = 1; } if (wordlength == 2) for (i = 0; i < 16; i++) SA_prom[i] = SA_prom[i+i]; if (wordlength == 2) { outb(0x49, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; } else { start_page = NE1SM_START_PG; stop_page = NE1SM_STOP_PG; } neX000 = (SA_prom[14] == 0x57 && SA_prom[15] == 0x57); ctron = (SA_prom[0] == 0x00 && SA_prom[1] == 0x00 && SA_prom[2] == 0x1d); if (neX000) { name = (wordlength == 2) ? "NE2000" : "NE1000"; } else if (ctron) { name = (wordlength == 2) ? "Ctron-8" : "Ctron-16"; start_page = 0x01; stop_page = (wordlength == 2) ? 0x40 : 0x20; } else { printk(" not found.\n"); return -ENXIO; } #else wordlength = 2; outb(0x49, ioaddr + NE_EN0_DCFG); start_page = NESM_START_PG; stop_page = NESM_STOP_PG; SA_prom[0] = MANUAL_HWADDR0; SA_prom[1] = MANUAL_HWADDR1; SA_prom[2] = MANUAL_HWADDR2; SA_prom[3] = MANUAL_HWADDR3; SA_prom[4] = MANUAL_HWADDR4; SA_prom[5] = MANUAL_HWADDR5; name = "NE2000"; #endif dev->base_addr = ioaddr; dev->irq = IRQ_AMIGA_PORTS; dev->netdev_ops = &ei_netdev_ops; i = request_irq(dev->irq, apne_interrupt, IRQF_SHARED, DRV_NAME, dev); if (i) return i; for(i = 0; i < ETHER_ADDR_LEN; i++) dev->dev_addr[i] = SA_prom[i]; printk(" %pM\n", dev->dev_addr); printk("%s: %s found.\n", dev->name, name); ei_status.name = name; ei_status.tx_start_page = start_page; ei_status.stop_page = stop_page; ei_status.word16 = (wordlength == 2); ei_status.rx_start_page = start_page + TX_PAGES; ei_status.reset_8390 = &apne_reset_8390; ei_status.block_input = &apne_block_input; ei_status.block_output = &apne_block_output; ei_status.get_8390_hdr = &apne_get_8390_hdr; NS8390_init(dev, 0); pcmcia_ack_int(pcmcia_get_intreq()); pcmcia_enable_irq(); apne_owned = 1; return 0; } static void apne_reset_8390(struct net_device *dev) { unsigned long reset_start_time = jiffies; init_pcmcia(); if (ei_debug > 1) printk("resetting the 8390 t=%ld...", jiffies); outb(inb(NE_BASE + NE_RESET), NE_BASE + NE_RESET); ei_status.txing = 0; ei_status.dmaing = 0; while ((inb(NE_BASE+NE_EN0_ISR) & ENISR_RESET) == 0) if (time_after(jiffies, reset_start_time + 2*HZ/100)) { printk("%s: ne_reset_8390() did not complete.\n", dev->name); break; } outb(ENISR_RESET, NE_BASE + NE_EN0_ISR); } static void apne_get_8390_hdr(struct net_device *dev, struct e8390_pkt_hdr *hdr, int ring_page) { int nic_base = dev->base_addr; int cnt; char *ptrc; short *ptrs; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_get_8390_hdr " "[DMAstat:%d][irqlock:%d][intr:%d].\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(sizeof(struct e8390_pkt_hdr), nic_base + NE_EN0_RCNTLO); outb(0, nic_base + NE_EN0_RCNTHI); outb(0, nic_base + NE_EN0_RSARLO); outb(ring_page, nic_base + NE_EN0_RSARHI); outb(E8390_RREAD+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)hdr; for(cnt = 0; cnt < (sizeof(struct e8390_pkt_hdr)>>1); cnt++) *ptrs++ = inw(NE_BASE + NE_DATAPORT); } else { ptrc = (char*)hdr; for(cnt = 0; cnt < sizeof(struct e8390_pkt_hdr); cnt++) *ptrc++ = inb(NE_BASE + NE_DATAPORT); } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; le16_to_cpus(&hdr->count); } static void apne_block_input(struct net_device *dev, int count, struct sk_buff *skb, int ring_offset) { int nic_base = dev->base_addr; char *buf = skb->data; char *ptrc; short *ptrs; int cnt; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_block_input " "[DMAstat:%d][irqlock:%d][intr:%d].\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_NODMA+E8390_PAGE0+E8390_START, nic_base+ NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(count & 0xff, nic_base + NE_EN0_RCNTLO); outb(count >> 8, nic_base + NE_EN0_RCNTHI); outb(ring_offset & 0xff, nic_base + NE_EN0_RSARLO); outb(ring_offset >> 8, nic_base + NE_EN0_RSARHI); outb(E8390_RREAD+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)buf; for (cnt = 0; cnt < (count>>1); cnt++) *ptrs++ = inw(NE_BASE + NE_DATAPORT); if (count & 0x01) { buf[count-1] = inb(NE_BASE + NE_DATAPORT); } } else { ptrc = (char*)buf; for (cnt = 0; cnt < count; cnt++) *ptrc++ = inb(NE_BASE + NE_DATAPORT); } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; } static void apne_block_output(struct net_device *dev, int count, const unsigned char *buf, const int start_page) { int nic_base = NE_BASE; unsigned long dma_start; char *ptrc; short *ptrs; int cnt; if (ei_status.word16 && (count & 0x01)) count++; if (ei_status.dmaing) { printk("%s: DMAing conflict in ne_block_output." "[DMAstat:%d][irqlock:%d][intr:%d]\n", dev->name, ei_status.dmaing, ei_status.irqlock, dev->irq); return; } ei_status.dmaing |= 0x01; outb(E8390_PAGE0+E8390_START+E8390_NODMA, nic_base + NE_CMD); outb(ENISR_RDC, nic_base + NE_EN0_ISR); outb(count & 0xff, nic_base + NE_EN0_RCNTLO); outb(count >> 8, nic_base + NE_EN0_RCNTHI); outb(0x00, nic_base + NE_EN0_RSARLO); outb(start_page, nic_base + NE_EN0_RSARHI); outb(E8390_RWRITE+E8390_START, nic_base + NE_CMD); if (ei_status.word16) { ptrs = (short*)buf; for (cnt = 0; cnt < count>>1; cnt++) outw(*ptrs++, NE_BASE+NE_DATAPORT); } else { ptrc = (char*)buf; for (cnt = 0; cnt < count; cnt++) outb(*ptrc++, NE_BASE + NE_DATAPORT); } dma_start = jiffies; while ((inb(NE_BASE + NE_EN0_ISR) & ENISR_RDC) == 0) if (time_after(jiffies, dma_start + 2*HZ/100)) { printk("%s: timeout waiting for Tx RDC.\n", dev->name); apne_reset_8390(dev); NS8390_init(dev,1); break; } outb(ENISR_RDC, nic_base + NE_EN0_ISR); ei_status.dmaing &= ~0x01; return; } static irqreturn_t apne_interrupt(int irq, void *dev_id) { unsigned char pcmcia_intreq; if (!(gayle.inten & GAYLE_IRQ_IRQ)) return IRQ_NONE; pcmcia_intreq = pcmcia_get_intreq(); if (!(pcmcia_intreq & GAYLE_IRQ_IRQ)) { pcmcia_ack_int(pcmcia_intreq); return IRQ_NONE; } if (ei_debug > 3) printk("pcmcia intreq = %x\n", pcmcia_intreq); pcmcia_disable_irq(); ei_interrupt(irq, dev_id); pcmcia_ack_int(pcmcia_get_intreq()); pcmcia_enable_irq(); return IRQ_HANDLED; } #ifdef MODULE static struct net_device *apne_dev; static int __init apne_module_init(void) { apne_dev = apne_probe(-1); if (IS_ERR(apne_dev)) return PTR_ERR(apne_dev); return 0; } static void __exit apne_module_exit(void) { unregister_netdev(apne_dev); pcmcia_disable_irq(); free_irq(IRQ_AMIGA_PORTS, apne_dev); pcmcia_reset(); release_region(IOBASE, 0x20); free_netdev(apne_dev); } module_init(apne_module_init); module_exit(apne_module_exit); #endif static int init_pcmcia(void) { u_char config; #ifndef MANUAL_CONFIG u_char tuple[32]; int offset_len; #endif u_long offset; pcmcia_reset(); pcmcia_program_voltage(PCMCIA_0V); pcmcia_access_speed(PCMCIA_SPEED_250NS); pcmcia_write_enable(); #ifdef MANUAL_CONFIG config = MANUAL_CONFIG; #else if (pcmcia_copy_tuple(CISTPL_CFTABLE_ENTRY, tuple, 32) < 3) return 0; config = tuple[2] & 0x3f; #endif #ifdef MANUAL_OFFSET offset = MANUAL_OFFSET; #else if (pcmcia_copy_tuple(CISTPL_CONFIG, tuple, 32) < 6) return 0; offset_len = (tuple[2] & 0x3) + 1; offset = 0; while(offset_len--) { offset = (offset << 8) | tuple[4+offset_len]; } #endif out_8(GAYLE_ATTRIBUTE+offset, config); return 1; } MODULE_LICENSE("GPL");
leemgs/OptimusOneKernel-KandroidCommunity
drivers/net/apne.c
C
gpl-2.0
12,904
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Curate ♫ | Prototype</title> <link rel="stylesheet" href="curate.css"> <script src="script.js"></script> </head> <body> <!-- First Page --> <div> <h1>Canvas 1 - Intro Animations <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <img src="assets/logo.png" alt=""> <img src="assets/bg1.png" alt=""> <div> <img src="assets/albums1.png" alt=""> <img src="assets/albums2.png" alt=""> </div> <aside> <p>Feel like savoring <br> these dishes, fam? &UpperRightArrow; </p> <br> <hr> <div></div> <br> <br> <img src="assets/icon.png" alt=""> <p>"you got flavor, boi"</p> </aside> </main> </section> </div> <!-- Second Page --> <div> <h1>Canvas 2 - Bot Function <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <img src="assets/logo.png" alt=""> <aside> <p>Forget Kansas yet?<br> Here's Portugal in an <br> acoustic nutshell &LowerRightArrow; </p> <img src="assets/icon.png" alt=""> <br> <hr> <div></div> <p>start speaking or type</p> <p>"I miss home, toto."</p> <p>Alright, here's what's <br> lit back in Topeka. &LowerRightArrow;</p> </aside> <img src="assets/suggestion.png" alt=""> <img src="assets/new_suggestion_albums.png" alt=""> <img src="assets/new_suggestion_bg.png" alt=""> </main> <img src="assets/keyboard.png" alt=""> </section> </div> <!-- Third Page --> <div> <h1>Canvas 3 - Navigation <br> Hit Refresh for Animation Replay.</h1> <section> <header> <img src="http://lorinsteel.com/blog/wp-content/uploads/2014/11/iOS-8-Status-Bar-01.png" alt="iOS 8 Status Bar"> </header> <main> <aside> <p>“ You might fall in love with pop duo Nuremburg’s silky synths -- a velvety vocal debut. ”</p> <p>- Variety, 2016</p> <img src="assets/icon.png" alt=""> </aside> <img src="assets/logo.png" alt=""> <img src="assets/album_bg.png" alt=""> <img src="assets/album_nav.png" alt=""> </main> <main> <img src="assets/player.png" alt=""> <img src="assets/waveform.png" alt=""> <img src="assets/player_bg.png" alt=""> <img src="assets/player_suggest.png" alt=""> </main> <main> <img src="assets/suggestion_bot.png" alt=""> <img src="assets/suggestion_album.png" alt=""> </main> </section> </div> </body> </html>
aiyadurai/webd-adventures
Capstone/Prototypes/UX:Animation Prototype/index.html
HTML
gpl-2.0
2,941
<?php class departamento extends controller { public function __construct() { parent::__construct(); include 'controllers/loginController.php'; $valida = new login(); $valida->sessao_valida(); } public function index_action($pagina = 1) { //list all records $_SESSION['pagina'] = $pagina; $this->smarty->assign('paginador', $this->mostraGrid()); $this->smarty->assign('title', 'Departamento'); //call the smarty $this->smarty->display('departamento/index.tpl'); } public function add() { $this->smarty->assign('title', 'Novo Departamento'); $this->smarty->display('departamento/new.tpl'); } public function save() { $modeldepartamento = new departamentoModel(); $dados['departamento'] = $_POST['name']; //$dados['created'] = date("Y-m-d H:i:s"); //$dados['active'] = 1; $modeldepartamento->setDepartamento($dados); header('Location: /departamento'); } public function update() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $dados['codigo'] = $id; $dados['departamento'] = $_POST['name']; $modeldepartamento->updDepartamento($dados); header('Location: /departamento'); } public function detalhes() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id); $this->smarty->assign('registro', $resdepartamento[0]); $this->smarty->assign('title', 'Detalhes do Departamento'); //call the smarty $this->smarty->display('departamento/detail.tpl'); } public function edit() { //die(); $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $resdepartamento = $modeldepartamento->getDepartamento('codigo=' . $id); $this->smarty->assign('registro', $resdepartamento[0]); $this->smarty->assign('title', 'Editar Departamento'); //call the smarty $this->smarty->display('departamento/edit.tpl'); } public function delete() { $id = $this->getParam('id'); $modeldepartamento = new departamentoModel(); $dados['codigo'] = $id; $modeldepartamento->delDepartamento($dados); header('Location: /departamento'); } public function mostraGrid(){ $total_reg = "10"; // número de registros por página $pagina = $_SESSION['pagina']; if (!$pagina) { $pc = "1"; } else { $pc = $pagina; } $inicio = $pc - 1; $inicio = $inicio * $total_reg; //list all records $model_departamentos = new departamentoModel(); $departamentos_res = $model_departamentos->getDepartamentoLimit(null,$inicio,$total_reg); //Full table Scan :( or :) //send the records to template sytem $this->smarty->assign('listdepartamento', $departamentos_res); $query_total = $model_departamentos->getCountDepartamento(); $total_registros = $query_total[0]['total']; //pega o valor $html = $this->paginador($pc, $total_registros, 'departamento'); return $html; } public function paginacao() { $this->index_action($this->getParam('pagina')); } } ?>
suspecie/controle-eventos-php-thepowerpuffgirls
controllers/departamentoController.php
PHP
gpl-2.0
3,526
Webspark FeaturesCustom ============ A collection of features compiled specifically for the Webspark distro of Panopoly. This includes: ASU GSA - Google Search Appliance ASU Maps Enhanced ASU Security Scan Fixes Various Fieldable Panel Pane Elements: ASU Spotlight Webspark Banner Webspark Hero Webspark Jumbohero Webspark Content Callout Webspark Extras Webspark feeds content: Webspark News & Events Webspark Page Elements: Webspark Breadcrumbs Mega Footer Mega Footer Menu Webspark Megamenu Webspark Panels Styles Webspark WYSIWYG settings
bjdevil21/d7testrepo
profiles/openasu/modules/custom/webspark_featurescustom/README.md
Markdown
gpl-2.0
585
<?php // $Id: oci8po.class.php 68 2009-07-31 18:23:01Z dlandau $ /////////////////////////////////////////////////////////////////////////// // // // NOTICE OF COPYRIGHT // // // // Moodle - Modular Object-Oriented Dynamic Learning Environment // // http://moodle.com // // // // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // // (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details: // // // // http://www.gnu.org/copyleft/gpl.html // // // /////////////////////////////////////////////////////////////////////////// /// This class generate SQL code to be used against Oracle /// It extends XMLDBgenerator so everything can be /// overriden as needed to generate correct SQL. class XMLDBoci8po extends XMLDBgenerator { /// Only set values that are different from the defaults present in XMLDBgenerator var $statement_end = "\n/"; // String to be automatically added at the end of each statement // Using "/" because the standard ";" isn't good for stored procedures (triggers) var $number_type = 'NUMBER'; // Proper type for NUMBER(x) in this DB var $unsigned_allowed = false; // To define in the generator must handle unsigned information var $default_for_char = ' '; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) // Using this whitespace here because Oracle doesn't distinguish empty and null! :-( var $drop_default_clause_required = true; //To specify if the generator must use some DEFAULT clause to drop defaults var $drop_default_clause = 'NULL'; //The DEFAULT clause required to drop defaults var $default_after_null = false; //To decide if the default clause of each field must go after the null clause var $sequence_extra_code = true; //Does the generator need to add extra code to generate the sequence fields var $sequence_name = ''; //Particular name for inline sequences in this generator var $drop_table_extra_code = true; //Does the generator need to add code after table drop var $rename_table_extra_code = true; //Does the generator need to add code after table rename var $rename_column_extra_code = true; //Does the generator need to add code after field rename var $enum_inline_code = false; //Does the generator need to add inline code in the column definition var $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)'; //The SQL template to alter columns /** * Creates one new XMLDBoci8po */ function XMLDBoci8po() { parent::XMLDBgenerator(); $this->prefix = ''; $this->reserved_words = $this->getReservedWords(); } /** * Given one XMLDB Type, lenght and decimals, returns the DB proper SQL type */ function getTypeSQL ($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { switch ($xmldb_type) { case XMLDB_TYPE_INTEGER: // From http://www.postgresql.org/docs/7.4/interactive/datatype.html if (empty($xmldb_length)) { $xmldb_length = 10; } $dbtype = 'NUMBER(' . $xmldb_length . ')'; break; case XMLDB_TYPE_NUMBER: $dbtype = $this->number_type; /// 38 is the max allowed if ($xmldb_length > 38) { $xmldb_length = 38; } if (!empty($xmldb_length)) { $dbtype .= '(' . $xmldb_length; if (!empty($xmldb_decimals)) { $dbtype .= ',' . $xmldb_decimals; } $dbtype .= ')'; } break; case XMLDB_TYPE_FLOAT: $dbtype = 'NUMBER'; break; case XMLDB_TYPE_CHAR: $dbtype = 'VARCHAR2'; if (empty($xmldb_length)) { $xmldb_length='255'; } $dbtype .= '(' . $xmldb_length . ')'; break; case XMLDB_TYPE_TEXT: $dbtype = 'CLOB'; break; case XMLDB_TYPE_BINARY: $dbtype = 'BLOB'; break; case XMLDB_TYPE_DATETIME: $dbtype = 'DATE'; break; } return $dbtype; } /** * Returns the code needed to create one enum for the xmldb_table and xmldb_field passes */ function getEnumExtraSQL ($xmldb_table, $xmldb_field) { $sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck'); $sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))'; return $sql; } /** * Returns the code needed to create one sequence for the xmldb_table and xmldb_field passes */ function getCreateSequenceSQL ($xmldb_table, $xmldb_field) { $results = array(); $sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq'); $sequence = "CREATE SEQUENCE " . $sequence_name; $sequence.= "\n START WITH 1"; $sequence.= "\n INCREMENT BY 1"; $sequence.= "\n NOMAXVALUE"; $results[] = $sequence; $results = array_merge($results, $this->getCreateTriggerSQL ($xmldb_table, $xmldb_field)); return $results; } /** * Returns the code needed to create one trigger for the xmldb_table and xmldb_field passed */ function getCreateTriggerSQL ($xmldb_table, $xmldb_field) { $trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg'); $sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq'); $trigger = "CREATE TRIGGER " . $trigger_name; $trigger.= "\n BEFORE INSERT"; $trigger.= "\nON " . $this->getTableName($xmldb_table); $trigger.= "\n FOR EACH ROW"; $trigger.= "\nBEGIN"; $trigger.= "\n IF :new." . $this->getEncQuoted($xmldb_field->getName()) . ' IS NULL THEN'; $trigger.= "\n SELECT " . $sequence_name . '.nextval INTO :new.' . $this->getEncQuoted($xmldb_field->getName()) . " FROM dual;"; $trigger.= "\n END IF;"; $trigger.= "\nEND;"; return array($trigger); } /** * Returns the code needed to drop one sequence for the xmldb_table and xmldb_field passed * Can, optionally, specify if the underlying trigger will be also dropped */ function getDropSequenceSQL ($xmldb_table, $xmldb_field, $include_trigger=false) { $sequence_name = $this->getSequenceFromDB($xmldb_table); $sequence = "DROP SEQUENCE " . $sequence_name; $trigger_name = $this->getTriggerFromDB($xmldb_table); $trigger = "DROP TRIGGER " . $trigger_name; if ($include_trigger) { $result = array($sequence, $trigger); } else { $result = array($sequence); } return $result; } /** * Returns the code (in array) needed to add one comment to the table */ function getCommentSQL ($xmldb_table) { $comment = "COMMENT ON TABLE " . $this->getTableName($xmldb_table); $comment.= " IS '" . addslashes(substr($xmldb_table->getComment(), 0, 250)) . "'"; return array($comment); } /** * Returns the code (array of statements) needed to execute extra statements on field rename */ function getRenameFieldExtraSQL ($xmldb_table, $xmldb_field, $newname) { $results = array(); /// If the field is enum, drop and re-create the check constraint if ($xmldb_field->getEnum()) { /// Drop the current enum $results = array_merge($results, $this->getDropEnumSQL($xmldb_table, $xmldb_field)); /// Change field name (over a clone to avoid some potential problems later) $new_xmldb_field = clone($xmldb_field); $new_xmldb_field->setName($newname); /// Recreate the enum $results = array_merge($results, $this->getCreateEnumSQL($xmldb_table, $new_xmldb_field)); } return $results; } /** * Returns the code (array of statements) needed to execute extra statements on table drop */ function getDropTableExtraSQL ($xmldb_table) { $xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id. return $this->getDropSequenceSQL($xmldb_table, $xmldb_field, false); } /** * Returns the code (array of statements) needed to execute extra statements on table rename */ function getRenameTableExtraSQL ($xmldb_table, $newname) { $results = array(); $xmldb_field = new XMLDBField('id'); // Fields having sequences should be exclusively, id. $oldseqname = $this->getSequenceFromDB($xmldb_table); $newseqname = $this->getNameForObject($newname, $xmldb_field->getName(), 'seq'); /// Rename de sequence $results[] = 'RENAME ' . $oldseqname . ' TO ' . $newseqname; $oldtriggername = $this->getTriggerFromDB($xmldb_table); $newtriggername = $this->getNameForObject($newname, $xmldb_field->getName(), 'trg'); /// Drop old trigger $results[] = "DROP TRIGGER " . $oldtriggername; $newt = new XMLDBTable($newname); /// Temp table for trigger code generation /// Create new trigger $results = array_merge($results, $this->getCreateTriggerSQL($newt, $xmldb_field)); /// Rename all the check constraints in the table $oldtablename = $this->getTableName($xmldb_table); $newtablename = $this->getTableName($newt); $oldconstraintprefix = $this->getNameForObject($xmldb_table->getName(), ''); $newconstraintprefix = $this->getNameForObject($newt->getName(), '', ''); if ($constraints = $this->getCheckConstraintsFromDB($xmldb_table)) { foreach ($constraints as $constraint) { /// Drop the old constraint $results[] = 'ALTER TABLE ' . $newtablename . ' DROP CONSTRAINT ' . $constraint->name; /// Calculate the new constraint name $newconstraintname = str_replace($oldconstraintprefix, $newconstraintprefix, $constraint->name); /// Add the new constraint $results[] = 'ALTER TABLE ' . $newtablename . ' ADD CONSTRAINT ' . $newconstraintname . ' CHECK (' . $constraint->description . ')'; } } return $results; } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to alter the field in the table * Oracle has some severe limits: * - clob and blob fields doesn't allow type to be specified * - error is dropped if the null/not null clause is specified and hasn't changed * - changes in precision/decimals of numeric fields drop an ORA-1440 error */ function getAlterFieldSQL($xmldb_table, $xmldb_field) { global $db; $results = array(); /// To store all the needed SQL commands /// Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); /// Take a look to field metadata $meta = array_change_key_case($db->MetaColumns($tablename)); $metac = $meta[$fieldname]; $oldtype = strtolower($metac->type); $oldmetatype = column_type($xmldb_table->getName(), $fieldname); $oldlength = $metac->max_length; /// To calculate the oldlength if the field is numeric, we need to perform one extra query /// because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883 if ($oldmetatype == 'N') { $uppertablename = strtoupper($tablename); $upperfieldname = strtoupper($fieldname); if ($col = get_record_sql("SELECT cname, precision FROM col WHERE tname = '$uppertablename' AND cname = '$upperfieldname'")) { $oldlength = $col->precision; } } $olddecimals = empty($metac->scale) ? null : $metac->scale; $oldnotnull = empty($metac->not_null) ? false : $metac->not_null; $olddefault = empty($metac->default_value) || strtoupper($metac->default_value) == 'NULL' ? null : $metac->default_value; $typechanged = true; //By default, assume that the column type has changed $precisionchanged = true; //By default, assume that the column precision has changed $decimalchanged = true; //By default, assume that the column decimal has changed $defaultchanged = true; //By default, assume that the column default has changed $notnullchanged = true; //By default, assume that the column notnull has changed $from_temp_fields = false; //By default don't assume we are going to use temporal fields /// Detect if we are changing the type of the column if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && substr($oldmetatype, 0, 1) == 'I') || ($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') || ($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') || ($xmldb_field->getType() == XMLDB_TYPE_CHAR && substr($oldmetatype, 0, 1) == 'C') || ($xmldb_field->getType() == XMLDB_TYPE_TEXT && substr($oldmetatype, 0, 1) == 'X') || ($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) { $typechanged = false; } /// Detect if precision has changed if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || ($oldlength == -1) || ($xmldb_field->getLength() == $oldlength)) { $precisionchanged = false; } /// Detect if decimal has changed if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) || ($xmldb_field->getType() == XMLDB_TYPE_CHAR) || ($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || (!$xmldb_field->getDecimals()) || (!$olddecimals) || ($xmldb_field->getDecimals() == $olddecimals)) { $decimalchanged = false; } /// Detect if we are changing the default if (($xmldb_field->getDefault() === null && $olddefault === null) || ($xmldb_field->getDefault() === $olddefault) || //Check both equality and ("'" . $xmldb_field->getDefault() . "'" === $olddefault)) { //Equality with quotes because ADOdb returns the default with quotes $defaultchanged = false; } /// Detect if we are changing the nullability if (($xmldb_field->getNotnull() === $oldnotnull)) { $notnullchanged = false; } /// If type has changed or precision or decimal has changed and we are in one numeric field /// - create one temp column with the new specs /// - fill the new column with the values from the old one /// - drop the old column /// - rename the temp column to the original name if (($typechanged) || (($oldmetatype == 'N' || $oldmetatype == 'I') && ($precisionchanged || $decimalchanged))) { $tempcolname = $xmldb_field->getName() . '_alter_column_tmp'; /// Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints $this->alter_column_skip_notnull = true; $this->alter_column_skip_default = true; $xmldb_field->setName($tempcolname); /// Create the temporal column $results = array_merge($results, $this->getAddFieldSQL($xmldb_table, $xmldb_field)); /// Copy contents from original col to the temporal one $results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = ' . $fieldname; /// Drop the old column $xmldb_field->setName($fieldname); //Set back the original field name $results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field)); /// Rename the temp column to the original one $results[] = 'ALTER TABLE ' . $tablename . ' RENAME COLUMN ' . $tempcolname . ' TO ' . $fieldname; /// Mark we have performed one change based in temp fields $from_temp_fields = true; /// Re-enable the notnull and default sections so the general AlterFieldSQL can use it $this->alter_column_skip_notnull = false; $this->alter_column_skip_default = false; /// Dissable the type section because we have done it with the temp field $this->alter_column_skip_type = true; /// If new field is nullable, nullability hasn't changed if (!$xmldb_field->getNotnull()) { $notnullchanged = false; } /// If new field hasn't default, default hasn't changed if ($xmldb_field->getDefault() === null) { $defaultchanged = false; } } /// If type and precision and decimals hasn't changed, prevent the type clause if (!$typechanged && !$precisionchanged && !$decimalchanged) { $this->alter_column_skip_type = true; } /// If NULL/NOT NULL hasn't changed /// prevent null clause to be specified if (!$notnullchanged) { $this->alter_column_skip_notnull = true; /// Initially, prevent the notnull clause /// But, if we have used the temp field and the new field is not null, then enforce the not null clause if ($from_temp_fields && $xmldb_field->getNotnull()) { $this->alter_column_skip_notnull = false; } } /// If default hasn't changed /// prevent default clause to be specified if (!$defaultchanged) { $this->alter_column_skip_default = true; /// Initially, prevent the default clause /// But, if we have used the temp field and the new field has default clause, then enforce the default clause if ($from_temp_fields && $default_clause = $this->getDefaultClause($xmldb_field)) { $this->alter_column_skip_default = false; } } /// If arriving here, something is not being skiped (type, notnull, default), calculate the standar AlterFieldSQL if (!$this->alter_column_skip_type || !$this->alter_column_skip_notnull || !$this->alter_column_skip_default) { $results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field)); return $results; } /// Finally return results return $results; } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its enum * (usually invoked from getModifyEnumSQL() */ function getCreateEnumSQL($xmldb_table, $xmldb_field) { /// All we have to do is to create the check constraint return array('ALTER TABLE ' . $this->getTableName($xmldb_table) . ' ADD ' . $this->getEnumExtraSQL($xmldb_table, $xmldb_field)); } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its enum * (usually invoked from getModifyEnumSQL() */ function getDropEnumSQL($xmldb_table, $xmldb_field) { /// Let's introspect to know the real name of the check constraint if ($check_constraints = $this->getCheckConstraintsFromDB($xmldb_table, $xmldb_field)) { $check_constraint = array_shift($check_constraints); /// Get the 1st (should be only one) $constraint_name = strtolower($check_constraint->name); /// Extract the REAL name /// All we have to do is to drop the check constraint return array('ALTER TABLE ' . $this->getTableName($xmldb_table) . ' DROP CONSTRAINT ' . $constraint_name); } else { /// Constraint not found. Nothing to do return array(); } } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to create its default * (usually invoked from getModifyDefaultSQL() */ function getCreateDefaultSQL($xmldb_table, $xmldb_field) { /// Just a wrapper over the getAlterFieldSQL() function for Oracle that /// is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one XMLDBTable and one XMLDBField, return the SQL statements needded to drop its default * (usually invoked from getModifyDefaultSQL() */ function getDropDefaultSQL($xmldb_table, $xmldb_field) { /// Just a wrapper over the getAlterFieldSQL() function for Oracle that /// is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one XMLDBTable returns one array with all the check constrainsts * in the table (fetched from DB) * Optionally the function allows one xmldb_field to be specified in * order to return only the check constraints belonging to one field. * Each element contains the name of the constraint and its description * If no check constraints are found, returns an empty array */ function getCheckConstraintsFromDB($xmldb_table, $xmldb_field = null) { $results = array(); $tablename = strtoupper($this->getTableName($xmldb_table)); if ($constraints = get_records_sql("SELECT lower(c.constraint_name) AS name, c.search_condition AS description FROM user_constraints c WHERE c.table_name = '{$tablename}' AND c.constraint_type = 'C' AND c.constraint_name not like 'SYS%'")) { foreach ($constraints as $constraint) { $results[$constraint->name] = $constraint; } } /// Filter by the required field if specified if ($xmldb_field) { $filtered_results = array(); $filter = $xmldb_field->getName(); /// Lets clean a bit each constraint description, looking for the filtered field foreach ($results as $key => $result) { /// description starts by "$filter IN" assume it's a constraint beloging to the field if (preg_match("/^{$filter} IN/i", $result->description)) { $filtered_results[$key] = $result; } } /// Assign filtered results to the final results array $results = $filtered_results; } return $results; } /** * Given one XMLDBTable returns one string with the sequence of the table * in the table (fetched from DB) * The sequence name for oracle is calculated by looking the corresponding * trigger and retrieving the sequence name from it (because sequences are * independent elements) * If no sequence is found, returns false */ function getSequenceFromDB($xmldb_table) { $tablename = strtoupper($this->getTableName($xmldb_table)); $prefixupper = strtoupper($this->prefix); $sequencename = false; if ($trigger = get_record_sql("SELECT trigger_name, trigger_body FROM user_triggers WHERE table_name = '{$tablename}' AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) { /// If trigger found, regexp it looking for the sequence name preg_match('/.*SELECT (.*)\.nextval/i', $trigger->trigger_body, $matches); if (isset($matches[1])) { $sequencename = $matches[1]; } } return $sequencename; } /** * Given one XMLDBTable returns one string with the trigger * in the table (fetched from DB) * If no trigger is found, returns false */ function getTriggerFromDB($xmldb_table) { $tablename = strtoupper($this->getTableName($xmldb_table)); $prefixupper = strtoupper($this->prefix); $triggername = false; if ($trigger = get_record_sql("SELECT trigger_name, trigger_body FROM user_triggers WHERE table_name = '{$tablename}' AND trigger_name LIKE '{$prefixupper}%_ID%_TRG'")) { $triggername = $trigger->trigger_name; } return $triggername; } /** * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) * return if such name is currently in use (true) or no (false) * (invoked from getNameForObject() */ function isNameInUse($object_name, $type, $table_name) { switch($type) { case 'ix': case 'uix': case 'seq': case 'trg': if ($check = get_records_sql("SELECT object_name FROM user_objects WHERE lower(object_name) = '" . strtolower($object_name) . "'")) { return true; } break; case 'pk': case 'uk': case 'fk': case 'ck': if ($check = get_records_sql("SELECT constraint_name FROM user_constraints WHERE lower(constraint_name) = '" . strtolower($object_name) . "'")) { return true; } break; } return false; //No name in use found } /** * Returns an array of reserved words (lowercase) for this DB */ function getReservedWords() { /// This file contains the reserved words for Oracle databases /// from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm $reserved_words = array ( 'access', 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'audit', 'between', 'by', 'char', 'check', 'cluster', 'column', 'comment', 'compress', 'connect', 'create', 'current', 'date', 'decimal', 'default', 'delete', 'desc', 'distinct', 'drop', 'else', 'exclusive', 'exists', 'file', 'float', 'for', 'from', 'grant', 'group', 'having', 'identified', 'immediate', 'in', 'increment', 'index', 'initial', 'insert', 'integer', 'intersect', 'into', 'is', 'level', 'like', 'lock', 'long', 'maxextents', 'minus', 'mlslabel', 'mode', 'modify', 'noaudit', 'nocompress', 'not', 'nowait', 'null', 'number', 'of', 'offline', 'on', 'online', 'option', 'or', 'order', 'pctfree', 'prior', 'privileges', 'public', 'raw', 'rename', 'resource', 'revoke', 'row', 'rowid', 'rownum', 'rows', 'select', 'session', 'set', 'share', 'size', 'smallint', 'start', 'successful', 'synonym', 'sysdate', 'table', 'then', 'to', 'trigger', 'uid', 'union', 'unique', 'update', 'user', 'validate', 'values', 'varchar', 'varchar2', 'view', 'whenever', 'where', 'with' ); return $reserved_words; } } ?>
bobpuffer/1.9.12-LAE1.3
lib/xmldb/classes/generators/oci8po/oci8po.class.php
PHP
gpl-2.0
29,382
<!DOCTYPE html> <html> <head> <title>SceneJS / cannon.js example</title> <meta charset="utf-8"> <style> * {margin:0;padding:0} </style> </head> <body> <script src="../libs/scenejs.js"></script> <script src="../build/cannon.js"></script> <canvas id="theCanvas" width="600" height="400"/> <script> var scene, quaternionNode, translationNode, world, body, shape, timeStep=1/60; initCannon(); initSceneJS(); animate(); function initCannon() { world = new CANNON.World(); world.gravity.set(0,0,0); shape = new CANNON.Box(new CANNON.Vec3(1,1,1)); body = new CANNON.Body({ mass: 1 }); body.addShape(shape); body.angularVelocity.set(0,10,0); body.angularDamping = 0.01; world.add(body); } function initSceneJS() { SceneJS.createScene({ id: "theScene", canvasId: "theCanvas", nodes: [ { type: "lookAt", eye : { x: 0.0, y: 10.0, z: 15 }, look : { y:1.0 }, up : { y: 1.0 }, nodes: [ { type: "camera", optics: { type: "perspective", fovy : 25.0, aspect : 1.47, near : 0.10, far : 300.0 }, nodes: [ { type: "renderer", clearColor: { r: 1.0, g: 1.0, b: 1.0 }, clear: { depth : true, color : true }, nodes: [ { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 1.0 }, diffuse: true, specular: true, dir: { x: 1.0, y: -0.5, z: -1.0 } }, { type: "light", mode: "dir", color: { r: 1.0, g: 1.0, b: 0.8 }, diffuse: true, specular: false, dir: { x: 0.0, y: -0.5, z: -1.0 } }, { type: "translate", id: "translate", x : 0.0, y : 0.0, z : 0.0, nodes: [ { type: "quaternion", id: "quaternion", x : 1.0, y : 0.0, z : 0.0, angle : 0.0, nodes: [ { type: "material", emit: 0, baseColor: { r: 0.5, g: 0.5, b: 0.6 }, specularColor: { r: 0.9, g: 0.9, b: 0.9 }, specular: 1.0, shine: 70.0, nodes: [ { type : "cube", xSize: shape.halfExtents.x, ySize: shape.halfExtents.y, zSize: shape.halfExtents.z, } ] } ] } ] } ] } ] } ] } ] }); // Get handles to some nodes scene = SceneJS.scene("theScene"); quaternionNode = scene.findNode("quaternion"); translationNode = scene.findNode("translate"); } function animate() { // Start the scene rendering scene.start({ idleFunc: updatePhysics }); } function updatePhysics() { var axisAndAngle, axis, angle; // Step the physics world world.step(timeStep); // Copy position from cannon to SceneJS translation node translationNode.set("xyz",body.position); // Get orientation of the body from cannon.js axisAndAngle = body.quaternion.toAxisAngle(); axis = axisAndAngle[0]; angle = axisAndAngle[1]; // Copy orientation to the SceneJS quaternion node quaternionNode.set("rotation",{ x: axis.x, y: axis.y, z: axis.z, angle: angle*180 / Math.PI }); } </script> </body> </html>
oportocala/novie
bower_components/cannon.js/examples/scenejs.html
HTML
gpl-2.0
6,655
<?php class BWGViewGalleries_bwg { //////////////////////////////////////////////////////////////////////////////////////// // Events // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Constants // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Variables // //////////////////////////////////////////////////////////////////////////////////////// private $model; //////////////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor // //////////////////////////////////////////////////////////////////////////////////////// public function __construct($model) { $this->model = $model; } //////////////////////////////////////////////////////////////////////////////////////// // Public Methods // //////////////////////////////////////////////////////////////////////////////////////// public function display() { global $WD_BWG_UPLOAD_DIR; $rows_data = $this->model->get_rows_data(); $page_nav = $this->model->page_nav(); $search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : ''); $search_select_value = ((isset($_POST['search_select_value'])) ? (int) $_POST['search_select_value'] : 0); $asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc'); $order_by = (isset($_POST['order_by']) ? esc_html(stripslashes($_POST['order_by'])) : 'order'); $order_class = 'manage-column column-title sorted ' . $asc_or_desc; $ids_string = ''; ?> <div style="clear: both; float: left; width: 95%;"> <div style="float:left; font-size: 14px; font-weight: bold;"> This section allows you to create, edit and delete galleries. <a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/wordpress-gallery-guide-step-2.html">Read More in User Manual</a> </div> <div style="float: right; text-align: right;"> <a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/wordpress-photo-gallery-plugin.html"> <img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" /> </a> </div> </div> <form class="wrap" id="galleries_form" method="post" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;"> <span class="gallery-icon"></span> <h2> Galleries <a href="" class="add-new-h2" onclick="spider_set_input_value('task', 'add'); spider_form_submit(event, 'galleries_form')">Add new</a> </h2> <div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div> <div class="buttons_div"> <span class="button-secondary non_selectable" onclick="spider_check_all_items()"> <input type="checkbox" id="check_all_items" name="check_all_items" onclick="spider_check_all_items_checkbox()" style="margin: 0; vertical-align: middle;" /> <span style="vertical-align: middle;">Select All</span> </span> <input id="show_hide_weights" class="button-secondary" type="button" onclick="spider_show_hide_weights();return false;" value="Hide order column" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'save_order')" value="Save Order" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'publish_all')" value="Publish" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('task', 'unpublish_all')" value="Unpublish" /> <input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) { spider_set_input_value('task', 'delete_all'); } else { return false; }" value="Delete" /> </div> <div class="tablenav top"> <?php WDWLibrary::search('Name', $search_value, 'galleries_form'); WDWLibrary::html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form'); ?> </div> <table class="wp-list-table widefat fixed pages"> <thead> <th class="table_small_col"></th> <th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th> <th class="table_small_col <?php if ($order_by == 'id') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'id'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'id') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>ID</span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col">Thumbnail</th> <th class="<?php if ($order_by == 'name') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'name'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Name</span><span class="sorting-indicator"></span> </a> </th> <th class="<?php if ($order_by == 'slug') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'slug'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'slug') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Slug</span><span class="sorting-indicator"></span> </a> </th> <th class="<?php if ($order_by == 'display_name') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'display_name'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'display_name') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Author</span><span class="sorting-indicator"></span> </a> </th> <th id="th_order" class="table_medium_col <?php if ($order_by == 'order') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'order'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Order</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col <?php if ($order_by == 'published') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('order_by', 'published'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['order_by']) && (esc_html(stripslashes($_POST['order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_form_submit(event, 'galleries_form')" href=""> <span>Published</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col">Edit</th> <th class="table_big_col">Delete</th> </thead> <tbody id="tbody_arr"> <?php if ($rows_data) { foreach ($rows_data as $row_data) { $alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"'; $published_image = (($row_data->published) ? 'publish' : 'unpublish'); $published = (($row_data->published) ? 'unpublish' : 'publish'); if ($row_data->preview_image == '') { $preview_image = WD_BWG_URL . '/images/no-image.png'; } else { $preview_image = site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row_data->preview_image; } ?> <tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>> <td class="connectedSortable table_small_col"><div title="Drag to re-order"class="handle" style="margin:5px auto 0 auto;"></div></td> <td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td> <td class="table_small_col"><?php echo $row_data->id; ?></td> <td class="table_extra_large_col"> <img title="<?php echo $row_data->name; ?>" style="border: 1px solid #CCCCCC; max-width:60px; max-height:60px;" src="<?php echo $preview_image . '?date=' . date('Y-m-y H:i:s'); ?>"> </td> <td><a onclick="spider_set_input_value('task', 'edit'); spider_set_input_value('page_number', '1'); spider_set_input_value('search_value', ''); spider_set_input_value('search_or_not', ''); spider_set_input_value('asc_or_desc', 'asc'); spider_set_input_value('order_by', 'order'); spider_set_input_value('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="" title="Edit"><?php echo $row_data->name; ?></a></td> <td><?php echo $row_data->slug; ?></td> <td><?php echo get_userdata($row_data->author)->display_name; ?></td> <td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td> <td class="table_big_col"><a onclick="spider_set_input_value('task', '<?php echo $published; ?>');spider_set_input_value('current_id', '<?php echo $row_data->id; ?>');spider_form_submit(event, 'galleries_form')" href=""><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td> <td class="table_big_col"><a onclick="spider_set_input_value('task', 'edit'); spider_set_input_value('page_number', '1'); spider_set_input_value('search_value', ''); spider_set_input_value('search_or_not', ''); spider_set_input_value('asc_or_desc', 'asc'); spider_set_input_value('order_by', 'order'); spider_set_input_value('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="">Edit</a></td> <td class="table_big_col"><a onclick="spider_set_input_value('task', 'delete'); spider_set_input_value('current_id', '<?php echo $row_data->id; ?>'); spider_form_submit(event, 'galleries_form')" href="">Delete</a></td> </tr> <?php $ids_string .= $row_data->id . ','; } } ?> </tbody> </table> <input id="task" name="task" type="hidden" value="" /> <input id="current_id" name="current_id" type="hidden" value="" /> <input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" /> <input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" /> <input id="order_by" name="order_by" type="hidden" value="<?php echo $order_by; ?>" /> <script> window.onload = spider_show_hide_weights; </script> </form> <?php } public function edit($id) { global $WD_BWG_UPLOAD_DIR; $row = $this->model->get_row_data($id); $option_row = $this->model->get_option_row_data(); $page_title = (($id != 0) ? 'Edit gallery ' . $row->name : 'Create new gallery'); ?> <div style="clear: both; float: left; width: 95%;"> <div id="message_div" class="updated" style="display: none;"></div> <div style="float:left; font-size: 14px; font-weight: bold;"> This section allows you to add/edit gallery. <a style="color: blue; text-decoration: none;" target="_blank" href="http://web-dorado.com/wordpress-gallery-guide-step-2.html">Read More in User Manual</a> </div> <div style="float: right; text-align: right;"> <a style="text-decoration: none;" target="_blank" href="http://web-dorado.com/products/wordpress-photo-gallery-plugin.html"> <img width="215" border="0" alt="web-dorado.com" src="<?php echo WD_BWG_URL . '/images/logo.png'; ?>" /> </a> </div> </div> <script> function spider_set_href(a, number, type) { var image_url = document.getElementById("image_url_" + number).value; var thumb_url = document.getElementById("thumb_url_" + number).value; a.href='<?php echo add_query_arg(array('action' => 'editThumb', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&type=' + type + '&image_id=' + number + '&image_url=' + image_url + '&thumb_url=' + thumb_url + '&TB_iframe=1'; } function bwg_add_preview_image(files) { document.getElementById("preview_image").value = files[0]['thumb_url']; document.getElementById("button_preview_image").style.display = "none"; document.getElementById("delete_preview_image").style.display = "inline-block"; if (document.getElementById("img_preview_image")) { document.getElementById("img_preview_image").src = files[0]['reliative_url']; document.getElementById("img_preview_image").style.display = "inline-block"; } } var j_int = 0; var bwg_j = 'pr_' + j_int; function bwg_add_image(files) { var tbody = document.getElementById('tbody_arr'); for (var i in files) { var is_video = files[i]['filetype'] == 'YOUTUBE' || files[i]['filetype'] == 'VIMEO'; var tr = document.createElement('tr'); tr.setAttribute('id', "tr_" + bwg_j); if (tbody.firstChild) { tbody.insertBefore(tr, tbody.firstChild); } else { tbody.appendChild(tr); } // Handle TD. var td_handle = document.createElement('td'); td_handle.setAttribute('class', "connectedSortable table_small_col"); td_handle.setAttribute('title', "Drag to re-order"); tr.appendChild(td_handle); var div_handle = document.createElement('div'); div_handle.setAttribute('class', "handle connectedSortable"); div_handle.setAttribute('style', "margin: 5px auto 0px;"); td_handle.appendChild(div_handle); // Checkbox TD. var td_checkbox = document.createElement('td'); td_checkbox.setAttribute('class', "table_small_col check-column"); td_checkbox.setAttribute('onclick', "spider_check_all(this)"); tr.appendChild(td_checkbox); var input_checkbox = document.createElement('input'); input_checkbox.setAttribute('id', "check_" + bwg_j); input_checkbox.setAttribute('name', "check_" + bwg_j); input_checkbox.setAttribute('type', "checkbox"); td_checkbox.appendChild(input_checkbox); // Numbering TD. var td_numbering = document.createElement('td'); td_numbering.setAttribute('class', "table_small_col"); td_numbering.innerHTML = ""; tr.appendChild(td_numbering); // Thumb TD. var td_thumb = document.createElement('td'); td_thumb.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_thumb); var a_thumb = document.createElement('a'); a_thumb.setAttribute('class', "thickbox thickbox-preview"); a_thumb.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_thumb.setAttribute('title', files[i]['name']); td_thumb.appendChild(a_thumb); var img_thumb = document.createElement('img'); img_thumb.setAttribute('id', "image_thumb_" + bwg_j); img_thumb.setAttribute('class', "thumb"); img_thumb.setAttribute('src', files[i]['thumb']); a_thumb.appendChild(img_thumb); // Filename TD. var td_filename = document.createElement('td'); td_filename.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_filename); var div_filename = document.createElement('div'); div_filename.setAttribute('class', "filename"); div_filename.setAttribute('id', "filename_" + bwg_j); td_filename.appendChild(div_filename); var strong_filename = document.createElement('strong'); div_filename.appendChild(strong_filename); var a_filename = document.createElement('a'); a_filename.setAttribute('href', "<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_filename.setAttribute('class', "spider_word_wrap thickbox thickbox-preview"); a_filename.setAttribute('title', files[i]['filename']); a_filename.innerHTML = files[i]['filename']; strong_filename.appendChild(a_filename); var div_date_modified = document.createElement('div'); div_date_modified.setAttribute('class', "fileDescription"); div_date_modified.setAttribute('title', "Date modified"); div_date_modified.setAttribute('id', "date_modified_" + bwg_j); div_date_modified.innerHTML = files[i]['date_modified']; td_filename.appendChild(div_date_modified); var div_fileresolution = document.createElement('div'); div_fileresolution.setAttribute('class', "fileDescription"); div_fileresolution.setAttribute('title', "Image Resolution"); div_fileresolution.setAttribute('id', "fileresolution" + bwg_j); div_fileresolution.innerHTML = files[i]['resolution']; td_filename.appendChild(div_fileresolution); var div_filesize = document.createElement('div'); div_filesize.setAttribute('class', "fileDescription"); div_filesize.setAttribute('title', (!is_video) ? "Image size" : "Duration"); div_filesize.setAttribute('id', "filesize" + bwg_j); div_filesize.innerHTML = files[i]['size']; td_filename.appendChild(div_filesize); var div_filetype = document.createElement('div'); div_filetype.setAttribute('class', "fileDescription"); div_filetype.setAttribute('title', "Type"); div_filetype.setAttribute('id', "filetype" + bwg_j); div_filetype.innerHTML = files[i]['filetype']; td_filename.appendChild(div_filetype); if (!is_video) { var div_edit = document.createElement('div'); td_filename.appendChild(div_edit); var span_edit_crop = document.createElement('span'); span_edit_crop.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_crop); var a_crop = document.createElement('a'); a_crop.setAttribute('class', "thickbox thickbox-preview"); a_crop.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'crop');"); a_crop.innerHTML = "Crop"; span_edit_crop.appendChild(a_crop); div_edit.innerHTML += " | "; var span_edit_rotate = document.createElement('span'); span_edit_rotate.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_rotate); var a_rotate = document.createElement('a'); a_rotate.setAttribute('class', "thickbox thickbox-preview"); a_rotate.setAttribute('onclick', "spider_set_href(this, '" + bwg_j + "', 'rotate');"); a_rotate.innerHTML = "Rotate"; span_edit_rotate.appendChild(a_rotate); div_edit.innerHTML += " | " var span_edit_recover = document.createElement('span'); span_edit_recover.setAttribute('class', "edit_thumb"); div_edit.appendChild(span_edit_recover); var a_recover = document.createElement('a'); a_recover.setAttribute('onclick', 'if (confirm("Do you want to reset the image?")) { spider_set_input_value("ajax_task", "recover"); spider_set_input_value("image_current_id", "' + bwg_j + '"); spider_ajax_save("galleries_form");} return false;'); a_recover.innerHTML = "Reset"; span_edit_recover.appendChild(a_recover); } var input_image_url = document.createElement('input'); input_image_url.setAttribute('id', "image_url_" + bwg_j); input_image_url.setAttribute('name', "image_url_" + bwg_j); input_image_url.setAttribute('type', "hidden"); input_image_url.setAttribute('value', files[i]['url']); td_filename.appendChild(input_image_url); var input_thumb_url = document.createElement('input'); input_thumb_url.setAttribute('id', "thumb_url_" + bwg_j); input_thumb_url.setAttribute('name', "thumb_url_" + bwg_j); input_thumb_url.setAttribute('type', "hidden"); input_thumb_url.setAttribute('value', files[i]['thumb_url']); td_filename.appendChild(input_thumb_url); var input_filename = document.createElement('input'); input_filename.setAttribute('id', "input_filename_" + bwg_j); input_filename.setAttribute('name', "input_filename_" + bwg_j); input_filename.setAttribute('type', "hidden"); input_filename.setAttribute('value', files[i]['filename']); td_filename.appendChild(input_filename); var input_date_modified = document.createElement('input'); input_date_modified.setAttribute('id', "input_date_modified_" + bwg_j); input_date_modified.setAttribute('name', "input_date_modified_" + bwg_j); input_date_modified.setAttribute('type', "hidden"); input_date_modified.setAttribute('value', files[i]['date_modified']); td_filename.appendChild(input_date_modified); var input_resolution = document.createElement('input'); input_resolution.setAttribute('id', "input_resolution_" + bwg_j); input_resolution.setAttribute('name', "input_resolution_" + bwg_j); input_resolution.setAttribute('type', "hidden"); input_resolution.setAttribute('value', files[i]['resolution']); td_filename.appendChild(input_resolution); var input_size = document.createElement('input'); input_size.setAttribute('id', "input_size_" + bwg_j); input_size.setAttribute('name', "input_size_" + bwg_j); input_size.setAttribute('type', "hidden"); input_size.setAttribute('value', files[i]['size']); td_filename.appendChild(input_size); var input_filetype = document.createElement('input'); input_filetype.setAttribute('id', "input_filetype_" + bwg_j); input_filetype.setAttribute('name', "input_filetype_" + bwg_j); input_filetype.setAttribute('type', "hidden"); input_filetype.setAttribute('value', files[i]['filetype']); td_filename.appendChild(input_filetype); // Alt/Title TD. var td_alt = document.createElement('td'); td_alt.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_alt); var input_alt = document.createElement('input'); input_alt.setAttribute('id', "image_alt_text_" + bwg_j); input_alt.setAttribute('name', "image_alt_text_" + bwg_j); input_alt.setAttribute('type', "text"); input_alt.setAttribute('size', "24"); if (is_video) { input_alt.setAttribute('value', files[i]['name']); } else { input_alt.setAttribute('value', files[i]['filename']); } td_alt.appendChild(input_alt); <?php if ($option_row->thumb_click_action != 'open_lightbox') { ?> //Redirect url input_alt = document.createElement('input'); input_alt.setAttribute('id', "redirect_url_" + bwg_j); input_alt.setAttribute('name', "redirect_url_" + bwg_j); input_alt.setAttribute('type', "text"); input_alt.setAttribute('size', "24"); td_alt.appendChild(input_alt); <?php } ?> // Description TD. var td_desc = document.createElement('td'); td_desc.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_desc); var textarea_desc = document.createElement('textarea'); textarea_desc.setAttribute('id', "image_description_" + bwg_j); textarea_desc.setAttribute('name', "image_description_" + bwg_j); textarea_desc.setAttribute('rows', "2"); textarea_desc.setAttribute('cols', "20"); textarea_desc.setAttribute('style', "resize:vertical;"); if (is_video) { textarea_desc.innerHTML = files[i]['description']; } td_desc.appendChild(textarea_desc); // Tag TD. var td_tag = document.createElement('td'); td_tag.setAttribute('class', "table_extra_large_col"); tr.appendChild(td_tag); var a_tag = document.createElement('a'); a_tag.setAttribute('class', "button button-small button-primary thickbox thickbox-preview"); a_tag.setAttribute('href', "<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&image_id=" + bwg_j + "&TB_iframe=1"); a_tag.innerHTML = 'Add tag'; td_tag.appendChild(a_tag); var div_tag = document.createElement('div'); div_tag.setAttribute('class', "tags_div"); div_tag.setAttribute('id', "tags_div_" + bwg_j); td_tag.appendChild(div_tag); var hidden_tag = document.createElement('input'); hidden_tag.setAttribute('type', "hidden"); hidden_tag.setAttribute('id', "tags_" + bwg_j); hidden_tag.setAttribute('name', "tags_" + bwg_j); hidden_tag.setAttribute('value', ""); td_tag.appendChild(hidden_tag); // Order TD. var td_order = document.createElement('td'); td_order.setAttribute('class', "spider_order table_medium_col"); td_order.setAttribute('style', "display: none;"); tr.appendChild(td_order); var input_order = document.createElement('input'); input_order.setAttribute('id', "order_input_" + bwg_j); input_order.setAttribute('name', "order_input_" + bwg_j); input_order.setAttribute('type', "text"); input_order.setAttribute('value', 0 - j_int); input_order.setAttribute('size', "1"); td_order.appendChild(input_order); // Publish TD. var td_publish = document.createElement('td'); td_publish.setAttribute('class', "table_big_col"); tr.appendChild(td_publish); var a_publish = document.createElement('a'); a_publish.setAttribute('onclick', "spider_set_input_value('ajax_task', 'image_unpublish');spider_set_input_value('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');"); td_publish.appendChild(a_publish); var img_publish = document.createElement('img'); img_publish.setAttribute('src', "<?php echo WD_BWG_URL . '/images/publish.png'; ?>"); a_publish.appendChild(img_publish); // Delete TD. var td_delete = document.createElement('td'); td_delete.setAttribute('class', "table_big_col"); tr.appendChild(td_delete); var a_delete = document.createElement('a'); a_delete.setAttribute('onclick', "spider_set_input_value('ajax_task', 'image_delete');spider_set_input_value('image_current_id', '" + bwg_j + "');spider_ajax_save('galleries_form');"); a_delete.innerHTML = 'Delete'; td_delete.appendChild(a_delete); document.getElementById("ids_string").value += bwg_j + ','; j_int++; bwg_j = 'pr_' + j_int; } jQuery("#show_hide_weights").val("Hide order column"); spider_show_hide_weights(); } </script> <form class="wrap" method="post" id="galleries_form" action="admin.php?page=galleries_bwg" style="float: left; width: 95%;"> <span class="gallery-icon"></span> <h2><?php echo $page_title; ?></h2> <div style="float:right;"> <input class="button-secondary" type="button" onclick="if (spider_check_required('name', 'Name')) {return false;}; spider_set_input_value('page_number', '1'); spider_set_input_value('ajax_task', 'ajax_save'); spider_ajax_save('galleries_form'); spider_set_input_value('task', 'save')" value="Save" /> <input class="button-secondary" type="button" onclick="if (spider_check_required('name', 'Name')) {return false;}; spider_set_input_value('ajax_task', 'ajax_apply'); spider_ajax_save('galleries_form')" value="Apply" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('page_number', '1'); spider_set_input_value('task', 'cancel')" value="Cancel" /> </div> <table style="clear:both;"> <tbody> <tr> <td class="spider_label"><label for="name">Name: <span style="color:#FF0000;">*</span> </label></td> <td><input type="text" id="name" name="name" value="<?php echo $row->name; ?>" size="39" /></td> </tr> <tr> <td class="spider_label"><label for="slug">Slug: </label></td> <td><input type="text" id="slug" name="slug" value="<?php echo $row->slug; ?>" size="39" /></td> </tr> <tr> <td class="spider_label"><label for="description">Description: </label></td> <td> <div style="width:500px;"> <?php if (user_can_richedit()) { wp_editor($row->description, 'description', array('teeny' => FALSE, 'textarea_name' => 'description', 'media_buttons' => FALSE, 'textarea_rows' => 5)); } else { ?> <textarea cols="36" rows="5" id="description" name="description" style="resize:vertical"> <?php echo $row->description; ?> </textarea> <?php } ?> </div> </td> </tr> <tr> <td class="spider_label"><label>Author: </label></td> <td><?php echo get_userdata($row->author)->display_name; ?></td> </tr> <tr> <td class="spider_label"><label for="published1">Published: </label></td> <td> <input type="radio" class="inputbox" id="published0" name="published" <?php echo (($row->published) ? '' : 'checked="checked"'); ?> value="0" > <label for="published0">No</label> <input type="radio" class="inputbox" id="published1" name="published" <?php echo (($row->published) ? 'checked="checked"' : ''); ?> value="1" > <label for="published1">Yes</label> </td> </tr> <tr> <td class="spider_label"><label for="url">Preview image: </label></td> <td> <a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_preview_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" id="button_preview_image" class="button-primary thickbox thickbox-preview" title="Add Preview Image" onclick="return false;" style="margin-bottom:5px; display:none;"> Add Preview Image </a> <input type="hidden" id="preview_image" name="preview_image" value="<?php echo $row->preview_image; ?>" style="display:inline-block;"/> <img id="img_preview_image" style="max-height:90px; max-width:120px; vertical-align:middle;" src="<?php echo site_url() . '/' . $WD_BWG_UPLOAD_DIR . $row->preview_image; ?>"> <span id="delete_preview_image" class="spider_delete_img" onclick="spider_remove_url('button_preview_image', 'preview_image', 'delete_preview_image', 'img_preview_image')"></span> </td> </tr> <tr> <td colspan=2> <?php echo $this->image_display($id); ?> </td> </tr> </tbody> </table> <input id="task" name="task" type="hidden" value="" /> <input id="current_id" name="current_id" type="hidden" value="<?php echo $row->id; ?>" /> <script> <?php if ($row->preview_image == '') { ?> spider_remove_url('button_preview_image', 'preview_image', 'delete_preview_image', 'img_preview_image'); <?php } ?> </script> <div id="opacity_div" style="display: none; background-color: rgba(0, 0, 0, 0.2); position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;"></div> <div id="loading_div" style="display:none; text-align: center; position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99999;"> <img src="<?php echo WD_BWG_URL . '/images/ajax_loader.png'; ?>" class="spider_ajax_loading" style="margin-top: 200px; width:50px;"> </div> </form> <?php } public function image_display($id) { global $WD_BWG_UPLOAD_DIR; $rows_data = $this->model->get_image_rows_data($id); $page_nav = $this->model->image_page_nav($id); $option_row = $this->model->get_option_row_data(); $search_value = ((isset($_POST['search_value'])) ? esc_html(stripslashes($_POST['search_value'])) : ''); $asc_or_desc = ((isset($_POST['asc_or_desc'])) ? esc_html(stripslashes($_POST['asc_or_desc'])) : 'asc'); $image_order_by = (isset($_POST['image_order_by']) ? esc_html(stripslashes($_POST['image_order_by'])) : 'order'); $order_class = 'manage-column column-title sorted ' . $asc_or_desc; $page_number = (isset($_POST['page_number']) ? esc_html(stripslashes($_POST['page_number'])) : 1); $ids_string = ''; ?> <div id="draganddrop" class="updated" style="display:none;"><strong><p>Changes made in this table should be saved.</p></strong></div> <div class="buttons_div_left"> <a href="<?php echo add_query_arg(array('action' => 'addImages', 'width' => '700', 'height' => '550', 'extensions' => 'jpg,jpeg,png,gif', 'callback' => 'bwg_add_image', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button-primary thickbox thickbox-preview" id="content-add_media" title="Add Images" onclick="return false;" style="margin-bottom:5px;"> Add Images </a> <input id="show_add_video" class="button-primary" type="button" onclick="jQuery('.opacity_add_video').show(); return false;" value="Add Video" /> </div> <div class="buttons_div_right"> <span class="button-secondary non_selectable" onclick="spider_check_all_items()"> <input type="checkbox" id="check_all_items" name="check_all_items" onclick="spider_check_all_items_checkbox()" style="margin: 0; vertical-align: middle;" /> <span style="vertical-align: middle;">Select All</span> </span> <input id="show_hide_weights" class="button-secondary" type="button" onclick="spider_show_hide_weights();return false;" value="Hide order column" /> <input class="button-primary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_set_watermark'); spider_ajax_save('galleries_form'); return false;" value="Set Watermark" /> <input class="button-secondary" type="submit" onclick="jQuery('.opacity_resize_image').show(); return false;" value="Resize" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_recover_all'); spider_ajax_save('galleries_form'); return false;" value="Reset" /> <a onclick="return bwg_check_checkboxes();" href="<?php echo add_query_arg(array('action' => 'addTags', 'width' => '650', 'height' => '500'), admin_url('admin-ajax.php')); ?>&TB_iframe=1" class="button-primary thickbox thickbox-preview">Add tag</a> <input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_publish_all'); spider_ajax_save('galleries_form'); return false;" value="Publish" /> <input class="button-secondary" type="submit" onclick="spider_set_input_value('ajax_task', 'image_unpublish_all'); spider_ajax_save('galleries_form'); return false;" value="Unpublish" /> <input class="button-secondary" type="submit" onclick="if (confirm('Do you want to delete selected items?')) { spider_set_input_value('ajax_task', 'image_delete_all'); spider_ajax_save('galleries_form'); return false; } else { return false; }" value="Delete" /> </div> <div id="opacity_add_video" class="opacity_resize_image opacity_add_video bwg_opacity_video" onclick="jQuery('.opacity_add_video').hide();jQuery('.opacity_resize_image').hide();"></div> <div id="add_video" class="opacity_add_video bwg_add_video"> <input type="text" id="video_url" name="video_url" value="" /> <input class="button-primary" type="button" onclick="if (bwg_get_video_info('video_url')) {jQuery('.opacity_add_video').hide();} return false;" value="Add to gallery" /> <input class="button-secondary" type="button" onclick="jQuery('.opacity_add_video').hide(); return false;" value="Cancel" /> <div class="spider_description">Enter YouTube or Vimeo link here.</div> </div> <div id="" class="opacity_resize_image bwg_resize_image"> Resize images to: <input type="text" name="image_width" id="image_width" value="1600" /> x <input type="text" name="image_height" id="image_height" value="1200" /> px <input class="button-primary" type="button" onclick="spider_set_input_value('ajax_task', 'image_resize'); spider_ajax_save('galleries_form'); jQuery('.opacity_resize_image').hide(); return false;" value="Resize" /> <input class="button-secondary" type="button" onclick="jQuery('.opacity_resize_image').hide(); return false;" value="Cancel" /> <div class="spider_description">The maximum size of resized image.</div> </div> <div class="tablenav top"> <?php WDWLibrary::ajax_search('Filename', $search_value, 'galleries_form'); WDWLibrary::ajax_html_page_nav($page_nav['total'], $page_nav['limit'], 'galleries_form'); ?> </div> <table id="images_table" class="wp-list-table widefat fixed pages"> <thead> <th class="check-column table_small_col"></th> <th class="manage-column column-cb check-column table_small_col"><input id="check_all" type="checkbox" onclick="spider_check_all(this)" style="margin:0;" /></th> <th class="table_small_col">#</th> <th class="table_extra_large_col">Thumbnail</th> <th class="table_extra_large_col <?php if ($image_order_by == 'filename') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'filename'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'filename') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Filename</span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col <?php if ($image_order_by == 'alt') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'alt'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'alt') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Alt/Title<?php if ($option_row->thumb_click_action != 'open_lightbox') { ?><br />Redirect URL<?php } ?></span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col <?php if ($image_order_by == 'description') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'description'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'description') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Description</span><span class="sorting-indicator"></span> </a> </th> <th class="table_extra_large_col">Tags</th> <th id="th_order" class="table_medium_col <?php if ($image_order_by == 'order') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'order'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'order') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Order</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col <?php if ($image_order_by == 'published') {echo $order_class;} ?>"> <a onclick="spider_set_input_value('task', ''); spider_set_input_value('image_order_by', 'published'); spider_set_input_value('asc_or_desc', '<?php echo ((isset($_POST['asc_or_desc']) && isset($_POST['image_order_by']) && (esc_html(stripslashes($_POST['image_order_by'])) == 'published') && esc_html(stripslashes($_POST['asc_or_desc'])) == 'asc') ? 'desc' : 'asc'); ?>'); spider_ajax_save('galleries_form');"> <span>Published</span><span class="sorting-indicator"></span> </a> </th> <th class="table_big_col">Delete</th> </thead> <tbody id="tbody_arr"> <?php $i = ($page_number - 1) * 20; if ($rows_data) { foreach ($rows_data as $row_data) { $is_video = $row_data->filetype == 'YOUTUBE' || $row_data->filetype == 'VIMEO'; $alternate = (!isset($alternate) || $alternate == 'class="alternate"') ? '' : 'class="alternate"'; $rows_tag_data = $this->model->get_tag_rows_data($row_data->id); $published_image = (($row_data->published) ? 'publish' : 'unpublish'); $published = (($row_data->published) ? 'unpublish' : 'publish'); ?> <tr id="tr_<?php echo $row_data->id; ?>" <?php echo $alternate; ?>> <td class="connectedSortable table_small_col"><div title="Drag to re-order" class="handle" style="margin:5px auto 0 auto;"></div></td> <td class="table_small_col check-column"><input id="check_<?php echo $row_data->id; ?>" name="check_<?php echo $row_data->id; ?>" onclick="spider_check_all(this)" type="checkbox" /></td> <td class="table_small_col"><?php echo ++$i; ?></td> <td class="table_extra_large_col"> <a class="thickbox thickbox-preview" title="<?php echo $row_data->alt; ?>" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display'/*thumb_display*/, 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"> <img id="image_thumb_<?php echo $row_data->id; ?>" class="thumb" src="<?php echo (!$is_video ? site_url() . '/' . $WD_BWG_UPLOAD_DIR : "") . $row_data->thumb_url . '?date=' . date('Y-m-y H:i:s'); ?>"> </a> </td> <td class="table_extra_large_col"> <div class="filename" id="filename_<?php echo $row_data->id; ?>"> <strong><a title="<?php echo $row_data->alt; ?>" class="spider_word_wrap thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'display', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>"><?php echo $row_data->filename; ?></a></strong> </div> <div class="fileDescription" title="Date modified" id="date_modified_<?php echo $row_data->id; ?>"><?php echo date("d F Y, H:i", strtotime($row_data->date)); ?></div> <div class="fileDescription" title="Image Resolution" id="fileresolution_<?php echo $row_data->id; ?>"><?php echo $row_data->resolution; ?></div> <div class="fileDescription" title="<?php echo (!$is_video ? "Image size" : "Duration")?>" id="filesize_<?php echo $row_data->id; ?>"><?php echo $row_data->size; ?></div> <div class="fileDescription" title="Type" id="filetype_<?php echo $row_data->id; ?>"><?php echo $row_data->filetype; ?></div> <?php if(!$is_video) {?> <div> <span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'crop', 'image_id' => $row_data->id, 'TB_iframe' => '1', 'width' => '800', 'height' => '500'), admin_url('admin-ajax.php')); ?>">Crop</a></span> | <span class="edit_thumb"><a class="thickbox thickbox-preview" href="<?php echo add_query_arg(array('action' => 'editThumb', 'type' => 'rotate', 'image_id' => $row_data->id, 'width' => '800', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>">Rotate</a></span> | <span class="edit_thumb"><a onclick="if (confirm('Do you want to reset the image?')) { spider_set_input_value('ajax_task', 'recover'); spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form'); } return false;">Reset</a></span> </div> <?php } ?> <input type="hidden" id="image_url_<?php echo $row_data->id; ?>" name="image_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->image_url; ?>" /> <input type="hidden" id="thumb_url_<?php echo $row_data->id; ?>" name="thumb_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->thumb_url; ?>" /> <input type="hidden" id="input_filename_<?php echo $row_data->id; ?>" name="input_filename_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filename; ?>" /> <input type="hidden" id="input_date_modified_<?php echo $row_data->id; ?>" name="input_date_modified_<?php echo $row_data->id; ?>" value="<?php echo $row_data->date; ?>" /> <input type="hidden" id="input_resolution_<?php echo $row_data->id; ?>" name="input_resolution_<?php echo $row_data->id; ?>" value="<?php echo $row_data->resolution; ?>" /> <input type="hidden" id="input_size_<?php echo $row_data->id; ?>" name="input_size_<?php echo $row_data->id; ?>" value="<?php echo $row_data->size; ?>" /> <input type="hidden" id="input_filetype_<?php echo $row_data->id; ?>" name="input_filetype_<?php echo $row_data->id; ?>" value="<?php echo $row_data->filetype; ?>" /> </td> <td class="table_extra_large_col"> <input size="24" type="text" id="image_alt_text_<?php echo $row_data->id; ?>" name="image_alt_text_<?php echo $row_data->id; ?>" value="<?php echo $row_data->alt; ?>" /> <?php if ($option_row->thumb_click_action != 'open_lightbox') { ?> <input size="24" type="text" id="redirect_url_<?php echo $row_data->id; ?>" name="redirect_url_<?php echo $row_data->id; ?>" value="<?php echo $row_data->redirect_url; ?>" /> <?php } ?> </td> <td class="table_extra_large_col"> <textarea cols="20" rows="2" id="image_description_<?php echo $row_data->id; ?>" name="image_description_<?php echo $row_data->id; ?>" style="resize:vertical;"><?php echo $row_data->description; ?></textarea> </td> <td class="table_extra_large_col"> <a href="<?php echo add_query_arg(array('action' => 'addTags', 'image_id' => $row_data->id, 'width' => '650', 'height' => '500', 'TB_iframe' => '1'), admin_url('admin-ajax.php')); ?>" class="button button-small button-primary thickbox thickbox-preview">Add tag</a> <div class="tags_div" id="tags_div_<?php echo $row_data->id; ?>"> <?php $tags_id_string = ''; if ($rows_tag_data) { foreach($rows_tag_data as $row_tag_data) { ?> <div class="tag_div" id="<?php echo $row_data->id; ?>_tag_<?php echo $row_tag_data->term_id; ?>"> <span class="tag_name"><?php echo $row_tag_data->name; ?></span> <span style="float:right;" class="spider_delete_img_small" onclick="bwg_remove_tag('<?php echo $row_tag_data->term_id; ?>', '<?php echo $row_data->id; ?>')" /> </div> <?php $tags_id_string .= $row_tag_data->term_id . ','; } } ?> </div> <input type="hidden" value="<?php echo $tags_id_string; ?>" id="tags_<?php echo $row_data->id; ?>" name="tags_<?php echo $row_data->id; ?>"/> </td> <td class="spider_order table_medium_col"><input id="order_input_<?php echo $row_data->id; ?>" name="order_input_<?php echo $row_data->id; ?>" type="text" size="1" value="<?php echo $row_data->order; ?>" /></td> <td class="table_big_col"><a onclick="spider_set_input_value('ajax_task', 'image_<?php echo $published; ?>'); spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form');"><img src="<?php echo WD_BWG_URL . '/images/' . $published_image . '.png'; ?>"></img></a></td> <td class="table_big_col"><a onclick="spider_set_input_value('ajax_task', 'image_delete'); spider_set_input_value('image_current_id', '<?php echo $row_data->id; ?>'); spider_ajax_save('galleries_form');">Delete</a></td> </tr> <?php $ids_string .= $row_data->id . ','; } } ?> <input id="ids_string" name="ids_string" type="hidden" value="<?php echo $ids_string; ?>" /> <input id="asc_or_desc" name="asc_or_desc" type="hidden" value="asc" /> <input id="image_order_by" name="image_order_by" type="hidden" value="<?php echo $image_order_by; ?>" /> <input id="ajax_task" name="ajax_task" type="hidden" value="" /> <input id="image_current_id" name="image_current_id" type="hidden" value="" /> <input id="added_tags_select_all" name="added_tags_select_all" type="hidden" value="" /> </tbody> </table> <script> window.onload = spider_show_hide_weights; </script> <?php } //////////////////////////////////////////////////////////////////////////////////////// // Getters & Setters // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Private Methods // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Listeners // //////////////////////////////////////////////////////////////////////////////////////// }
duynguyenhai/wordpress
wp-content/plugins/photo-gallery/admin/views/BWGViewGalleries_bwg.php
PHP
gpl-2.0
57,953
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>read_at</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../reference.html" title="Reference"> <link rel="prev" href="read/overload8.html" title="read (8 of 8 overloads)"> <link rel="next" href="read_at/overload1.html" title="read_at (1 of 8 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="read/overload8.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="read_at/overload1.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="boost_asio.reference.read_at"></a><a class="link" href="read_at.html" title="read_at">read_at</a> </h3></div></div></div> <p> <a class="indexterm" name="id1486748"></a> Attempt to read a certain amount of data at the specified offset before returning. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload1.html" title="read_at (1 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload1.html" title="read_at (1 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload2.html" title="read_at (2 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload2.html" title="read_at (2 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload3.html" title="read_at (3 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload3.html" title="read_at (3 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload4.html" title="read_at (4 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload4.html" title="read_at (4 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload5.html" title="read_at (5 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload5.html" title="read_at (5 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload6.html" title="read_at (6 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload6.html" title="read_at (6 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload7.html" title="read_at (7 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload7.html" title="read_at (7 of 8 overloads)">more...</a></em></span> <span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="SyncRandomAccessReadDevice.html" title="Buffer-oriented synchronous random-access read device requirements">SyncRandomAccessReadDevice</a><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">Allocator</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">CompletionCondition</span><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_at/overload8.html" title="read_at (8 of 8 overloads)">read_at</a><span class="special">(</span> <span class="identifier">SyncRandomAccessReadDevice</span> <span class="special">&amp;</span> <span class="identifier">d</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uint64_t</span> <span class="identifier">offset</span><span class="special">,</span> <span class="identifier">basic_streambuf</span><span class="special">&lt;</span> <span class="identifier">Allocator</span> <span class="special">&gt;</span> <span class="special">&amp;</span> <span class="identifier">b</span><span class="special">,</span> <span class="identifier">CompletionCondition</span> <span class="identifier">completion_condition</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="read_at/overload8.html" title="read_at (8 of 8 overloads)">more...</a></em></span> </pre> <h5> <a name="boost_asio.reference.read_at.h0"></a> <span><a name="boost_asio.reference.read_at.requirements"></a></span><a class="link" href="read_at.html#boost_asio.reference.read_at.requirements">Requirements</a> </h5> <p> <span class="bold"><strong>Header: </strong></span><code class="literal">boost/asio/read_at.hpp</code> </p> <p> <span class="bold"><strong>Convenience header: </strong></span><code class="literal">boost/asio.hpp</code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2011 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="read/overload8.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="read_at/overload1.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
charlesDGY/coflo
coflo-0.0.4/third_party/boost_1_48_0/doc/html/boost_asio/reference/read_at.html
HTML
gpl-2.0
16,915
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>strategy::transform::rotate_transformer</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="Chapter&#160;1.&#160;Geometry 1.0"> <link rel="up" href="../strategies.html" title="Strategies"> <link rel="prev" href="strategy_transform_map_transformer.html" title="strategy::transform::map_transformer"> <link rel="next" href="strategy_transform_scale_transformer.html" title="strategy::transform::scale_transformer"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="strategy_transform_map_transformer.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_transform_scale_transformer.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer"></a><a class="link" href="strategy_transform_rotate_transformer.html" title="strategy::transform::rotate_transformer">strategy::transform::rotate_transformer</a> </h4></div></div></div> <p> <a class="indexterm" name="id954360"></a><a class="indexterm" name="id954366"></a><a class="indexterm" name="id954371"></a> Strategy of rotate transformation in Cartesian system. </p> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h0"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.description"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.description">Description</a> </h6> <p> Rotate rotates a geometry of specified angle about a fixed point (e.g. origin). </p> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h1"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.synopsis"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.synopsis">Synopsis</a> </h6> <p> </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">P1</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">P2</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">DegreeOrRadian</span><span class="special">&gt;</span> <span class="keyword">class</span> <span class="identifier">strategy</span><span class="special">::</span><span class="identifier">transform</span><span class="special">::</span><span class="identifier">rotate_transformer</span> <span class="special">{</span> <span class="comment">// ...</span> <span class="special">};</span> </pre> <p> </p> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h2"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.template_parameter_s_"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.template_parameter_s_">Template parameter(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Parameter </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody> <tr> <td> <p> typename P1 </p> </td> <td> <p> first point type </p> </td> </tr> <tr> <td> <p> typename P2 </p> </td> <td> <p> second point type </p> </td> </tr> <tr> <td> <p> typename DegreeOrRadian </p> </td> <td> <p> degree/or/radian, type of rotation angle specification </p> </td> </tr> </tbody> </table></div> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h3"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.constructor_s_"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.constructor_s_">Constructor(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> <col> </colgroup> <thead><tr> <th> <p> Function </p> </th> <th> <p> Description </p> </th> <th> <p> Parameters </p> </th> </tr></thead> <tbody><tr> <td> <p> </p> <pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="identifier">rotate_transformer</span><span class="special">(</span><span class="identifier">angle_type</span> <span class="keyword">const</span> <span class="special">&amp;</span> <span class="identifier">angle</span><span class="special">)</span></pre> <p> </p> </td> <td> </td> <td> <p> <span class="bold"><strong>angle_type const &amp;</strong></span>: <span class="emphasis"><em>angle</em></span>: </p> </td> </tr></tbody> </table></div> <h6> <a name="geometry.reference.strategies.strategy_transform_rotate_transformer.h4"></a> <span><a name="geometry.reference.strategies.strategy_transform_rotate_transformer.header"></a></span><a class="link" href="strategy_transform_rotate_transformer.html#geometry.reference.strategies.strategy_transform_rotate_transformer.header">Header</a> </h6> <p> <code class="computeroutput"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">strategies</span><span class="special">/</span><span class="identifier">transform</span><span class="special">/</span><span class="identifier">matrix_transformers</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2011 Barend Gehrels, Bruno Lalande, Mateusz Loskot<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="strategy_transform_map_transformer.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../strategies.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="strategy_transform_scale_transformer.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
charlesDGY/coflo
coflo-0.0.4/third_party/boost_1_48_0/libs/geometry/doc/html/geometry/reference/strategies/strategy_transform_rotate_transformer.html
HTML
gpl-2.0
9,102
package visitors; /** * Created by stratosphr on 20/11/15. */ public interface IVisitedSort extends IVisited { Object accept(ISortVisitor visitor); }
stratosphr/Logic
src/visitors/IVisitedSort.java
Java
gpl-2.0
159
/* * aTunes * Copyright (C) Alex Aranda, Sylvain Gaudard and contributors * * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors * * http://www.atunes.org * http://sourceforge.net/projects/atunes * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package net.sourceforge.atunes.kernel.modules.navigator; import java.awt.Component; import java.util.List; import javax.swing.Action; import javax.swing.JMenu; import javax.swing.JMenuItem; import net.sourceforge.atunes.kernel.actions.CustomAbstractAction; import net.sourceforge.atunes.model.IAudioObject; import net.sourceforge.atunes.model.IPlayListHandler; import net.sourceforge.atunes.model.ITreeNode; /** * Enables or disables navigator actions given selection * * @author alex * */ public class NavigatorActionsStateController { private IPlayListHandler playListHandler; /** * @param playListHandler */ public void setPlayListHandler(final IPlayListHandler playListHandler) { this.playListHandler = playListHandler; } /** * Enables or disables tree popup actions * * @param rootSelected * @param components * @param nodes */ void updateTreePopupMenuWithTreeSelection(final boolean rootSelected, final Component[] components, final List<ITreeNode> nodes) { for (Component c : components) { updateMenuComponent(rootSelected, nodes, c); } } /** * Enables or disables table popup actions * * @param rootSelected * @param components * @param selection */ void updateTablePopupMenuWithTableSelection(final boolean rootSelected, final Component[] components, final List<IAudioObject> selection) { for (Component c : components) { updateTableMenuComponent(rootSelected, selection, c); } } /** * @param rootSelected * @param selection * @param c */ private void updateMenuComponent(final boolean rootSelected, final List<ITreeNode> selection, final Component c) { if (c != null) { if (c instanceof JMenu) { for (int i = 0; i < ((JMenu) c).getItemCount(); i++) { updateMenuComponent(rootSelected, selection, ((JMenu) c).getItem(i)); } } else if (c instanceof JMenuItem) { updateMenuItem(rootSelected, selection, (JMenuItem) c); } } } /** * @param rootSelected * @param selection * @param c */ private void updateTableMenuComponent(final boolean rootSelected, final List<IAudioObject> selection, final Component c) { if (c != null) { if (c instanceof JMenu) { for (int i = 0; i < ((JMenu) c).getItemCount(); i++) { updateTableMenuComponent(rootSelected, selection, ((JMenu) c).getItem(i)); } } else if (c instanceof JMenuItem) { updateTableMenuItem(rootSelected, selection, (JMenuItem) c); } } } /** * @param rootSelected * @param selection * @param menuItem */ private void updateMenuItem(final boolean rootSelected, final List<ITreeNode> selection, final JMenuItem menuItem) { Action a = menuItem.getAction(); if (a instanceof CustomAbstractAction) { CustomAbstractAction customAction = (CustomAbstractAction) a; if (!customAction.isEnabledForPlayList(this.playListHandler .getVisiblePlayList())) { customAction.setEnabled(false); } else { customAction.setEnabled(customAction .isEnabledForNavigationTreeSelection(rootSelected, selection)); } } } /** * @param rootSelected * @param selection * @param menuItem */ private void updateTableMenuItem(final boolean rootSelected, final List<IAudioObject> selection, final JMenuItem menuItem) { Action a = menuItem.getAction(); if (a instanceof CustomAbstractAction) { CustomAbstractAction customAction = (CustomAbstractAction) a; if (!customAction.isEnabledForPlayList(this.playListHandler .getVisiblePlayList())) { customAction.setEnabled(false); } else { customAction.setEnabled(customAction .isEnabledForNavigationTableSelection(selection)); } } } }
PDavid/aTunes
aTunes/src/main/java/net/sourceforge/atunes/kernel/modules/navigator/NavigatorActionsStateController.java
Java
gpl-2.0
4,445
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.mum.ea.mb; import edu.mum.ea.ejb.ProjectEJB; import edu.mum.ea.ejb.ReleaseBacklogEJB; import edu.mum.ea.ejb.SprintEJB; import edu.mum.ea.ejb.TaskEJB; import edu.mum.ea.entity.Project; import edu.mum.ea.entity.ReleaseBacklog; import edu.mum.ea.entity.Sprint; import edu.mum.ea.entity.Task; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; /** * * @author Syed */ @ManagedBean @RequestScoped public class SprintMB { private Sprint sprint; @EJB private SprintEJB sprintEJB; @EJB private ProjectEJB projectEJB; @EJB private ReleaseBacklogEJB releaseBacklogEJB; @EJB private TaskEJB taskEJB; @ManagedProperty(value = "#{sessionMB}") private SessionMB sessionMB; private List<Task> taskList = new ArrayList<Task>(); private List<ReleaseBacklog> releaseBacklogList = new ArrayList<ReleaseBacklog>(); private long relBacklogId; private List<String> selectedTasks = new ArrayList<String>(); private List<Sprint> sprintList; /** * Creates a new instance of ProjectMB */ public SprintMB() { sprint = new Sprint(); sprintList = new ArrayList<Sprint>(); } @PostConstruct public void init() { //Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); //Project project = projectEJB.find(sessionMB.getUserSelectedProject().getId()); releaseBacklogList = releaseBacklogEJB.findAllRelBakByProject(sessionMB.getUserSelectedProject().getId());//project.getReleaseBacklogList(); } public SessionMB getSessionMB() { return sessionMB; } public void setSessionMB(SessionMB sessionMB) { this.sessionMB = sessionMB; } public Sprint getSprint() { return sprint; } public void setSprint(Sprint sprint) { this.sprint = sprint; } public List<Sprint> getSprintList() { sprintList = sprintEJB.findAllSprintByProject(sessionMB.getUserSelectedProject().getId());//sprintEJB.findAll(); return sprintList; } public void setSprintList(List<Sprint> sprintList) { this.sprintList = sprintList; } public List<ReleaseBacklog> getReleaseBacklogList() { return releaseBacklogList; } public void setReleaseBacklogList(List<ReleaseBacklog> releaseBacklogList) { this.releaseBacklogList = releaseBacklogList; } public long getRelBacklogId() { return relBacklogId; } public void setRelBacklogId(long relBacklogId) { this.relBacklogId = relBacklogId; } public List<Task> getTaskList() { return taskList; } public void setTaskList(List<Task> taskList) { this.taskList = taskList; } public List<String> getSelectedTasks() { return selectedTasks; } public void setSelectedTasks(List<String> selectedTasks) { this.selectedTasks = selectedTasks; } public String createSprint() { sprint.setReleaseBacklog(releaseBacklogEJB.find(getRelBacklogId())); sprintEJB.save(sprint); return "sprint-list"; } public String gotoUpdatePage(Long id){ sprint = sprintEJB.find(id); try { setRelBacklogId(sprint.getReleaseBacklog().getId()); } catch(Exception e) { //System.out.println("-----" + e.getMessage()); } return "sprint-update"; } public String updateSprint(){ try { sprint.setReleaseBacklog(releaseBacklogEJB.find(getRelBacklogId())); } catch (Exception e) { //System.out.println("-----" + e.getMessage()); } sprintEJB.edit(sprint); return "sprint-list"; } public String deleteSprint(Long sprintId){ sprintEJB.delete(sprintId); return "sprint-list"; } public String sprintDetail(Long id) { sprint = sprintEJB.find(id); taskList = taskEJB.findAll(); for (Task t : sprint.getTasks()) { selectedTasks.add(t.getId().toString()); } return "sprint-view"; } public String addTaskToSprint() { long sprintId = sprint.getId(); sprint = sprintEJB.find(sprintId); taskList = sprint.getTasks(); int size = taskList.size(); for (int i = 0; i < size; i++) { taskList.remove(taskList.get(i)); size--; --i; } for (String taskId : selectedTasks) { if (!taskList.contains(taskEJB.find(Long.parseLong(taskId)))) { sprint.getTasks().add(taskEJB.find(Long.parseLong(taskId))); } } sprintEJB.edit(sprint); return "/sprint/sprint-list"; } }
ruzdi/ProjectManagement
ProjectManagement-war/src/java/edu/mum/ea/mb/SprintMB.java
Java
gpl-2.0
5,482
/* $Id$ */ /* * Copyright (C) 2013 Teluu Inc. (http://www.teluu.com) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjsua2/account.hpp> #include <pjsua2/endpoint.hpp> #include <pjsua2/presence.hpp> #include <pj/ctype.h> #include "util.hpp" using namespace pj; using namespace std; #define THIS_FILE "account.cpp" /////////////////////////////////////////////////////////////////////////////// void RtcpFbCap::fromPj(const pjmedia_rtcp_fb_cap &prm) { this->codecId = pj2Str(prm.codec_id); this->type = prm.type; this->typeName = pj2Str(prm.type_name); this->param = pj2Str(prm.param); } pjmedia_rtcp_fb_cap RtcpFbCap::toPj() const { pjmedia_rtcp_fb_cap cap; pj_bzero(&cap, sizeof(cap)); cap.codec_id = str2Pj(this->codecId); cap.type = this->type; cap.type_name = str2Pj(this->typeName); cap.param = str2Pj(this->param); return cap; } /////////////////////////////////////////////////////////////////////////////// RtcpFbConfig::RtcpFbConfig() { pjmedia_rtcp_fb_setting setting; pjmedia_rtcp_fb_setting_default(&setting); fromPj(setting); } void RtcpFbConfig::fromPj(const pjmedia_rtcp_fb_setting &prm) { this->dontUseAvpf = PJ2BOOL(prm.dont_use_avpf); this->caps.clear(); for (unsigned i = 0; i < prm.cap_count; ++i) { RtcpFbCap cap; cap.fromPj(prm.caps[i]); this->caps.push_back(cap); } } pjmedia_rtcp_fb_setting RtcpFbConfig::toPj() const { pjmedia_rtcp_fb_setting setting; pj_bzero(&setting, sizeof(setting)); setting.dont_use_avpf = this->dontUseAvpf; setting.cap_count = this->caps.size(); for (unsigned i = 0; i < setting.cap_count; ++i) { setting.caps[i] = this->caps[i].toPj(); } return setting; } void RtcpFbConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("RtcpFbConfig"); NODE_READ_BOOL (this_node, dontUseAvpf); ContainerNode cap_node = this_node.readArray("caps"); this->caps.clear(); while (cap_node.hasUnread()) { RtcpFbCap cap; NODE_READ_STRING (cap_node, cap.codecId); NODE_READ_NUM_T (cap_node, pjmedia_rtcp_fb_type, cap.type); NODE_READ_STRING (cap_node, cap.typeName); NODE_READ_STRING (cap_node, cap.param); this->caps.push_back(cap); } } void RtcpFbConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("RtcpFbConfig"); NODE_WRITE_BOOL (this_node, dontUseAvpf); ContainerNode cap_node = this_node.writeNewArray("caps"); for (unsigned i=0; i<this->caps.size(); ++i) { NODE_WRITE_STRING (cap_node, this->caps[i].codecId); NODE_WRITE_NUM_T (cap_node, pjmedia_rtcp_fb_type, this->caps[i].type); NODE_WRITE_STRING (cap_node, this->caps[i].typeName); NODE_WRITE_STRING (cap_node, this->caps[i].param); } } /////////////////////////////////////////////////////////////////////////////// void SrtpCrypto::fromPj(const pjmedia_srtp_crypto &prm) { this->key = pj2Str(prm.key); this->name = pj2Str(prm.name); this->flags = prm.flags; } pjmedia_srtp_crypto SrtpCrypto::toPj() const { pjmedia_srtp_crypto crypto; crypto.key = str2Pj(this->key); crypto.name = str2Pj(this->name); crypto.flags = this->flags; return crypto; } /////////////////////////////////////////////////////////////////////////////// SrtpOpt::SrtpOpt() { pjsua_srtp_opt opt; pjsua_srtp_opt_default(&opt); fromPj(opt); } void SrtpOpt::fromPj(const pjsua_srtp_opt &prm) { this->cryptos.clear(); for (unsigned i = 0; i < prm.crypto_count; ++i) { SrtpCrypto crypto; crypto.fromPj(prm.crypto[i]); this->cryptos.push_back(crypto); } this->keyings.clear(); for (unsigned i = 0; i < prm.keying_count; ++i) { this->keyings.push_back(prm.keying[i]); } } pjsua_srtp_opt SrtpOpt::toPj() const { pjsua_srtp_opt opt; pj_bzero(&opt, sizeof(opt)); opt.crypto_count = this->cryptos.size(); for (unsigned i = 0; i < opt.crypto_count; ++i) { opt.crypto[i] = this->cryptos[i].toPj(); } opt.keying_count = this->keyings.size(); for (unsigned i = 0; i < opt.keying_count; ++i) { opt.keying[i] = (pjmedia_srtp_keying_method)this->keyings[i]; } return opt; } void SrtpOpt::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("SrtpOpt"); ContainerNode crypto_node = this_node.readArray("cryptos"); this->cryptos.clear(); while (crypto_node.hasUnread()) { SrtpCrypto crypto; NODE_READ_STRING (crypto_node, crypto.key); NODE_READ_STRING (crypto_node, crypto.name); NODE_READ_UNSIGNED (crypto_node, crypto.flags); this->cryptos.push_back(crypto); } ContainerNode keying_node = this_node.readArray("keyings"); this->keyings.clear(); while (keying_node.hasUnread()) { unsigned keying; NODE_READ_UNSIGNED (keying_node, keying); this->keyings.push_back(keying); } } void SrtpOpt::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("SrtpOpt"); ContainerNode crypto_node = this_node.writeNewArray("cryptos"); for (unsigned i=0; i<this->cryptos.size(); ++i) { NODE_WRITE_STRING (crypto_node, this->cryptos[i].key); NODE_WRITE_STRING (crypto_node, this->cryptos[i].name); NODE_WRITE_UNSIGNED (crypto_node, this->cryptos[i].flags); } ContainerNode keying_node = this_node.writeNewArray("keyings"); for (unsigned i=0; i<this->keyings.size(); ++i) { NODE_WRITE_UNSIGNED (keying_node, this->keyings[i]); } } /////////////////////////////////////////////////////////////////////////////// void AccountRegConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountRegConfig"); NODE_READ_STRING (this_node, registrarUri); NODE_READ_BOOL (this_node, registerOnAdd); NODE_READ_UNSIGNED (this_node, timeoutSec); NODE_READ_UNSIGNED (this_node, retryIntervalSec); NODE_READ_UNSIGNED (this_node, firstRetryIntervalSec); NODE_READ_UNSIGNED (this_node, randomRetryIntervalSec); NODE_READ_UNSIGNED (this_node, delayBeforeRefreshSec); NODE_READ_BOOL (this_node, dropCallsOnFail); NODE_READ_UNSIGNED (this_node, unregWaitMsec); NODE_READ_UNSIGNED (this_node, proxyUse); NODE_READ_STRING (this_node, contactParams); readSipHeaders(this_node, "headers", headers); } void AccountRegConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountRegConfig"); NODE_WRITE_STRING (this_node, registrarUri); NODE_WRITE_BOOL (this_node, registerOnAdd); NODE_WRITE_UNSIGNED (this_node, timeoutSec); NODE_WRITE_UNSIGNED (this_node, retryIntervalSec); NODE_WRITE_UNSIGNED (this_node, firstRetryIntervalSec); NODE_WRITE_UNSIGNED (this_node, randomRetryIntervalSec); NODE_WRITE_UNSIGNED (this_node, delayBeforeRefreshSec); NODE_WRITE_BOOL (this_node, dropCallsOnFail); NODE_WRITE_UNSIGNED (this_node, unregWaitMsec); NODE_WRITE_UNSIGNED (this_node, proxyUse); NODE_WRITE_STRING (this_node, contactParams); writeSipHeaders(this_node, "headers", headers); } /////////////////////////////////////////////////////////////////////////////// void AccountSipConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountSipConfig"); NODE_READ_STRINGV (this_node, proxies); NODE_READ_STRING (this_node, contactForced); NODE_READ_STRING (this_node, contactParams); NODE_READ_STRING (this_node, contactUriParams); NODE_READ_BOOL (this_node, authInitialEmpty); NODE_READ_STRING (this_node, authInitialAlgorithm); NODE_READ_INT (this_node, transportId); ContainerNode creds_node = this_node.readArray("authCreds"); authCreds.resize(0); while (creds_node.hasUnread()) { AuthCredInfo cred; cred.readObject(creds_node); authCreds.push_back(cred); } } void AccountSipConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountSipConfig"); NODE_WRITE_STRINGV (this_node, proxies); NODE_WRITE_STRING (this_node, contactForced); NODE_WRITE_STRING (this_node, contactParams); NODE_WRITE_STRING (this_node, contactUriParams); NODE_WRITE_BOOL (this_node, authInitialEmpty); NODE_WRITE_STRING (this_node, authInitialAlgorithm); NODE_WRITE_INT (this_node, transportId); ContainerNode creds_node = this_node.writeNewArray("authCreds"); for (unsigned i=0; i<authCreds.size(); ++i) { authCreds[i].writeObject(creds_node); } } /////////////////////////////////////////////////////////////////////////////// void AccountCallConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountCallConfig"); NODE_READ_NUM_T ( this_node, pjsua_call_hold_type, holdType); NODE_READ_NUM_T ( this_node, pjsua_100rel_use, prackUse); NODE_READ_NUM_T ( this_node, pjsua_sip_timer_use, timerUse); NODE_READ_UNSIGNED( this_node, timerMinSESec); NODE_READ_UNSIGNED( this_node, timerSessExpiresSec); } void AccountCallConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountCallConfig"); NODE_WRITE_NUM_T ( this_node, pjsua_call_hold_type, holdType); NODE_WRITE_NUM_T ( this_node, pjsua_100rel_use, prackUse); NODE_WRITE_NUM_T ( this_node, pjsua_sip_timer_use, timerUse); NODE_WRITE_UNSIGNED( this_node, timerMinSESec); NODE_WRITE_UNSIGNED( this_node, timerSessExpiresSec); } /////////////////////////////////////////////////////////////////////////////// void AccountPresConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountPresConfig"); NODE_READ_BOOL ( this_node, publishEnabled); NODE_READ_BOOL ( this_node, publishQueue); NODE_READ_UNSIGNED( this_node, publishShutdownWaitMsec); NODE_READ_STRING ( this_node, pidfTupleId); readSipHeaders(this_node, "headers", headers); } void AccountPresConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountPresConfig"); NODE_WRITE_BOOL ( this_node, publishEnabled); NODE_WRITE_BOOL ( this_node, publishQueue); NODE_WRITE_UNSIGNED( this_node, publishShutdownWaitMsec); NODE_WRITE_STRING ( this_node, pidfTupleId); writeSipHeaders(this_node, "headers", headers); } /////////////////////////////////////////////////////////////////////////////// void AccountMwiConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountMwiConfig"); NODE_READ_BOOL ( this_node, enabled); NODE_READ_UNSIGNED( this_node, expirationSec); } void AccountMwiConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountMwiConfig"); NODE_WRITE_BOOL ( this_node, enabled); NODE_WRITE_UNSIGNED( this_node, expirationSec); } /////////////////////////////////////////////////////////////////////////////// void AccountNatConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountNatConfig"); NODE_READ_NUM_T ( this_node, pjsua_stun_use, sipStunUse); NODE_READ_NUM_T ( this_node, pjsua_stun_use, mediaStunUse); NODE_READ_NUM_T ( this_node, pjsua_nat64_opt, nat64Opt); NODE_READ_BOOL ( this_node, iceEnabled); NODE_READ_INT ( this_node, iceMaxHostCands); NODE_READ_BOOL ( this_node, iceAggressiveNomination); NODE_READ_UNSIGNED( this_node, iceNominatedCheckDelayMsec); NODE_READ_INT ( this_node, iceWaitNominationTimeoutMsec); NODE_READ_BOOL ( this_node, iceNoRtcp); NODE_READ_BOOL ( this_node, iceAlwaysUpdate); NODE_READ_BOOL ( this_node, turnEnabled); NODE_READ_STRING ( this_node, turnServer); NODE_READ_NUM_T ( this_node, pj_turn_tp_type, turnConnType); NODE_READ_STRING ( this_node, turnUserName); NODE_READ_INT ( this_node, turnPasswordType); NODE_READ_STRING ( this_node, turnPassword); NODE_READ_INT ( this_node, contactRewriteUse); NODE_READ_INT ( this_node, contactRewriteMethod); NODE_READ_INT ( this_node, viaRewriteUse); NODE_READ_INT ( this_node, sdpNatRewriteUse); NODE_READ_INT ( this_node, sipOutboundUse); NODE_READ_STRING ( this_node, sipOutboundInstanceId); NODE_READ_STRING ( this_node, sipOutboundRegId); NODE_READ_UNSIGNED( this_node, udpKaIntervalSec); NODE_READ_STRING ( this_node, udpKaData); NODE_READ_INT ( this_node, contactUseSrcPort); } void AccountNatConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountNatConfig"); NODE_WRITE_NUM_T ( this_node, pjsua_stun_use, sipStunUse); NODE_WRITE_NUM_T ( this_node, pjsua_stun_use, mediaStunUse); NODE_WRITE_NUM_T ( this_node, pjsua_nat64_opt, nat64Opt); NODE_WRITE_BOOL ( this_node, iceEnabled); NODE_WRITE_INT ( this_node, iceMaxHostCands); NODE_WRITE_BOOL ( this_node, iceAggressiveNomination); NODE_WRITE_UNSIGNED( this_node, iceNominatedCheckDelayMsec); NODE_WRITE_INT ( this_node, iceWaitNominationTimeoutMsec); NODE_WRITE_BOOL ( this_node, iceNoRtcp); NODE_WRITE_BOOL ( this_node, iceAlwaysUpdate); NODE_WRITE_BOOL ( this_node, turnEnabled); NODE_WRITE_STRING ( this_node, turnServer); NODE_WRITE_NUM_T ( this_node, pj_turn_tp_type, turnConnType); NODE_WRITE_STRING ( this_node, turnUserName); NODE_WRITE_INT ( this_node, turnPasswordType); NODE_WRITE_STRING ( this_node, turnPassword); NODE_WRITE_INT ( this_node, contactRewriteUse); NODE_WRITE_INT ( this_node, contactRewriteMethod); NODE_WRITE_INT ( this_node, viaRewriteUse); NODE_WRITE_INT ( this_node, sdpNatRewriteUse); NODE_WRITE_INT ( this_node, sipOutboundUse); NODE_WRITE_STRING ( this_node, sipOutboundInstanceId); NODE_WRITE_STRING ( this_node, sipOutboundRegId); NODE_WRITE_UNSIGNED( this_node, udpKaIntervalSec); NODE_WRITE_STRING ( this_node, udpKaData); NODE_WRITE_INT ( this_node, contactUseSrcPort); } /////////////////////////////////////////////////////////////////////////////// void AccountMediaConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountMediaConfig"); NODE_READ_BOOL ( this_node, lockCodecEnabled); NODE_READ_BOOL ( this_node, streamKaEnabled); NODE_READ_NUM_T ( this_node, pjmedia_srtp_use, srtpUse); NODE_READ_INT ( this_node, srtpSecureSignaling); NODE_READ_OBJ ( this_node, srtpOpt); NODE_READ_NUM_T ( this_node, pjsua_ipv6_use, ipv6Use); NODE_READ_OBJ ( this_node, transportConfig); NODE_READ_BOOL ( this_node, rtcpMuxEnabled); } void AccountMediaConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountMediaConfig"); NODE_WRITE_BOOL ( this_node, lockCodecEnabled); NODE_WRITE_BOOL ( this_node, streamKaEnabled); NODE_WRITE_NUM_T ( this_node, pjmedia_srtp_use, srtpUse); NODE_WRITE_INT ( this_node, srtpSecureSignaling); NODE_WRITE_OBJ ( this_node, srtpOpt); NODE_WRITE_NUM_T ( this_node, pjsua_ipv6_use, ipv6Use); NODE_WRITE_OBJ ( this_node, transportConfig); NODE_WRITE_BOOL ( this_node, rtcpMuxEnabled); } /////////////////////////////////////////////////////////////////////////////// void AccountVideoConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountVideoConfig"); NODE_READ_BOOL ( this_node, autoShowIncoming); NODE_READ_BOOL ( this_node, autoTransmitOutgoing); NODE_READ_UNSIGNED( this_node, windowFlags); NODE_READ_NUM_T ( this_node, pjmedia_vid_dev_index, defaultCaptureDevice); NODE_READ_NUM_T ( this_node, pjmedia_vid_dev_index, defaultRenderDevice); NODE_READ_NUM_T ( this_node, pjmedia_vid_stream_rc_method, rateControlMethod); NODE_READ_UNSIGNED( this_node, rateControlBandwidth); NODE_READ_UNSIGNED( this_node, startKeyframeCount); NODE_READ_UNSIGNED( this_node, startKeyframeInterval); } void AccountVideoConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountVideoConfig"); NODE_WRITE_BOOL ( this_node, autoShowIncoming); NODE_WRITE_BOOL ( this_node, autoTransmitOutgoing); NODE_WRITE_UNSIGNED( this_node, windowFlags); NODE_WRITE_NUM_T ( this_node, pjmedia_vid_dev_index, defaultCaptureDevice); NODE_WRITE_NUM_T ( this_node, pjmedia_vid_dev_index, defaultRenderDevice); NODE_WRITE_NUM_T ( this_node, pjmedia_vid_stream_rc_method, rateControlMethod); NODE_WRITE_UNSIGNED( this_node, rateControlBandwidth); NODE_WRITE_UNSIGNED( this_node, startKeyframeCount); NODE_WRITE_UNSIGNED( this_node, startKeyframeInterval); } /////////////////////////////////////////////////////////////////////////////// void AccountIpChangeConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountIpChangeConfig"); NODE_READ_BOOL ( this_node, shutdownTp); NODE_READ_BOOL ( this_node, hangupCalls); NODE_READ_UNSIGNED( this_node, reinviteFlags); } void AccountIpChangeConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountIpChangeConfig"); NODE_WRITE_BOOL ( this_node, shutdownTp); NODE_WRITE_BOOL ( this_node, hangupCalls); NODE_WRITE_UNSIGNED( this_node, reinviteFlags); } /////////////////////////////////////////////////////////////////////////////// AccountConfig::AccountConfig() { pjsua_acc_config acc_cfg; pjsua_acc_config_default(&acc_cfg); pjsua_media_config med_cfg; pjsua_media_config_default(&med_cfg); fromPj(acc_cfg, &med_cfg); } /* Convert to pjsip. */ void AccountConfig::toPj(pjsua_acc_config &ret) const { unsigned i; pjsua_acc_config_default(&ret); // Global ret.priority = priority; ret.id = str2Pj(idUri); // AccountRegConfig ret.reg_uri = str2Pj(regConfig.registrarUri); ret.register_on_acc_add = regConfig.registerOnAdd; ret.reg_timeout = regConfig.timeoutSec; ret.reg_retry_interval = regConfig.retryIntervalSec; ret.reg_first_retry_interval= regConfig.firstRetryIntervalSec; ret.reg_retry_random_interval= regConfig.randomRetryIntervalSec; ret.reg_delay_before_refresh= regConfig.delayBeforeRefreshSec; ret.drop_calls_on_reg_fail = regConfig.dropCallsOnFail; ret.unreg_timeout = regConfig.unregWaitMsec; ret.reg_use_proxy = regConfig.proxyUse; ret.reg_contact_params = str2Pj(regConfig.contactParams); for (i=0; i<regConfig.headers.size(); ++i) { pj_list_push_back(&ret.reg_hdr_list, &regConfig.headers[i].toPj()); } // AccountSipConfig ret.cred_count = 0; if (sipConfig.authCreds.size() > PJ_ARRAY_SIZE(ret.cred_info)) PJSUA2_RAISE_ERROR(PJ_ETOOMANY); for (i=0; i<sipConfig.authCreds.size(); ++i) { const AuthCredInfo &src = sipConfig.authCreds[i]; pjsip_cred_info *dst = &ret.cred_info[i]; dst->realm = str2Pj(src.realm); dst->scheme = str2Pj(src.scheme); dst->username = str2Pj(src.username); dst->data_type = src.dataType; dst->data = str2Pj(src.data); dst->ext.aka.k = str2Pj(src.akaK); dst->ext.aka.op = str2Pj(src.akaOp); dst->ext.aka.amf= str2Pj(src.akaAmf); ret.cred_count++; } ret.proxy_cnt = 0; if (sipConfig.proxies.size() > PJ_ARRAY_SIZE(ret.proxy)) PJSUA2_RAISE_ERROR(PJ_ETOOMANY); for (i=0; i<sipConfig.proxies.size(); ++i) { ret.proxy[ret.proxy_cnt++] = str2Pj(sipConfig.proxies[i]); } ret.force_contact = str2Pj(sipConfig.contactForced); ret.contact_params = str2Pj(sipConfig.contactParams); ret.contact_uri_params = str2Pj(sipConfig.contactUriParams); ret.auth_pref.initial_auth = sipConfig.authInitialEmpty; ret.auth_pref.algorithm = str2Pj(sipConfig.authInitialAlgorithm); ret.transport_id = sipConfig.transportId; // AccountCallConfig ret.call_hold_type = callConfig.holdType; ret.require_100rel = callConfig.prackUse; ret.use_timer = callConfig.timerUse; ret.timer_setting.min_se = callConfig.timerMinSESec; ret.timer_setting.sess_expires = callConfig.timerSessExpiresSec; // AccountPresConfig for (i=0; i<presConfig.headers.size(); ++i) { pj_list_push_back(&ret.sub_hdr_list, &presConfig.headers[i].toPj()); } ret.publish_enabled = presConfig.publishEnabled; ret.publish_opt.queue_request= presConfig.publishQueue; ret.unpublish_max_wait_time_msec = presConfig.publishShutdownWaitMsec; ret.pidf_tuple_id = str2Pj(presConfig.pidfTupleId); // AccountMwiConfig ret.mwi_enabled = mwiConfig.enabled; ret.mwi_expires = mwiConfig.expirationSec; // AccountNatConfig ret.sip_stun_use = natConfig.sipStunUse; ret.media_stun_use = natConfig.mediaStunUse; ret.nat64_opt = natConfig.nat64Opt; ret.ice_cfg_use = PJSUA_ICE_CONFIG_USE_CUSTOM; ret.ice_cfg.enable_ice = natConfig.iceEnabled; ret.ice_cfg.ice_max_host_cands = natConfig.iceMaxHostCands; ret.ice_cfg.ice_opt.aggressive = natConfig.iceAggressiveNomination; ret.ice_cfg.ice_opt.nominated_check_delay = natConfig.iceNominatedCheckDelayMsec; ret.ice_cfg.ice_opt.controlled_agent_want_nom_timeout = natConfig.iceWaitNominationTimeoutMsec; ret.ice_cfg.ice_no_rtcp = natConfig.iceNoRtcp; ret.ice_cfg.ice_always_update = natConfig.iceAlwaysUpdate; ret.turn_cfg_use = PJSUA_TURN_CONFIG_USE_CUSTOM; ret.turn_cfg.enable_turn = natConfig.turnEnabled; ret.turn_cfg.turn_server = str2Pj(natConfig.turnServer); ret.turn_cfg.turn_conn_type = natConfig.turnConnType; ret.turn_cfg.turn_auth_cred.type = PJ_STUN_AUTH_CRED_STATIC; ret.turn_cfg.turn_auth_cred.data.static_cred.username = str2Pj(natConfig.turnUserName); ret.turn_cfg.turn_auth_cred.data.static_cred.data_type = (pj_stun_passwd_type)natConfig.turnPasswordType; ret.turn_cfg.turn_auth_cred.data.static_cred.data = str2Pj(natConfig.turnPassword); ret.turn_cfg.turn_auth_cred.data.static_cred.realm = pj_str((char*)""); ret.turn_cfg.turn_auth_cred.data.static_cred.nonce = pj_str((char*)""); ret.allow_contact_rewrite = natConfig.contactRewriteUse; ret.contact_rewrite_method = natConfig.contactRewriteMethod; ret.contact_use_src_port = natConfig.contactUseSrcPort; ret.allow_via_rewrite = natConfig.viaRewriteUse; ret.allow_sdp_nat_rewrite = natConfig.sdpNatRewriteUse; ret.use_rfc5626 = natConfig.sipOutboundUse; ret.rfc5626_instance_id = str2Pj(natConfig.sipOutboundInstanceId); ret.rfc5626_reg_id = str2Pj(natConfig.sipOutboundRegId); ret.ka_interval = natConfig.udpKaIntervalSec; ret.ka_data = str2Pj(natConfig.udpKaData); // AccountMediaConfig ret.rtp_cfg = mediaConfig.transportConfig.toPj(); ret.lock_codec = mediaConfig.lockCodecEnabled; #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) ret.use_stream_ka = mediaConfig.streamKaEnabled; #endif ret.use_srtp = mediaConfig.srtpUse; ret.srtp_secure_signaling = mediaConfig.srtpSecureSignaling; ret.srtp_opt = mediaConfig.srtpOpt.toPj(); ret.ipv6_media_use = mediaConfig.ipv6Use; ret.enable_rtcp_mux = mediaConfig.rtcpMuxEnabled; ret.rtcp_fb_cfg = mediaConfig.rtcpFbConfig.toPj(); // AccountVideoConfig ret.vid_in_auto_show = videoConfig.autoShowIncoming; ret.vid_out_auto_transmit = videoConfig.autoTransmitOutgoing; ret.vid_wnd_flags = videoConfig.windowFlags; ret.vid_cap_dev = videoConfig.defaultCaptureDevice; ret.vid_rend_dev = videoConfig.defaultRenderDevice; ret.vid_stream_rc_cfg.method= videoConfig.rateControlMethod; ret.vid_stream_rc_cfg.bandwidth = videoConfig.rateControlBandwidth; ret.vid_stream_sk_cfg.count = videoConfig.startKeyframeCount; ret.vid_stream_sk_cfg.interval = videoConfig.startKeyframeInterval; // AccountIpChangeConfig ret.ip_change_cfg.shutdown_tp = ipChangeConfig.shutdownTp; ret.ip_change_cfg.hangup_calls = ipChangeConfig.hangupCalls; ret.ip_change_cfg.reinvite_flags = ipChangeConfig.reinviteFlags; } /* Initialize from pjsip. */ void AccountConfig::fromPj(const pjsua_acc_config &prm, const pjsua_media_config *mcfg) { const pjsip_hdr *hdr; unsigned i; // Global priority = prm.priority; idUri = pj2Str(prm.id); // AccountRegConfig regConfig.registrarUri = pj2Str(prm.reg_uri); regConfig.registerOnAdd = (prm.register_on_acc_add != 0); regConfig.timeoutSec = prm.reg_timeout; regConfig.retryIntervalSec = prm.reg_retry_interval; regConfig.firstRetryIntervalSec = prm.reg_first_retry_interval; regConfig.randomRetryIntervalSec = prm.reg_retry_random_interval; regConfig.delayBeforeRefreshSec = prm.reg_delay_before_refresh; regConfig.dropCallsOnFail = PJ2BOOL(prm.drop_calls_on_reg_fail); regConfig.unregWaitMsec = prm.unreg_timeout; regConfig.proxyUse = prm.reg_use_proxy; regConfig.contactParams = pj2Str(prm.reg_contact_params); regConfig.headers.clear(); hdr = prm.reg_hdr_list.next; while (hdr != &prm.reg_hdr_list) { SipHeader new_hdr; new_hdr.fromPj(hdr); regConfig.headers.push_back(new_hdr); hdr = hdr->next; } // AccountSipConfig sipConfig.authCreds.clear(); for (i=0; i<prm.cred_count; ++i) { AuthCredInfo cred; const pjsip_cred_info &src = prm.cred_info[i]; cred.realm = pj2Str(src.realm); cred.scheme = pj2Str(src.scheme); cred.username = pj2Str(src.username); cred.dataType = src.data_type; cred.data = pj2Str(src.data); cred.akaK = pj2Str(src.ext.aka.k); cred.akaOp = pj2Str(src.ext.aka.op); cred.akaAmf = pj2Str(src.ext.aka.amf); sipConfig.authCreds.push_back(cred); } sipConfig.proxies.clear(); for (i=0; i<prm.proxy_cnt; ++i) { sipConfig.proxies.push_back(pj2Str(prm.proxy[i])); } sipConfig.contactForced = pj2Str(prm.force_contact); sipConfig.contactParams = pj2Str(prm.contact_params); sipConfig.contactUriParams = pj2Str(prm.contact_uri_params); sipConfig.authInitialEmpty = PJ2BOOL(prm.auth_pref.initial_auth); sipConfig.authInitialAlgorithm = pj2Str(prm.auth_pref.algorithm); sipConfig.transportId = prm.transport_id; // AccountCallConfig callConfig.holdType = prm.call_hold_type; callConfig.prackUse = prm.require_100rel; callConfig.timerUse = prm.use_timer; callConfig.timerMinSESec = prm.timer_setting.min_se; callConfig.timerSessExpiresSec = prm.timer_setting.sess_expires; // AccountPresConfig presConfig.headers.clear(); hdr = prm.sub_hdr_list.next; while (hdr != &prm.sub_hdr_list) { SipHeader new_hdr; new_hdr.fromPj(hdr); presConfig.headers.push_back(new_hdr); hdr = hdr->next; } presConfig.publishEnabled = PJ2BOOL(prm.publish_enabled); presConfig.publishQueue = PJ2BOOL(prm.publish_opt.queue_request); presConfig.publishShutdownWaitMsec = prm.unpublish_max_wait_time_msec; presConfig.pidfTupleId = pj2Str(prm.pidf_tuple_id); // AccountMwiConfig mwiConfig.enabled = PJ2BOOL(prm.mwi_enabled); mwiConfig.expirationSec = prm.mwi_expires; // AccountNatConfig natConfig.sipStunUse = prm.sip_stun_use; natConfig.mediaStunUse = prm.media_stun_use; natConfig.nat64Opt = prm.nat64_opt; if (prm.ice_cfg_use == PJSUA_ICE_CONFIG_USE_CUSTOM) { natConfig.iceEnabled = PJ2BOOL(prm.ice_cfg.enable_ice); natConfig.iceMaxHostCands = prm.ice_cfg.ice_max_host_cands; natConfig.iceAggressiveNomination = PJ2BOOL(prm.ice_cfg.ice_opt.aggressive); natConfig.iceNominatedCheckDelayMsec = prm.ice_cfg.ice_opt.nominated_check_delay; natConfig.iceWaitNominationTimeoutMsec = prm.ice_cfg.ice_opt.controlled_agent_want_nom_timeout; natConfig.iceNoRtcp = PJ2BOOL(prm.ice_cfg.ice_no_rtcp); natConfig.iceAlwaysUpdate = PJ2BOOL(prm.ice_cfg.ice_always_update); } else { pjsua_media_config default_mcfg; if (!mcfg) { pjsua_media_config_default(&default_mcfg); mcfg = &default_mcfg; } natConfig.iceEnabled = PJ2BOOL(mcfg->enable_ice); natConfig.iceMaxHostCands= mcfg->ice_max_host_cands; natConfig.iceAggressiveNomination = PJ2BOOL(mcfg->ice_opt.aggressive); natConfig.iceNominatedCheckDelayMsec = mcfg->ice_opt.nominated_check_delay; natConfig.iceWaitNominationTimeoutMsec = mcfg->ice_opt.controlled_agent_want_nom_timeout; natConfig.iceNoRtcp = PJ2BOOL(mcfg->ice_no_rtcp); natConfig.iceAlwaysUpdate = PJ2BOOL(mcfg->ice_always_update); } if (prm.turn_cfg_use == PJSUA_TURN_CONFIG_USE_CUSTOM) { natConfig.turnEnabled = PJ2BOOL(prm.turn_cfg.enable_turn); natConfig.turnServer = pj2Str(prm.turn_cfg.turn_server); natConfig.turnConnType = prm.turn_cfg.turn_conn_type; natConfig.turnUserName = pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.username); natConfig.turnPasswordType = prm.turn_cfg.turn_auth_cred.data.static_cred.data_type; natConfig.turnPassword = pj2Str(prm.turn_cfg.turn_auth_cred.data.static_cred.data); } else { pjsua_media_config default_mcfg; if (!mcfg) { pjsua_media_config_default(&default_mcfg); mcfg = &default_mcfg; } natConfig.turnEnabled = PJ2BOOL(mcfg->enable_turn); natConfig.turnServer = pj2Str(mcfg->turn_server); natConfig.turnConnType = mcfg->turn_conn_type; natConfig.turnUserName = pj2Str(mcfg->turn_auth_cred.data.static_cred.username); natConfig.turnPasswordType = mcfg->turn_auth_cred.data.static_cred.data_type; natConfig.turnPassword = pj2Str(mcfg->turn_auth_cred.data.static_cred.data); } natConfig.contactRewriteUse = prm.allow_contact_rewrite; natConfig.contactRewriteMethod = prm.contact_rewrite_method; natConfig.contactUseSrcPort = prm.contact_use_src_port; natConfig.viaRewriteUse = prm.allow_via_rewrite; natConfig.sdpNatRewriteUse = prm.allow_sdp_nat_rewrite; natConfig.sipOutboundUse = prm.use_rfc5626; natConfig.sipOutboundInstanceId = pj2Str(prm.rfc5626_instance_id); natConfig.sipOutboundRegId = pj2Str(prm.rfc5626_reg_id); natConfig.udpKaIntervalSec = prm.ka_interval; natConfig.udpKaData = pj2Str(prm.ka_data); // AccountMediaConfig mediaConfig.transportConfig.fromPj(prm.rtp_cfg); mediaConfig.lockCodecEnabled= PJ2BOOL(prm.lock_codec); #if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0) mediaConfig.streamKaEnabled = PJ2BOOL(prm.use_stream_ka); #else mediaConfig.streamKaEnabled = false; #endif mediaConfig.srtpUse = prm.use_srtp; mediaConfig.srtpSecureSignaling = prm.srtp_secure_signaling; mediaConfig.srtpOpt.fromPj(prm.srtp_opt); mediaConfig.ipv6Use = prm.ipv6_media_use; mediaConfig.rtcpMuxEnabled = PJ2BOOL(prm.enable_rtcp_mux); mediaConfig.rtcpFbConfig.fromPj(prm.rtcp_fb_cfg); // AccountVideoConfig videoConfig.autoShowIncoming = PJ2BOOL(prm.vid_in_auto_show); videoConfig.autoTransmitOutgoing = PJ2BOOL(prm.vid_out_auto_transmit); videoConfig.windowFlags = prm.vid_wnd_flags; videoConfig.defaultCaptureDevice = prm.vid_cap_dev; videoConfig.defaultRenderDevice = prm.vid_rend_dev; videoConfig.rateControlMethod = prm.vid_stream_rc_cfg.method; videoConfig.rateControlBandwidth = prm.vid_stream_rc_cfg.bandwidth; videoConfig.startKeyframeCount = prm.vid_stream_sk_cfg.count; videoConfig.startKeyframeInterval = prm.vid_stream_sk_cfg.interval; // AccountIpChangeConfig ipChangeConfig.shutdownTp = PJ2BOOL(prm.ip_change_cfg.shutdown_tp); ipChangeConfig.hangupCalls = PJ2BOOL(prm.ip_change_cfg.hangup_calls); ipChangeConfig.reinviteFlags = prm.ip_change_cfg.reinvite_flags; } void AccountConfig::readObject(const ContainerNode &node) PJSUA2_THROW(Error) { ContainerNode this_node = node.readContainer("AccountConfig"); NODE_READ_INT ( this_node, priority); NODE_READ_STRING ( this_node, idUri); NODE_READ_OBJ ( this_node, regConfig); NODE_READ_OBJ ( this_node, sipConfig); NODE_READ_OBJ ( this_node, callConfig); NODE_READ_OBJ ( this_node, presConfig); NODE_READ_OBJ ( this_node, mwiConfig); NODE_READ_OBJ ( this_node, natConfig); NODE_READ_OBJ ( this_node, mediaConfig); NODE_READ_OBJ ( this_node, videoConfig); } void AccountConfig::writeObject(ContainerNode &node) const PJSUA2_THROW(Error) { ContainerNode this_node = node.writeNewContainer("AccountConfig"); NODE_WRITE_INT ( this_node, priority); NODE_WRITE_STRING ( this_node, idUri); NODE_WRITE_OBJ ( this_node, regConfig); NODE_WRITE_OBJ ( this_node, sipConfig); NODE_WRITE_OBJ ( this_node, callConfig); NODE_WRITE_OBJ ( this_node, presConfig); NODE_WRITE_OBJ ( this_node, mwiConfig); NODE_WRITE_OBJ ( this_node, natConfig); NODE_WRITE_OBJ ( this_node, mediaConfig); NODE_WRITE_OBJ ( this_node, videoConfig); } /////////////////////////////////////////////////////////////////////////////// void AccountInfo::fromPj(const pjsua_acc_info &pai) { id = pai.id; isDefault = pai.is_default != 0; uri = pj2Str(pai.acc_uri); regIsConfigured = pai.has_registration != 0; regIsActive = pai.has_registration && pai.expires > 0 && (pai.status / 100 == 2); regExpiresSec = pai.expires; regStatus = pai.status; regStatusText = pj2Str(pai.status_text); regLastErr = pai.reg_last_err; onlineStatus = pai.online_status != 0; onlineStatusText = pj2Str(pai.online_status_text); } /////////////////////////////////////////////////////////////////////////////// Account::Account() : id(PJSUA_INVALID_ID) { } Account::~Account() { /* If this instance is deleted, also delete the corresponding account in * PJSUA library. */ shutdown(); } void Account::create(const AccountConfig &acc_cfg, bool make_default) PJSUA2_THROW(Error) { pjsua_acc_config pj_acc_cfg; acc_cfg.toPj(pj_acc_cfg); pj_acc_cfg.user_data = (void*)this; PJSUA2_CHECK_EXPR( pjsua_acc_add(&pj_acc_cfg, make_default, &id) ); } void Account::shutdown() { if (isValid() && pjsua_get_state() < PJSUA_STATE_CLOSING) { // Cleanup buddies in the buddy list while(buddyList.size() > 0) { Buddy *b = buddyList[0]; delete b; /* this will remove itself from the list */ } // This caused error message of "Error: cannot find Account.." // when Endpoint::on_reg_started() is called for unregistration. //pjsua_acc_set_user_data(id, NULL); pjsua_acc_del(id); } } void Account::modify(const AccountConfig &acc_cfg) PJSUA2_THROW(Error) { pjsua_acc_config pj_acc_cfg; acc_cfg.toPj(pj_acc_cfg); pj_acc_cfg.user_data = (void*)this; PJSUA2_CHECK_EXPR( pjsua_acc_modify(id, &pj_acc_cfg) ); } bool Account::isValid() const { return pjsua_acc_is_valid(id) != 0; } void Account::setDefault() PJSUA2_THROW(Error) { PJSUA2_CHECK_EXPR( pjsua_acc_set_default(id) ); } bool Account::isDefault() const { return pjsua_acc_get_default() == id; } int Account::getId() const { return id; } Account *Account::lookup(int acc_id) { return (Account*)pjsua_acc_get_user_data(acc_id); } AccountInfo Account::getInfo() const PJSUA2_THROW(Error) { pjsua_acc_info pj_ai; AccountInfo ai; PJSUA2_CHECK_EXPR( pjsua_acc_get_info(id, &pj_ai) ); ai.fromPj(pj_ai); return ai; } void Account::setRegistration(bool renew) PJSUA2_THROW(Error) { PJSUA2_CHECK_EXPR( pjsua_acc_set_registration(id, renew) ); } void Account::setOnlineStatus(const PresenceStatus &pres_st) PJSUA2_THROW(Error) { pjrpid_element pj_rpid; pj_bzero(&pj_rpid, sizeof(pj_rpid)); pj_rpid.type = PJRPID_ELEMENT_TYPE_PERSON; pj_rpid.activity = pres_st.activity; pj_rpid.id = str2Pj(pres_st.rpidId); pj_rpid.note = str2Pj(pres_st.note); PJSUA2_CHECK_EXPR( pjsua_acc_set_online_status2( id, pres_st.status == PJSUA_BUDDY_STATUS_ONLINE, &pj_rpid) ); } void Account::setTransport(TransportId tp_id) PJSUA2_THROW(Error) { PJSUA2_CHECK_EXPR( pjsua_acc_set_transport(id, tp_id) ); } void Account::presNotify(const PresNotifyParam &prm) PJSUA2_THROW(Error) { pj_str_t pj_state_str = str2Pj(prm.stateStr); pj_str_t pj_reason = str2Pj(prm.reason); pjsua_msg_data msg_data; prm.txOption.toPj(msg_data); PJSUA2_CHECK_EXPR( pjsua_pres_notify(id, (pjsua_srv_pres*)prm.srvPres, prm.state, &pj_state_str, &pj_reason, prm.withBody, &msg_data) ); } const BuddyVector& Account::enumBuddies() const PJSUA2_THROW(Error) { return buddyList; } BuddyVector2 Account::enumBuddies2() const PJSUA2_THROW(Error) { BuddyVector2 bv2; pjsua_buddy_id ids[PJSUA_MAX_BUDDIES]; unsigned i, count = PJSUA_MAX_BUDDIES; PJSUA2_CHECK_EXPR( pjsua_enum_buddies(ids, &count) ); for (i = 0; i < count; ++i) { bv2.push_back(Buddy(ids[i])); } return bv2; } Buddy* Account::findBuddy(string uri, FindBuddyMatch *buddy_match) const PJSUA2_THROW(Error) { if (!buddy_match) { static FindBuddyMatch def_bm; buddy_match = &def_bm; } for (unsigned i = 0; i < buddyList.size(); i++) { if (buddy_match->match(uri, *buddyList[i])) return buddyList[i]; } PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } Buddy Account::findBuddy2(string uri) const PJSUA2_THROW(Error) { pj_str_t pj_uri; pjsua_buddy_id bud_id; pj_strset2(&pj_uri, (char*)uri.c_str()); bud_id = pjsua_buddy_find(&pj_uri); if (id == PJSUA_INVALID_ID) { PJSUA2_RAISE_ERROR(PJ_ENOTFOUND); } Buddy buddy(bud_id); return buddy; } void Account::addBuddy(Buddy *buddy) { pj_assert(buddy); buddyList.push_back(buddy); } void Account::removeBuddy(Buddy *buddy) { pj_assert(buddy); BuddyVector::iterator it; for (it = buddyList.begin(); it != buddyList.end(); it++) { if (*it == buddy) { buddyList.erase(it); return; } } pj_assert(!"Bug! Buddy to be removed is not in the buddy list!"); }
ismangil/pjproject
pjsip/src/pjsua2/account.cpp
C++
gpl-2.0
39,647
/** * Copyright (C) ARM Limited 2012-2015. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #define NEWLINE_CANARY \ /* Unix */ \ "1\n" \ /* Windows */ \ "2\r\n" \ /* Mac OS */ \ "3\r" \ /* RISC OS */ \ "4\n\r" \ /* Add another character so the length isn't 0x0a bytes */ \ "5" #ifdef MALI_SUPPORT #include "gator_events_mali_common.h" #endif static void marshal_summary(long long timestamp, long long uptime, long long monotonic_delta, const char *uname) { unsigned long flags; int cpu = 0; char buf[32]; local_irq_save(flags); gator_buffer_write_packed_int(cpu, SUMMARY_BUF, MESSAGE_SUMMARY); gator_buffer_write_string(cpu, SUMMARY_BUF, NEWLINE_CANARY); gator_buffer_write_packed_int64(cpu, SUMMARY_BUF, timestamp); gator_buffer_write_packed_int64(cpu, SUMMARY_BUF, uptime); gator_buffer_write_packed_int64(cpu, SUMMARY_BUF, monotonic_delta); gator_buffer_write_string(cpu, SUMMARY_BUF, "uname"); gator_buffer_write_string(cpu, SUMMARY_BUF, uname); gator_buffer_write_string(cpu, SUMMARY_BUF, "PAGESIZE"); snprintf(buf, sizeof(buf), "%lu", PAGE_SIZE); gator_buffer_write_string(cpu, SUMMARY_BUF, buf); #if GATOR_IKS_SUPPORT gator_buffer_write_string(cpu, SUMMARY_BUF, "iks"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif #ifdef CONFIG_PREEMPT_RTB gator_buffer_write_string(cpu, SUMMARY_BUF, "preempt_rtb"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif #ifdef CONFIG_PREEMPT_RT_FULL gator_buffer_write_string(cpu, SUMMARY_BUF, "preempt_rt_full"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif /* Let Streamline know which GPU is used so that it can label the GPU Activity appropriately. This is a temporary fix, to be improved in a future release. */ #ifdef MALI_SUPPORT gator_buffer_write_string(cpu, SUMMARY_BUF, "mali_type"); #if (MALI_SUPPORT == MALI_4xx) gator_buffer_write_string(cpu, SUMMARY_BUF, "4xx"); #elif (MALI_SUPPORT == MALI_MIDGARD) gator_buffer_write_string(cpu, SUMMARY_BUF, "6xx"); #else gator_buffer_write_string(cpu, SUMMARY_BUF, "unknown"); #endif #endif #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 2, 0) gator_buffer_write_string(cpu, SUMMARY_BUF, "nosync"); gator_buffer_write_string(cpu, SUMMARY_BUF, ""); #endif gator_buffer_write_string(cpu, SUMMARY_BUF, ""); /* Commit the buffer now so it can be one of the first frames read by Streamline */ local_irq_restore(flags); gator_commit_buffer(cpu, SUMMARY_BUF, gator_get_time()); } static bool marshal_cookie_header(const char *text) { int cpu = get_physical_cpu(); return buffer_check_space(cpu, NAME_BUF, strlen(text) + 3 * MAXSIZE_PACK32); } static void marshal_cookie(int cookie, const char *text) { int cpu = get_physical_cpu(); /* buffer_check_space already called by marshal_cookie_header */ gator_buffer_write_packed_int(cpu, NAME_BUF, MESSAGE_COOKIE); gator_buffer_write_packed_int(cpu, NAME_BUF, cookie); gator_buffer_write_string(cpu, NAME_BUF, text); buffer_check(cpu, NAME_BUF, gator_get_time()); } static void marshal_thread_name(int pid, char *name) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, NAME_BUF, TASK_COMM_LEN + 3 * MAXSIZE_PACK32 + MAXSIZE_PACK64)) { gator_buffer_write_packed_int(cpu, NAME_BUF, MESSAGE_THREAD_NAME); gator_buffer_write_packed_int64(cpu, NAME_BUF, time); gator_buffer_write_packed_int(cpu, NAME_BUF, pid); gator_buffer_write_string(cpu, NAME_BUF, name); } local_irq_restore(flags); buffer_check(cpu, NAME_BUF, time); } static void marshal_link(int cookie, int tgid, int pid) { unsigned long cpu = get_physical_cpu(), flags; u64 time; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, ACTIVITY_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, MESSAGE_LINK); gator_buffer_write_packed_int64(cpu, ACTIVITY_BUF, time); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, cookie); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, tgid); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, pid); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, ACTIVITY_BUF, time); } static bool marshal_backtrace_header(int exec_cookie, int tgid, int pid, u64 time) { int cpu = get_physical_cpu(); if (!buffer_check_space(cpu, BACKTRACE_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32 + gator_backtrace_depth * 2 * MAXSIZE_PACK32)) { /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, BACKTRACE_BUF, time); return false; } gator_buffer_write_packed_int64(cpu, BACKTRACE_BUF, time); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, exec_cookie); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, tgid); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, pid); return true; } static void marshal_backtrace(unsigned long address, int cookie, int in_kernel) { int cpu = get_physical_cpu(); if (cookie == 0 && !in_kernel) cookie = UNRESOLVED_COOKIE; gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, cookie); gator_buffer_write_packed_int64(cpu, BACKTRACE_BUF, address); } static void marshal_backtrace_footer(u64 time) { int cpu = get_physical_cpu(); gator_buffer_write_packed_int(cpu, BACKTRACE_BUF, MESSAGE_END_BACKTRACE); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, BACKTRACE_BUF, time); } static bool marshal_event_header(u64 time) { unsigned long flags, cpu = get_physical_cpu(); bool retval = false; local_irq_save(flags); if (buffer_check_space(cpu, BLOCK_COUNTER_BUF, MAXSIZE_PACK32 + MAXSIZE_PACK64)) { gator_buffer_write_packed_int(cpu, BLOCK_COUNTER_BUF, 0); /* key of zero indicates a timestamp */ gator_buffer_write_packed_int64(cpu, BLOCK_COUNTER_BUF, time); retval = true; } local_irq_restore(flags); return retval; } static void marshal_event(int len, int *buffer) { unsigned long i, flags, cpu = get_physical_cpu(); if (len <= 0) return; /* length must be even since all data is a (key, value) pair */ if (len & 0x1) { pr_err("gator: invalid counter data detected and discarded\n"); return; } /* events must be written in key,value pairs */ local_irq_save(flags); for (i = 0; i < len; i += 2) { if (!buffer_check_space(cpu, BLOCK_COUNTER_BUF, 2 * MAXSIZE_PACK32)) break; gator_buffer_write_packed_int(cpu, BLOCK_COUNTER_BUF, buffer[i]); gator_buffer_write_packed_int(cpu, BLOCK_COUNTER_BUF, buffer[i + 1]); } local_irq_restore(flags); } static void marshal_event64(int len, long long *buffer64) { unsigned long i, flags, cpu = get_physical_cpu(); if (len <= 0) return; /* length must be even since all data is a (key, value) pair */ if (len & 0x1) { pr_err("gator: invalid counter data detected and discarded\n"); return; } /* events must be written in key,value pairs */ local_irq_save(flags); for (i = 0; i < len; i += 2) { if (!buffer_check_space(cpu, BLOCK_COUNTER_BUF, 2 * MAXSIZE_PACK64)) break; gator_buffer_write_packed_int64(cpu, BLOCK_COUNTER_BUF, buffer64[i]); gator_buffer_write_packed_int64(cpu, BLOCK_COUNTER_BUF, buffer64[i + 1]); } local_irq_restore(flags); } static void __maybe_unused marshal_event_single(int core, int key, int value) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, COUNTER_BUF, MAXSIZE_PACK64 + 3 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int64(cpu, COUNTER_BUF, time); gator_buffer_write_packed_int(cpu, COUNTER_BUF, core); gator_buffer_write_packed_int(cpu, COUNTER_BUF, key); gator_buffer_write_packed_int(cpu, COUNTER_BUF, value); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, COUNTER_BUF, time); } static void __maybe_unused marshal_event_single64(int core, int key, long long value) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, COUNTER_BUF, 2 * MAXSIZE_PACK64 + 2 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int64(cpu, COUNTER_BUF, time); gator_buffer_write_packed_int(cpu, COUNTER_BUF, core); gator_buffer_write_packed_int(cpu, COUNTER_BUF, key); gator_buffer_write_packed_int64(cpu, COUNTER_BUF, value); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, COUNTER_BUF, time); } static void marshal_sched_trace_switch(int pid, int state) { unsigned long cpu = get_physical_cpu(), flags; u64 time; if (!per_cpu(gator_buffer, cpu)[SCHED_TRACE_BUF]) return; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, SCHED_TRACE_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, MESSAGE_SCHED_SWITCH); gator_buffer_write_packed_int64(cpu, SCHED_TRACE_BUF, time); gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, pid); gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, state); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, SCHED_TRACE_BUF, time); } static void marshal_sched_trace_exit(int tgid, int pid) { unsigned long cpu = get_physical_cpu(), flags; u64 time; if (!per_cpu(gator_buffer, cpu)[SCHED_TRACE_BUF]) return; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, SCHED_TRACE_BUF, MAXSIZE_PACK64 + 2 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, MESSAGE_SCHED_EXIT); gator_buffer_write_packed_int64(cpu, SCHED_TRACE_BUF, time); gator_buffer_write_packed_int(cpu, SCHED_TRACE_BUF, pid); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, SCHED_TRACE_BUF, time); } #if GATOR_CPU_FREQ_SUPPORT static void marshal_idle(int core, int state) { unsigned long flags, cpu; u64 time; local_irq_save(flags); cpu = get_physical_cpu(); time = gator_get_time(); if (buffer_check_space(cpu, IDLE_BUF, MAXSIZE_PACK64 + 2 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, IDLE_BUF, state); gator_buffer_write_packed_int64(cpu, IDLE_BUF, time); gator_buffer_write_packed_int(cpu, IDLE_BUF, core); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, IDLE_BUF, time); } #endif #if defined(__arm__) || defined(__aarch64__) static void marshal_core_name(const int core, const int cpuid, const char *name) { int cpu = get_physical_cpu(); unsigned long flags; local_irq_save(flags); if (buffer_check_space(cpu, SUMMARY_BUF, MAXSIZE_PACK32 + MAXSIZE_CORE_NAME)) { gator_buffer_write_packed_int(cpu, SUMMARY_BUF, MESSAGE_CORE_NAME); gator_buffer_write_packed_int(cpu, SUMMARY_BUF, core); gator_buffer_write_packed_int(cpu, SUMMARY_BUF, cpuid); gator_buffer_write_string(cpu, SUMMARY_BUF, name); } /* Commit core names now so that they can show up in live */ local_irq_restore(flags); gator_commit_buffer(cpu, SUMMARY_BUF, gator_get_time()); } #endif static void marshal_activity_switch(int core, int key, int activity, int pid, int state) { unsigned long cpu = get_physical_cpu(), flags; u64 time; if (!per_cpu(gator_buffer, cpu)[ACTIVITY_BUF]) return; local_irq_save(flags); time = gator_get_time(); if (buffer_check_space(cpu, ACTIVITY_BUF, MAXSIZE_PACK64 + 5 * MAXSIZE_PACK32)) { gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, MESSAGE_SWITCH); gator_buffer_write_packed_int64(cpu, ACTIVITY_BUF, time); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, core); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, key); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, activity); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, pid); gator_buffer_write_packed_int(cpu, ACTIVITY_BUF, state); } local_irq_restore(flags); /* Check and commit; commit is set to occur once buffer is 3/4 full */ buffer_check(cpu, ACTIVITY_BUF, time); } void gator_marshal_activity_switch(int core, int key, int activity, int pid) { /* state is reserved for cpu use only */ marshal_activity_switch(core, key, activity, pid, 0); }
javilonas/Lonas_KL-SM-G901F
drivers/gator/gator_marshaling.c
C
gpl-2.0
12,460
BeginningDev ============ Beginning Development Initiatives
jellydevext/BeginningDev
README.md
Markdown
gpl-2.0
61
/** * card_view = new BaristaCardView({el: $("target_selector", url:"", title:"", subtitle:"", fg_color: "#1b9e77", image:"", span_class: "col-lg-12"}); * * A Backbone View that displays a card of information wrapped in link * The view is meant to be a top level entry point to other pages * basic use: card_view = new BaristaCardView(); * optional arguments: * @param {string} url the link to navigate to if the card is clicked, defaults to "" * @param {string} title the title of the card. defaults to "title" * @param {string} subtitle the subtitle of the card. defaults to "subtitle" * @param {string} image the link to an image to show as the cards main content. defaults to "" * @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to * #1b9e77 * @param {string} span_class a bootstrap span class to size the width of the view, defaults to * "col-lg-12" */ Barista.Views.BaristaCardView = Backbone.View.extend({ /** * give the view a name to be used throughout the View's functions when it needs to know what its class * name is * @type {String} */ name: "BaristaCardView", /** * supply a base model for the view * Overide this if you need to use it for dynamic content * @type {Backbone} */ model: new Backbone.Model(), /** * overide the view's default initialize method in order to catch options and render a custom template */ initialize: function(){ // set up color options. default if not specified this.fg_color = (this.options.fg_color !== undefined) ? this.options.fg_color : "#1b9e77"; // set up the span size this.span_class = (this.options.span_class !== undefined) ? this.options.span_class : "col-lg-12"; // set up the url this.url = (this.options.url !== undefined) ? this.options.url : ""; // set up the title this.title = (this.options.title !== undefined) ? this.options.title : "Title"; // set up the subtitle this.subtitle = (this.options.subtitle !== undefined) ? this.options.subtitle : "subtitle"; // set up the image this.image = (this.options.image !== undefined) ? this.options.image : ""; // bind render to model changes this.listenTo(this.model,'change', this.update); // compile the default template for the view this.compile_template(); }, /** * use Handlebars to compile the template for the view */ compile_template: function(){ var self = this; this.div_string = 'barista_view' + new Date().getTime();; this.$el.append(BaristaTemplates.CMapCard({div_string: this.div_string, span_class: this.span_class, url: this.url, title: this.title, subtitle: this.subtitle, image: this.image, fg_color: this.fg_color})); } });
cmap/barista
source/views/BaristaCardView.js
JavaScript
gpl-2.0
2,907
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="/stylesheets/stylesheet.css" media="screen" /> <link rel="stylesheet" type="text/css" href="/stylesheets/pygment_trac.css" media="screen" /> <link rel="stylesheet" type="text/css" href="/stylesheets/print.css" media="print" /> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <title>puppix by puppix</title> </head> <body> <a href="https://github.com/puppix/puppix.github.io"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://github-camo.global.ssl.fastly.net/52760788cde945287fbb584134c4cbc2bc36f904/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f77686974655f6666666666662e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png"></a> <header> <div class="inner"> <h1><a href="/">puppix</a></h1> <h2>Puppet for Enterprise Linux</h2> <a href="https://github.com/puppix" class="button"><small>Follow me on</small>GitHub</a> </div> </header> <div id="content-wrapper"> <div class="inner clearfix"> <section id="main-content"> {{ content }} </section> <aside id="sidebar"> <p> <a href="https://github.com/puppix">./github</a> - GitHub Page<br /> <a href="https://github.com/puppix/puppix.github.io/issues">./issues</a> - Global Tracker<br /> <a href="/codingstyle">./style</a> - Coding Style<br /> </p> <strong>Blog Posts</strong> <ul class="posts"> {% for post in site.posts %} <li> <a href="{{ post.url }}">{{ post.title }}</a><br /> &raquo; <span>{{ post.date | date_to_string }}</span> </li> {% endfor %} </ul> </aside> </div> </div> </body> </html>
scrothers/puppix.github.io
_layouts/default.html
HTML
gpl-2.0
2,287
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ludum2D.Tiles; using Ludum2D.World; using Microsoft.Xna.Framework; namespace Ludum2D.Core { public class LudumCore { private static LudumCore instance; public static LudumCore Instance { get { if (instance == null) { instance = new LudumCore(); } return instance; } } private LudumCore() { } public bool Initialized { get; private set; } /// <summary> /// Initialize the cores of the engine /// </summary> public void Initialize() { } /// <summary> /// Sets the size of a tile /// </summary> /// <param name="sq">Width and height of a tile; Must be x^2</param> public void SetTileSize(int sq) { if (!Initialized) { throw new Exception("The tile size cannot be modified once the the LudumCore has been initialized"); } Tile.Width = sq; } } }
oxysoft/Ludum2D
Ludum2D/Core/LudumCore.cs
C#
gpl-2.0
943
\section{Laser and Solar Panel} For this project a laser pointer and four solar panels is made available. The purpose of a laser pointer and solar panels is to show how the system works by pointing on a solar panel with the laser. The solar panels is all equal in size, with the dimensions of 3x3 cm. \todo[inline]{Some more info on the laser and the solar panel.}
MaximeRemy/Master-NDS7-Bluetooth
Report/chapters/Part1/TechnicalKnowladge/LaserSolarPanel.tex
TeX
gpl-2.0
368
<?php /** * @group Echo */ class SuppressionMaintenanceTest extends MediaWikiTestCase { public static function provider_updateRow() { $input = array( 'event_id' => 2, 'event_type' => 'mention', 'event_variant' => null, 'event_agent_id' => 3, 'event_agent_ip' => null, 'event_page_title' => '', 'event_page_namespace' => 0, 'event_page_extra' => null, 'event_extra' => null, 'event_page_id' => null, ); return array( array( 'Unrelated row must result in no update', array(), $input ), array( 'Page title and namespace for non-existant page must move into event_extra', array( // expected update 'event_extra' => serialize( array( 'page_title' => 'Yabba Dabba Do', 'page_namespace' => NS_MAIN ) ), ), array( // input row 'event_page_title' => 'Yabba Dabba Do', 'event_page_namespace' => NS_MAIN, ) + $input, ), array( 'Page title and namespace for existing page must be result in update to event_page_id', array( // expected update 'event_page_id' => 42, ), array( // input row 'event_page_title' => 'Mount Rushmore', 'event_page_namespace' => NS_MAIN, ) + $input, self::attachTitleFor( 42, 'Mount Rushmore', NS_MAIN ) ), array( 'When updating non-existant page must keep old extra data', array( // expected update 'event_extra' => serialize( array( 'foo' => 'bar', 'page_title' => 'Yabba Dabba Do', 'page_namespace' => NS_MAIN ) ), ), array( // input row 'event_page_title' => 'Yabba Dabba Do', 'event_page_namespace' => NS_MAIN, 'event_extra' => serialize( array( 'foo' => 'bar' ) ), ) + $input, ), array( 'Must update link-from-title/namespace to link-from-page-id for page-linked events', array( // expected update 'event_extra' => serialize( array( 'link-from-page-id' => 99 ) ), ), array( //input row 'event_type' => 'page-linked', 'event_extra' => serialize( array( 'link-from-title' => 'Horse', 'link-from-namespace' => NS_USER_TALK ) ), ) + $input, self::attachTitleFor( 99, 'Horse', NS_USER_TALK ) ), array( 'Must perform both generic update and page-linked update at same time', array( // expected update 'event_extra' => serialize( array( 'link-from-page-id' => 8675309 ) ), 'event_page_id' => 8675309, ), array( //input row 'event_type' => 'page-linked', 'event_extra' => serialize( array( 'link-from-title' => 'Jenny', 'link-from-namespace' => NS_MAIN, ) ), 'event_page_title' => 'Jenny', 'event_page_namespace' => NS_MAIN, ) + $input, self::attachTitleFor( 8675309, 'Jenny', NS_MAIN ), ), ); } protected static function attachTitleFor( $id, $providedText, $providedNamespace ) { return function( $test, $gen ) use ( $id, $providedText, $providedNamespace ) { $title = $test->getMock( 'Title' ); $title->expects( $test->any() ) ->method( 'getArticleId' ) ->will( $test->returnValue( $id ) ); $titles = array( $providedNamespace => array( $providedText => $title ) ); $gen->setNewTitleFromText( function( $text, $defaultNamespace ) use( $titles ) { if ( isset( $titles[$defaultNamespace][$text] ) ) { return $titles[$defaultNamespace][$text]; } return Title::newFromText( $text, $defaultNamespace ); } ); }; } /** * @dataProvider provider_updateRow */ public function testUpdateRow( $message, $expected, $input, $callable = null ) { $gen = new EchoSuppressionRowUpdateGenerator; if ( $callable ) { call_user_func( $callable, $this, $gen ); } $update = $gen->update( (object) $input ); $this->assertEquals( $expected, $update, $message ); } }
tuxun/smw-funwiki
extensions/Echo/tests/phpunit/maintenance/SupressionMaintenanceTest.php
PHP
gpl-2.0
3,786
<?php /* core/themes/classy/templates/navigation/menu-local-task.html.twig */ class __TwigTemplate_0969a23526138fcc37f60cc805db1d447beeec2f58012651e0e2200d57c77ec5 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 17 echo "<li"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (((isset($context["is_active"]) ? $context["is_active"] : null)) ? ("is-active") : (""))), "method"), "html", null, true)); echo ">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["link"]) ? $context["link"] : null), "html", null, true)); echo "</li> "; } public function getTemplateName() { return "core/themes/classy/templates/navigation/menu-local-task.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 17,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for a local task link.*/ /* **/ /* * Available variables:*/ /* * - attributes: HTML attributes for the wrapper element.*/ /* * - is_active: Whether the task item is an active tab.*/ /* * - link: A rendered link element.*/ /* **/ /* * Note: This template renders the content for each task item in*/ /* * menu-local-tasks.html.twig.*/ /* **/ /* * @see template_preprocess_menu_local_task()*/ /* *//* */ /* #}*/ /* <li{{ attributes.addClass(is_active ? 'is-active') }}>{{ link }}</li>*/ /* */
padmanabhan-developer/EstarProd
sites/default/files/php/twig/075870e6_menu-local-task.html.twig_09bb732346e5d24c980d871bac93beeabc98bdcdafc22eac5ff5f4c40f13cf6a/6ea817bad80d90d325204bb326b2453055a5d09f565dc9938936aba350e2c955.php
PHP
gpl-2.0
2,927
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / | # | | |___| | | | __/ (__| < | | | | . \ | # | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ | # | | # | Copyright Mathias Kettner 2014 [email protected] | # +------------------------------------------------------------------+ # # This file is part of Check_MK. # The official homepage is at http://mathias-kettner.de/check_mk. # # check_mk 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 in version 2. check_mk is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- # out even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more de- # ails. You should have received a copy of the GNU General Public # License along with GNU Make; see the file COPYING. If not, write # to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, # Boston, MA 02110-1301 USA. import config loaded_with_language = False # .----------------------------------------------------------------------. # | ____ _ _ | # | | _ \ ___ _ __ _ __ ___ (_)___ ___(_) ___ _ __ ___ | # | | |_) / _ \ '__| '_ ` _ \| / __/ __| |/ _ \| '_ \/ __| | # | | __/ __/ | | | | | | | \__ \__ \ | (_) | | | \__ \ | # | |_| \___|_| |_| |_| |_|_|___/___/_|\___/|_| |_|___/ | # | | # +----------------------------------------------------------------------+ # | Declare general permissions for Multisite | # '----------------------------------------------------------------------' def load(): global loaded_with_language if loaded_with_language == current_language: return config.declare_permission_section("general", _('General Permissions'), 10) config.declare_permission("general.use", _("Use Multisite at all"), _("Users without this permission are not let in at all"), [ "admin", "user", "guest" ]) config.declare_permission("general.see_all", _("See all Nagios objects"), _("See all objects regardless of contacts and contact groups. " "If combined with 'perform commands' then commands may be done on all objects."), [ "admin", "guest" ]) declare_visual_permissions('views', _("views")) declare_visual_permissions('dashboards', _("dashboards")) config.declare_permission("general.view_option_columns", _("Change view display columns"), _("Interactively change the number of columns being displayed by a view (does not edit or customize the view)"), [ "admin", "user", "guest" ]) config.declare_permission("general.view_option_refresh", _("Change view display refresh"), _("Interactively change the automatic browser reload of a view being displayed (does not edit or customize the view)"), [ "admin", "user" ]) config.declare_permission("general.painter_options", _("Change column display options"), _("Some of the display columns offer options for customizing their output. " "For example time stamp columns can be displayed absolute, relative or " "in a mixed style. This permission allows the user to modify display options"), [ "admin", "user", "guest" ]) config.declare_permission("general.act", _("Perform commands"), _("Allows users to perform Nagios commands. If no further permissions " "are granted, actions can only be done on objects one is a contact for"), [ "admin", "user" ]) config.declare_permission("general.see_sidebar", _("Use Check_MK sidebar"), _("Without this permission the Check_MK sidebar will be invisible"), [ "admin", "user", "guest" ]) config.declare_permission("general.configure_sidebar", _("Configure sidebar"), _("This allows the user to add, move and remove sidebar snapins."), [ "admin", "user" ]) config.declare_permission('general.edit_profile', _('Edit the user profile'), _('Permits the user to change the user profile settings.'), [ 'admin', 'user' ] ) config.declare_permission('general.edit_notifications', _('Edit personal notification settings'), _('This allows a user to edit his personal notification settings. You also need the permission ' '<i>Edit the user profile</i> in order to do this.'), [ 'admin', 'user' ] ) config.declare_permission('general.disable_notifications', _('Disable all personal notifications'), _('This permissions provides a checkbox in the personal settings of the user that ' 'allows him to completely disable all of his notifications. Use with caution.'), [ 'admin', ] ) config.declare_permission('general.edit_user_attributes', _('Edit personal user attributes'), _('This allows a user to edit his personal user attributes. You also need the permission ' '<i>Edit the user profile</i> in order to do this.'), [ 'admin', 'user' ] ) config.declare_permission('general.change_password', _('Edit the user password'), _('Permits the user to change the password.'), [ 'admin', 'user' ] ) config.declare_permission('general.logout', _('Logout'), _('Permits the user to logout.'), [ 'admin', 'user', 'guest' ] ) config.declare_permission("general.ignore_soft_limit", _("Ignore soft query limit"), _("Allows to ignore the soft query limit imposed upon the number of datasets returned by a query"), [ "admin", "user" ]) config.declare_permission("general.ignore_hard_limit", _("Ignore hard query limit"), _("Allows to ignore the hard query limit imposed upon the number of datasets returned by a query"), [ "admin" ]) loaded_with_language = current_language # TODO: This has been obsoleted by pagetypes.py def declare_visual_permissions(what, what_plural): config.declare_permission("general.edit_" + what, _("Customize %s and use them") % what_plural, _("Allows to create own %s, customize builtin %s and use them.") % (what_plural, what_plural), [ "admin", "user" ]) config.declare_permission("general.publish_" + what, _("Publish %s") % what_plural, _("Make %s visible and usable for other users.") % what_plural, [ "admin", "user" ]) config.declare_permission("general.see_user_" + what, _("See user %s") % what_plural, _("Is needed for seeing %s that other users have created.") % what_plural, [ "admin", "user", "guest" ]) config.declare_permission("general.force_" + what, _("Modify builtin %s") % what_plural, _("Make own published %s override builtin %s for all users.") % (what_plural, what_plural), [ "admin" ]) config.declare_permission("general.delete_foreign_" + what, _("Delete foreign %s") % what_plural, _("Allows to delete %s created by other users.") % what_plural, [ "admin" ])
xorpaul/check_mk
web/htdocs/default_permissions.py
Python
gpl-2.0
7,863
/* * Copyright (c) 2017, 2020, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <graalvm/llvm/polyglot.h> #include <graalvm/llvm/handles.h> int main() { void *p = polyglot_import("object"); void *p1 = create_handle(p); void *p2 = resolve_handle(p1); if (p != p2) { return 1; } return 0; }
smarr/Truffle
sulong/tests/com.oracle.truffle.llvm.tests.interop.native/interop/createResolveHandle.c
C
gpl-2.0
1,844
#! /bin/sh modprobe ib_core modprobe ib_uverbs modprobe ib_addr modprobe ib_umad modprobe ib_cm modprobe ib_mad # modprobe ib_ipoib modprobe ib_sa modprobe iw_cm modprobe ib_ucm modprobe rdma_ucm modprobe rdma_cm
nminoru/pib
driver/load_ib_modules.sh
Shell
gpl-2.0
214
package mrdev023.opengl; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.system.MemoryUtil.*; import java.awt.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.glfw.*; import org.lwjgl.opengl.*; import mrdev023.exception.*; public class Display { private static DisplayMode displayMode; private static String TITLE = ""; private static long window; private static boolean hasResized = false; public static void create(String title,int width,int height){ if ( !glfwInit() ) throw new IllegalStateException("Unable to initialize GLFW"); TITLE = title; displayMode = new DisplayMode(width,height); window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL); } public static void create(String title,int width,int height,int major,int minor){ if ( !glfwInit() ) throw new IllegalStateException("Unable to initialize GLFW"); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); TITLE = title; displayMode = new DisplayMode(width,height); window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL); } public static void setMouseGrabbed(boolean a){ if(a){ glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); }else{ glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } public static void setVSync(boolean a) throws DisplayException{ if(a)glfwSwapInterval(1); else glfwSwapInterval(0); } public static void create(String title,int width,int height,int major,int minor,int sample){ if ( !glfwInit() ) throw new IllegalStateException("Unable to initialize GLFW"); glfwWindowHint(GLFW_SAMPLES, sample); // antialiasing 4x glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); TITLE = title; displayMode = new DisplayMode(width,height); window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL); } public static void setSample(int sample){ glfwWindowHint(GLFW_SAMPLES, sample); } public static void setResizable(boolean a){ if(a)glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); else glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); } public static void setTitle(String title){ TITLE = title; glfwSetWindowTitle(window, TITLE); } public static String getTitle(){ return TITLE; } public static boolean wasResized(){ IntBuffer w = BufferUtils.createIntBuffer(1); IntBuffer h = BufferUtils.createIntBuffer(1); glfwGetWindowSize(window, w, h); int width = w.get(0); int height = h.get(0); if(Display.getDisplayMode().getWidth() != width || Display.getDisplayMode().getHeight() != height || hasResized){ setDisplayMode(new DisplayMode(width, height)); hasResized = false; return true; }else{ return false; } } public static void printMonitorsInfo(){ PointerBuffer monitors = glfwGetMonitors(); GLFWVidMode m; if(monitors == null){ System.out.println("No monitor detected !"); return; } for(int i = 0;i < monitors.capacity();i++){ m = glfwGetVideoMode(monitors.get(i)); System.out.println(glfwGetMonitorName(monitors.get(i)) + "(" + i + ") : " + m.width() + "x" + m.height() + ":" + m.refreshRate() + "Hz"); } } public static boolean isCloseRequested(){ return glfwWindowShouldClose(window); } public static void createContext(){ glfwMakeContextCurrent(window); GL.createCapabilities(); } public static void updateEvent(){ glfwPollEvents(); } public static void updateFrame(){ glfwSwapBuffers(window); } public static DisplayMode getDisplayMode() { return displayMode; } public static void setDisplayMode(DisplayMode displayMode) { if(Display.displayMode == null || displayMode == null)return; Display.displayMode.setDisplayMode(displayMode); hasResized = true; } public static void destroy(){ glfwDestroyWindow(window); glfwTerminate(); } public static long getWindow() { return window; } }
mrdev023/Modern-Game-Engine
src/mrdev023/opengl/Display.java
Java
gpl-2.0
4,476
/* #Date of creation : 9 Jan 2016. #Aim of program : To print power set of a set of characters. #Coded by : Rishikesh Agrawani. */ package main import "fmt" func main() { var n, r, i, j uint fmt.Print("Enter the number of binary variables(for which you want the binary combinations): ") fmt.Scanf("%d", &n) fmt.Print("\nEnter ", n, " binary variables name( name should be only 1 character long) separated by space: ") a := make([]string, n) r = 1 for i = 0; i < n; i++ { fmt.Scanf("%s", &a[i]) r *= 2 } fmt.Println("\nColumns => ", n, "\nRows => ", r) for i = 0; i < r; i++ { for j = 0; j < n; j++ { if (i>>j)&1 == 1 { fmt.Print(a[j], " ") } else { fmt.Print("- ") } } fmt.Println() } } /*1st RUN: Enter the number of binary variables(for which you want the binary combinations): 4 Enter 4 binary variables name( name should be only 1 character long) separated by space: a b c d Columns => 4 Rows => 16 - - - - a - - - - b - - a b - - - - c - a - c - - b c - a b c - - - - d a - - d - b - d a b - d - - c d a - c d - b c d a b c d */ /*2nd RUN: Enter the number of binary variables(for which you want the binary combinations): Enter 5 binary variables name( name should be only 1 character long) separated by space: Columns => 5 Rows => 32 - - - - - p - - - - - q - - - p q - - - - - r - - p - r - - - q r - - p q r - - - - - s - p - - s - - q - s - p q - s - - - r s - p - r s - - q r s - p q r s - - - - - t p - - - t - q - - t p q - - t - - r - t p - r - t - q r - t p q r - t - - - s t p - - s t - q - s t p q - s t - - r s t p - r s t - q r s t p q r s t */
hygull/go
sources/hck-ds-examples/power_set_for_set_of_characters.go
GO
gpl-2.0
1,645
/* ** Copyright (C) 1991, 1997 Free Software Foundation, Inc. ** ** This file is part of TACK. ** ** TACK is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2, or (at your option) ** any later version. ** ** TACK 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 TACK; see the file COPYING. If not, write to ** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, ** Boston, MA 02111-1307, USA. */ #include <tack.h> MODULE_ID("$Id: menu.c,v 1.1.1.1 2004/03/24 19:53:07 sure Exp $") /* Menu control */ static void test_byname(struct test_menu *, int *, int *); struct test_list *augment_test; char prompt_string[80]; /* menu prompt storage */ /* ** menu_prompt() ** ** Print the menu prompt string. */ void menu_prompt(void) { ptext(&prompt_string[1]); } /* ** menu_test_loop(test-structure, state, control-character) ** ** This function implements the repeat test function. */ static void menu_test_loop( struct test_list *test, int *state, int *ch) { int nch, p; if ((test->flags & MENU_REP_MASK) && (augment_test != test)) { /* set the augment variable (first time only) */ p = (test->flags >> 8) & 15; if ((test->flags & MENU_REP_MASK) == MENU_LM1) { augment = lines - 1; } else if ((test->flags & MENU_ONE_MASK) == MENU_ONE) { augment = 1; } else if ((test->flags & MENU_LC_MASK) == MENU_lines) { augment = lines * p / 10; } else if ((test->flags & MENU_LC_MASK) == MENU_columns) { augment = columns * p / 10; } else { augment = 1; } augment_test = test; set_augment_txt(); } do { if ((test->flags | *state) & MENU_CLEAR) { put_clear(); } else if (line_count + test->lines_needed >= lines) { put_clear(); } nch = 0; if (test->test_procedure) { /* The procedure takes precedence so I can pass the menu entry as an argument. */ can_test(test->caps_done, FLAG_TESTED); can_test(test->caps_tested, FLAG_TESTED); test->test_procedure(test, state, &nch); } else if (test->sub_menu) { /* nested menu's */ menu_display(test->sub_menu, &nch); *state = 0; if (nch == 'q' || nch == 's') { /* Quit and skip are killed here */ nch = '?'; } } else { break; /* cya */ } if (nch == '\r' || nch == '\n' || nch == 'n') { nch = 0; break; } } while (nch == 'r'); *ch = nch; } /* ** menu_display(menu-structure, flags) ** ** This function implements menu control. */ void menu_display( struct test_menu *menu, int *last_ch) { int test_state = 0, run_standard_tests; int hot_topic, ch = 0, nch = 0; struct test_list *mt; struct test_list *repeat_tests = 0; int repeat_state = 0; int prompt_length; prompt_length = strlen(prompt_string); if (menu->ident) { sprintf(&prompt_string[prompt_length], "/%s", menu->ident); } hot_topic = menu->default_action; run_standard_tests = menu->standard_tests ? menu->standard_tests[0] : -1; if (!last_ch) { last_ch = &ch; } while (1) { if (ch == 0) { /* Display the menu */ put_crlf(); if (menu->menu_function) { /* this function may be used to restrict menu entries. If used it must print the title. */ menu->menu_function(menu); } else if (menu->menu_title) { ptextln(menu->menu_title); } for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) { if (mt->menu_entry) { ptext(" "); ptextln(mt->menu_entry); } } if (menu->standard_tests) { ptext(" "); ptextln(menu->standard_tests); ptextln(" r) repeat test"); ptextln(" s) skip to next test"); } ptextln(" q) quit"); ptextln(" ?) help"); } if (ch == 0 || ch == REQUEST_PROMPT) { put_crlf(); ptext(&prompt_string[1]); if (hot_topic) { ptext(" ["); putchp(hot_topic); ptext("]"); } ptext(" > "); /* read a character */ ch = wait_here(); } if (ch == '\r' || ch == '\n') { ch = hot_topic; } if (ch == 'q') { break; } if (ch == '?') { ch = 0; continue; } nch = ch; ch = 0; /* Run one of the standard tests (by request) */ for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) { if (mt->menu_entry && (nch == mt->menu_entry[0])) { if (mt->flags & MENU_MENU) { test_byname(menu, &test_state, &nch); } else { menu_test_loop(mt, &test_state, &nch); } ch = nch; if ((mt->flags & MENU_COMPLETE) && ch == 0) { /* top level */ hot_topic = 'q'; ch = '?'; } } } if (menu->standard_tests && nch == 'r') { menu->resume_tests = repeat_tests; test_state = repeat_state; nch = run_standard_tests; } if (nch == run_standard_tests) { if (!(mt = menu->resume_tests)) { mt = menu->tests; } if (mt->flags & MENU_LAST) { mt = menu->tests; } /* Run the standard test suite */ for ( ; (mt->flags & MENU_LAST) == 0; ) { if ((mt->flags & MENU_NEXT) == MENU_NEXT) { repeat_tests = mt; repeat_state = test_state; nch = run_standard_tests; menu_test_loop(mt, &test_state, &nch); if (nch != 0 && nch != 'n') { ch = nch; break; } if (test_state & MENU_STOP) { break; } } mt++; } if (ch == 0) { ch = hot_topic; } menu->resume_tests = mt; menu->resume_state = test_state; menu->resume_char = ch; if (ch == run_standard_tests) { /* pop up a level */ break; } } } *last_ch = ch; prompt_string[prompt_length] = '\0'; } /* ** generic_done_message(test_list) ** ** Print the Done message and request input. */ void generic_done_message( struct test_list *test, int *state, int *ch) { char done_message[128]; if (test->caps_done) { sprintf(done_message, "(%s) Done ", test->caps_done); ptext(done_message); } else { ptext("Done "); } *ch = wait_here(); if (*ch == '\r' || *ch == '\n' || *ch == 'n') { *ch = 0; } if (*ch == 's') { *state |= MENU_STOP; *ch = 0; } } /* ** menu_clear_screen(test, state, ch) ** ** Just clear the screen. */ void menu_clear_screen( struct test_list *test GCC_UNUSED, int *state GCC_UNUSED, int *ch GCC_UNUSED) { put_clear(); } /* ** menu_reset_init(test, state, ch) ** ** Send the reset and init strings. */ void menu_reset_init( struct test_list *test GCC_UNUSED, int *state GCC_UNUSED, int *ch GCC_UNUSED) { reset_init(); put_crlf(); } /* ** subtest_menu(test, state, ch) ** ** Scan the menu looking for something to execute ** Return TRUE if we found anything. */ int subtest_menu( struct test_list *test, int *state, int *ch) { struct test_list *mt; if (*ch) { for (mt = test; (mt->flags & MENU_LAST) == 0; mt++) { if (mt->menu_entry && (*ch == mt->menu_entry[0])) { *ch = 0; menu_test_loop(mt, state, ch); return TRUE; } } } return FALSE; } /* ** menu_can_scan(menu-structure) ** ** Recursively scan the menu tree and find which cap names can be tested. */ void menu_can_scan( const struct test_menu *menu) { struct test_list *mt; for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) { can_test(mt->caps_done, FLAG_CAN_TEST); can_test(mt->caps_tested, FLAG_CAN_TEST); if (!(mt->test_procedure)) { if (mt->sub_menu) { menu_can_scan(mt->sub_menu); } } } } /* ** menu_search(menu-structure, cap) ** ** Recursively search the menu tree and execute any tests that use cap. */ static void menu_search( struct test_menu *menu, int *state, int *ch, char *cap) { struct test_list *mt; int nch; for (mt = menu->tests; (mt->flags & MENU_LAST) == 0; mt++) { nch = 0; if (cap_match(mt->caps_done, cap) || cap_match(mt->caps_tested, cap)) { menu_test_loop(mt, state, &nch); } if (!(mt->test_procedure)) { if (mt->sub_menu) { menu_search(mt->sub_menu, state, &nch, cap); } } if (*state & MENU_STOP) { break; } if (nch != 0 && nch != 'n') { *ch = nch; break; } } } /* ** test_byname(menu, state, ch) ** ** Get a cap name then run all tests that use that cap. */ static void test_byname( struct test_menu *menu, int *state GCC_UNUSED, int *ch) { int test_state = 0; char cap[32]; if (tty_can_sync == SYNC_NOT_TESTED) { verify_time(); } ptext("enter name: "); read_string(cap, sizeof(cap)); if (cap[0]) { menu_search(menu, &test_state, ch, cap); } *ch = '?'; }
nslu2/glibc
ncurses/tack/menu.c
C
gpl-2.0
8,641
/* * UriMapFeature.hpp * * Copyright (c) 2010 Paul Giblock <pgib/at/users.sourceforge.net> * * This file is part of Unison - http://unison.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #ifndef UNISON_LV2_URI_MAP_FEATURE_H #define UNISON_LV2_URI_MAP_FEATURE_H #include "Feature.hpp" #include <lv2/uri-map.lv2/uri-map.h> namespace Lv2 { namespace Internal { class UriMap; class UriMapFeature : public Feature { public: UriMapFeature (UriMap* uriMap); LV2_Feature* lv2Feature (); void initialize (LV2_Feature*, const Lv2Plugin&) const {}; void cleanup (LV2_Feature*) const {}; private: static uint32_t uriToId (LV2_URI_Map_Callback_Data cbData, const char* map, const char* uri); LV2_Feature m_feature; LV2_URI_Map_Feature m_data; UriMap* m_uriMap; }; } // Internal } // Lv2 #endif // vim: tw=90 ts=8 sw=2 sts=2 et sta noai
pgiblock/unison
extensions/lv2/UriMapFeature.hpp
C++
gpl-2.0
1,593
<div class="wide form"> <?php $form=$this->beginWidget('CActiveForm', array( 'action'=>Yii::app()->createUrl($this->route), 'method'=>'get', )); ?> <div class="row"> <?php echo $form->label($model,'id'); ?> <?php echo $form->textField($model,'id',array('size'=>20,'maxlength'=>20)); ?> </div> <div class="row"> <?php echo $form->label($model,'executed_at'); ?> <?php echo $form->textField($model,'executed_at'); ?> </div> <div class="row"> <?php echo $form->label($model,'class'); ?> <?php echo $form->textField($model,'class',array('size'=>8,'maxlength'=>8)); ?> </div> <div class="row"> <?php echo $form->label($model,'amount'); ?> <?php echo $form->textField($model,'amount',array('size'=>20,'maxlength'=>20)); ?> </div> <div class="row"> <?php echo $form->label($model,'charge_account'); ?> <?php echo $form->textField($model,'charge_account',array('size'=>10,'maxlength'=>10)); ?> </div> <div class="row"> <?php echo $form->label($model,'deposit_account'); ?> <?php echo $form->textField($model,'deposit_account',array('size'=>10,'maxlength'=>10)); ?> </div> <div class="row"> <?php echo $form->label($model,'charge_user'); ?> <?php echo $form->textField($model,'charge_user',array('size'=>10,'maxlength'=>10)); ?> </div> <div class="row"> <?php echo $form->label($model,'deposit_user'); ?> <?php echo $form->textField($model,'deposit_user',array('size'=>10,'maxlength'=>10)); ?> </div> <div class="row"> <?php echo $form->label($model,'subject'); ?> <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>255)); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton('Search'); ?> </div> <?php $this->endWidget(); ?> </div><!-- search-form -->
mianfiga/monedademos
protected/views/pending/_search.php
PHP
gpl-2.0
1,754
import tkinter FRAME_BORDER = 5 class PageView(object): __root = None bd = None def __init__(self, root=None, main_frame=None): param = self.params() if root is None: # standalone self.__root = tkinter.Tk() self.__root.title(param['title']) self.__root.geometry('%sx%s+%s+%s' % (param['w'], param['h'], param['x'], param['y'] )) else: # inside self.__root = root self.bd = param['bd'] if main_frame is None: # standalone main_f = tkinter.Frame(master=self.__root, bg='black', bd=self.bd) main_f.pack(fill='both', expand=True) else: # inside main_f = main_frame self.make_widgets(main_f) @property def root(self): return self.__root def close(self): self.__root.destroy() self.__root.quit() # Override def make_widgets(self, main_frame): pass # Override def params(self): param = { 'x': 0, 'y': 0, 'w': 500, 'h': 500, 'title': '% Type Prog Title Here %', } return param def mk_scrollable_area(obj, obj_frame, sbars): obj.grid(row=0, column=0, sticky='NSWE') if 'y' in sbars: y_scrollbar = tkinter.ttk.Scrollbar(obj_frame) y_scrollbar.grid(row=0, column=1, sticky='NS') y_scrollbar['command'] = obj.yview obj['yscrollcommand'] = y_scrollbar.set if 'x' in sbars: x_scrollbar = tkinter.ttk.Scrollbar(obj_frame, orient='horizontal') x_scrollbar.grid(row=1, column=0, sticky='WE') x_scrollbar['command'] = obj.xview obj['xscrollcommand'] = x_scrollbar.set obj_frame.columnconfigure(1, 'minsize') obj_frame.columnconfigure(0, weight=1) obj_frame.rowconfigure(1, 'minsize') obj_frame.rowconfigure(0, weight=1) def mk_listbox(frame, side='top', sbars='y', sel_mode=tkinter.EXTENDED): BORDER = 0 COLOR = 'grey' listbox_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER) listbox_frame.pack(side=side, fill='both', expand=True) listbox = tkinter.Listbox(listbox_frame, selectmode=sel_mode) mk_scrollable_area(listbox, listbox_frame, sbars) return listbox def mk_treeview(frame, side='top', sbars='y'): BORDER = 0 COLOR = 'grey' treeview_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER) treeview_frame.pack(side=side, fill='both', expand=True) treeview = tkinter.ttk.Treeview(treeview_frame) mk_scrollable_area(treeview, treeview_frame, sbars) return treeview
sora7/listparse
src/listparse/ui/common.py
Python
gpl-2.0
2,865
// Copyright (C) 2012 Markus Fischer // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Contact: [email protected] package ch.dbs.actions.bestellung; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.lang.StringEscapeUtils; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import util.CodeUrl; import util.Http; import ch.dbs.form.JournalDetails; import enums.Connect; /** * This class reads answers from the normal EZB UI searched with the parameter * xmloutput=1 to get XML. */ public class EZBXML { private static final Logger LOG = LoggerFactory.getLogger(EZBXML.class); public List<JournalDetails> searchByTitle(final String jtitle, final String bibid) { final Http http = new Http(); final CodeUrl coder = new CodeUrl(); final StringBuffer link = new StringBuffer( "http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=7&lang=de&jq_type1=KT&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&offset=-1&hits_per_page=30&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid="); link.append(bibid); link.append("&jq_term1="); link.append(coder.encode(jtitle, "ISO-8859-1")); String content = http.getContent(link.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(), null); // if we have > 30 hits, try a more concise search using: &jq_type1=KS (title starts with) instead of &jq_type1=KT (words in title) if (content != null && content.contains("<search_count>")) { final int x = Integer.parseInt(content.substring(content.indexOf("<search_count>") + 14, content.indexOf("</search_count>"))); if (x > 30) { final StringBuffer link2 = new StringBuffer( "http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=7&lang=de&jq_type1=KS&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&offset=-1&hits_per_page=30&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid="); link2.append(bibid); link2.append("&jq_term1="); link2.append(coder.encode(jtitle, "ISO-8859-1")); content = http.getContent(link2.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(), null); } } final List<String> jourids = getJourids(content); return searchByJourids(jourids, bibid); } public List<JournalDetails> searchByIssn(final String issn, final String bibid) { final Http http = new Http(); final StringBuffer link = new StringBuffer( "http://ezb.uni-regensburg.de/ezeit/searchres.phtml?xmloutput=1&colors=5&lang=de&jq_type1=KT&jq_term1=&jq_bool2=AND&jq_not2=+&jq_type2=KS&jq_term2=&jq_bool3=AND&jq_not3=+&jq_type3=PU&jq_term3=&jq_bool4=AND&jq_not4=+&jq_type4=IS&offset=-1&hits_per_page=50&search_journal=Suche+starten&Notations%5B%5D=all&selected_colors%5B%5D=1&selected_colors%5B%5D=2&selected_colors%5B%5D=4&bibid="); link.append(bibid); link.append("&jq_term4="); link.append(issn); final String content = http.getContent(link.toString(), Connect.TIMEOUT_2.getValue(), Connect.TRIES_2.getValue(), null); final List<String> jourids = getJourids(content); return searchByJourids(jourids, bibid); } public List<JournalDetails> searchByJourids(final List<String> jourids, final String bibid) { final List<JournalDetails> list = new ArrayList<JournalDetails>(); final Http http = new Http(); final StringBuffer link = new StringBuffer( "http://rzblx1.uni-regensburg.de/ezeit/detail.phtml?xmloutput=1&colors=7&lang=de&bibid="); link.append(bibid); link.append("&jour_id="); final StringBuffer infoLink = new StringBuffer( "http://ezb.uni-regensburg.de/ezeit/detail.phtml?colors=7&lang=de&bibid="); infoLink.append(bibid); infoLink.append("&jour_id="); try { for (final String jourid : jourids) { final JournalDetails jd = new JournalDetails(); final String content = http.getContent(link.toString() + jourid, Connect.TIMEOUT_1.getValue(), Connect.TRIES_1.getValue(), null); if (content != null) { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(new InputSource(new StringReader(content))); final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); final XPathExpression exprJournal = xpath.compile("//journal"); final XPathExpression exprPissns = xpath.compile("//journal/detail/P_ISSNs"); final XPathExpression exprEissns = xpath.compile("//journal/detail/E_ISSNs"); final NodeList resultJournal = (NodeList) exprJournal.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < resultJournal.getLength(); i++) { final Node firstResultNode = resultJournal.item(i); final Element journal = (Element) firstResultNode; // Title String title = getValue(journal.getElementsByTagName("title")); if (title != null) { title = Jsoup.clean(title, Whitelist.none()); title = Jsoup.parse(title).text(); } jd.setZeitschriftentitel(title); // P-ISSNs final NodeList resultPissns = (NodeList) exprPissns.evaluate(doc, XPathConstants.NODESET); // get first pissn for (int z = 0; z < resultPissns.getLength(); z++) { final Node firstPissnsNode = resultPissns.item(i); final Element pissnElement = (Element) firstPissnsNode; final String pissn = getValue(pissnElement.getElementsByTagName("P_ISSN")); jd.setIssn(pissn); } // try to get Eissn if we have no Pissn if (jd.getIssn() == null) { // E-ISSNs final NodeList resultEissns = (NodeList) exprEissns.evaluate(doc, XPathConstants.NODESET); // get first eissn for (int z = 0; z < resultEissns.getLength(); z++) { final Node firstEissnsNode = resultEissns.item(i); final Element eissnElement = (Element) firstEissnsNode; final String eissn = getValue(eissnElement.getElementsByTagName("E_ISSN")); jd.setIssn(eissn); } } // add info link jd.setLink(infoLink.toString() + jourid); list.add(jd); } } } } catch (final XPathExpressionException e) { LOG.error(e.toString()); } catch (final SAXParseException e) { LOG.error(e.toString()); } catch (final SAXException e) { LOG.error(e.toString()); } catch (final IOException e) { LOG.error(e.toString()); } catch (final ParserConfigurationException e) { LOG.error(e.toString()); } catch (final Exception e) { LOG.error(e.toString()); } return list; } private List<String> getJourids(final String content) { final List<String> result = new ArrayList<String>(); try { if (content != null) { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(new InputSource(new StringReader(content))); final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); final XPathExpression exprJournals = xpath.compile("//journals/journal"); final NodeList journals = (NodeList) exprJournals.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < journals.getLength(); i++) { final Node firstResultNode = journals.item(i); final Element journal = (Element) firstResultNode; final String id = journal.getAttribute("jourid"); if (id != null) { result.add(id); } } } } catch (final XPathExpressionException e) { LOG.error(e.toString()); } catch (final SAXParseException e) { LOG.error(e.toString()); } catch (final SAXException e) { LOG.error(e.toString()); } catch (final IOException e) { LOG.error(e.toString()); } catch (final ParserConfigurationException e) { LOG.error(e.toString()); } catch (final Exception e) { LOG.error(e.toString()); } return result; } private String getValue(final NodeList list) { String result = null; final Element listElement = (Element) list.item(0); if (listElement != null) { final NodeList textList = listElement.getChildNodes(); if (textList.getLength() > 0) { result = StringEscapeUtils.unescapeXml(textList.item(0).getNodeValue()); } } return result; } }
gbv/doctor-doc
source/ch/dbs/actions/bestellung/EZBXML.java
Java
gpl-2.0
11,803
/* * linux/fs/namei.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * Some corrections by tytso. */ /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname * lookup logic. */ /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture. */ #include <linux/init.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/fsnotify.h> #include <linux/personality.h> #include <linux/security.h> #include <linux/ima.h> #include <linux/syscalls.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/capability.h> #include <linux/file.h> #include <linux/fcntl.h> #include <linux/device_cgroup.h> #include <linux/fs_struct.h> #include <linux/posix_acl.h> #include <linux/hash.h> #include <asm/uaccess.h> #include "internal.h" #include "mount.h" /* [Feb-1997 T. Schoebel-Theuer] * Fundamental changes in the pathname lookup mechanisms (namei) * were necessary because of omirr. The reason is that omirr needs * to know the _real_ pathname, not the user-supplied one, in case * of symlinks (and also when transname replacements occur). * * The new code replaces the old recursive symlink resolution with * an iterative one (in case of non-nested symlink chains). It does * this with calls to <fs>_follow_link(). * As a side effect, dir_namei(), _namei() and follow_link() are now * replaced with a single function lookup_dentry() that can handle all * the special cases of the former code. * * With the new dcache, the pathname is stored at each inode, at least as * long as the refcount of the inode is positive. As a side effect, the * size of the dcache depends on the inode cache and thus is dynamic. * * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink * resolution to correspond with current state of the code. * * Note that the symlink resolution is not *completely* iterative. * There is still a significant amount of tail- and mid- recursion in * the algorithm. Also, note that <fs>_readlink() is not used in * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink() * may return different results than <fs>_follow_link(). Many virtual * filesystems (including /proc) exhibit this behavior. */ /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation: * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL * and the name already exists in form of a symlink, try to create the new * name indicated by the symlink. The old code always complained that the * name already exists, due to not following the symlink even if its target * is nonexistent. The new semantics affects also mknod() and link() when * the name is a symlink pointing to a non-existent name. * * I don't know which semantics is the right one, since I have no access * to standards. But I found by trial that HP-UX 9.0 has the full "new" * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the * "old" one. Personally, I think the new semantics is much more logical. * Note that "ln old new" where "new" is a symlink pointing to a non-existing * file does succeed in both HP-UX and SunOs, but not in Solaris * and in the old Linux semantics. */ /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink * semantics. See the comments in "open_namei" and "do_link" below. * * [10-Sep-98 Alan Modra] Another symlink change. */ /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks: * inside the path - always follow. * in the last component in creation/removal/renaming - never follow. * if LOOKUP_FOLLOW passed - follow. * if the pathname has trailing slashes - follow. * otherwise - don't follow. * (applied in that order). * * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT * restored for 2.4. This is the last surviving part of old 4.2BSD bug. * During the 2.4 we need to fix the userland stuff depending on it - * hopefully we will be able to get rid of that wart in 2.5. So far only * XEmacs seems to be relying on it... */ /* * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland) * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives * any extra contention... */ /* In order to reduce some races, while at the same time doing additional * checking and hopefully speeding things up, we copy filenames to the * kernel data space before using them.. * * POSIX.1 2.4: an empty pathname is invalid (ENOENT). * PATH_MAX includes the nul terminator --RR. */ static int do_getname(const char __user *filename, char *page) { int retval; unsigned long len = PATH_MAX; if (!segment_eq(get_fs(), KERNEL_DS)) { if ((unsigned long) filename >= TASK_SIZE) return -EFAULT; if (TASK_SIZE - (unsigned long) filename < PATH_MAX) len = TASK_SIZE - (unsigned long) filename; } retval = strncpy_from_user(page, filename, len); if (retval > 0) { if (retval < len) return 0; return -ENAMETOOLONG; } else if (!retval) retval = -ENOENT; return retval; } static char *getname_flags(const char __user *filename, int flags, int *empty) { char *result = __getname(); int retval; if (!result) return ERR_PTR(-ENOMEM); retval = do_getname(filename, result); if (retval < 0) { if (retval == -ENOENT && empty) *empty = 1; if (retval != -ENOENT || !(flags & LOOKUP_EMPTY)) { __putname(result); return ERR_PTR(retval); } } audit_getname(result); return result; } char *getname(const char __user * filename) { return getname_flags(filename, 0, NULL); } #ifdef CONFIG_AUDITSYSCALL void putname(const char *name) { if (unlikely(!audit_dummy_context())) audit_putname(name); else __putname(name); } EXPORT_SYMBOL(putname); #endif static int check_acl(struct inode *inode, int mask) { #ifdef CONFIG_FS_POSIX_ACL struct posix_acl *acl; if (mask & MAY_NOT_BLOCK) { acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS); if (!acl) return -EAGAIN; /* no ->get_acl() calls in RCU mode... */ if (acl == ACL_NOT_CACHED) return -ECHILD; return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK); } acl = get_cached_acl(inode, ACL_TYPE_ACCESS); /* * A filesystem can force a ACL callback by just never filling the * ACL cache. But normally you'd fill the cache either at inode * instantiation time, or on the first ->get_acl call. * * If the filesystem doesn't have a get_acl() function at all, we'll * just create the negative cache entry. */ if (acl == ACL_NOT_CACHED) { if (inode->i_op->get_acl) { acl = inode->i_op->get_acl(inode, ACL_TYPE_ACCESS); if (IS_ERR(acl)) return PTR_ERR(acl); } else { set_cached_acl(inode, ACL_TYPE_ACCESS, NULL); return -EAGAIN; } } if (acl) { int error = posix_acl_permission(inode, acl, mask); posix_acl_release(acl); return error; } #endif return -EAGAIN; } /* * This does the basic permission checking */ static int acl_permission_check(struct inode *inode, int mask) { unsigned int mode = inode->i_mode; if (current_user_ns() != inode_userns(inode)) goto other_perms; if (likely(current_fsuid() == inode->i_uid)) mode >>= 6; else { if (IS_POSIXACL(inode) && (mode & S_IRWXG)) { int error = check_acl(inode, mask); if (error != -EAGAIN) return error; } if (in_group_p(inode->i_gid)) mode >>= 3; } other_perms: /* * If the DACs are ok we don't need any capability check. */ if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0) return 0; return -EACCES; } /** * generic_permission - check for access rights on a Posix-like filesystem * @inode: inode to check access rights for * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...) * * Used to check for read/write/execute permissions on a file. * We use "fsuid" for this, letting us set arbitrary permissions * for filesystem access without changing the "normal" uids which * are used for other things. * * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk * request cannot be satisfied (eg. requires blocking or too much complexity). * It would then be called again in ref-walk mode. */ int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (ns_capable(inode_userns(inode), CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (ns_capable(inode_userns(inode), CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (ns_capable(inode_userns(inode), CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (ns_capable(inode_userns(inode), CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * We _really_ want to just do "generic_permission()" without * even looking at the inode->i_op values. So we keep a cache * flag in inode->i_opflags, that says "this has not special * permission function, use the fast case". */ static inline int do_inode_permission(struct inode *inode, int mask) { if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) { if (likely(inode->i_op->permission)) return inode->i_op->permission(inode, mask); /* This gets set once for the inode lifetime */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_FASTPERM; spin_unlock(&inode->i_lock); } return generic_permission(inode, mask); } /** * inode_permission - check for access rights to a given inode * @inode: inode to check permission on * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...) * * Used to check for read/write/execute permissions on an inode. * We use "fsuid" for this, letting us set arbitrary permissions * for filesystem access without changing the "normal" uids which * are used for other things. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. */ int inode_permission(struct inode *inode, int mask) { int retval; if (unlikely(mask & MAY_WRITE)) { umode_t mode = inode->i_mode; /* * Nobody gets write access to a read-only fs. */ if (IS_RDONLY(inode) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) return -EROFS; /* * Nobody gets write access to an immutable file. */ if (IS_IMMUTABLE(inode)) return -EACCES; } retval = do_inode_permission(inode, mask); if (retval) return retval; retval = devcgroup_inode_permission(inode, mask); if (retval) return retval; return security_inode_permission(inode, mask); } /** * path_get - get a reference to a path * @path: path to get the reference to * * Given a path increment the reference count to the dentry and the vfsmount. */ void path_get(struct path *path) { mntget(path->mnt); dget(path->dentry); } EXPORT_SYMBOL(path_get); /** * path_put - put a reference to a path * @path: path to put the reference to * * Given a path decrement the reference count to the dentry and the vfsmount. */ void path_put(struct path *path) { dput(path->dentry); mntput(path->mnt); } EXPORT_SYMBOL(path_put); /* * Path walking has 2 modes, rcu-walk and ref-walk (see * Documentation/filesystems/path-lookup.txt). In situations when we can't * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab * normal reference counts on dentries and vfsmounts to transition to rcu-walk * mode. Refcounts are grabbed at the last known good point before rcu-walk * got stuck, so ref-walk may continue from there. If this is not successful * (eg. a seqcount has changed), then failure is returned and it's up to caller * to restart the path walk from the beginning in ref-walk mode. */ /** * unlazy_walk - try to switch to ref-walk mode. * @nd: nameidata pathwalk data * @dentry: child of nd->path.dentry or NULL * Returns: 0 on success, -ECHILD on failure * * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry * for ref-walk mode. @dentry must be a path found by a do_lookup call on * @nd or NULL. Must be called from rcu-walk context. */ static int unlazy_walk(struct nameidata *nd, struct dentry *dentry) { struct fs_struct *fs = current->fs; struct dentry *parent = nd->path.dentry; int want_root = 0; BUG_ON(!(nd->flags & LOOKUP_RCU)); if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { want_root = 1; spin_lock(&fs->lock); if (nd->root.mnt != fs->root.mnt || nd->root.dentry != fs->root.dentry) goto err_root; } spin_lock(&parent->d_lock); if (!dentry) { if (!__d_rcu_to_refcount(parent, nd->seq)) goto err_parent; BUG_ON(nd->inode != parent->d_inode); } else { if (dentry->d_parent != parent) goto err_parent; spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); if (!__d_rcu_to_refcount(dentry, nd->seq)) goto err_child; /* * If the sequence check on the child dentry passed, then * the child has not been removed from its parent. This * means the parent dentry must be valid and able to take * a reference at this point. */ BUG_ON(!IS_ROOT(dentry) && dentry->d_parent != parent); BUG_ON(!parent->d_count); parent->d_count++; spin_unlock(&dentry->d_lock); } spin_unlock(&parent->d_lock); if (want_root) { path_get(&nd->root); spin_unlock(&fs->lock); } mntget(nd->path.mnt); rcu_read_unlock(); br_read_unlock(&vfsmount_lock); nd->flags &= ~LOOKUP_RCU; return 0; err_child: spin_unlock(&dentry->d_lock); err_parent: spin_unlock(&parent->d_lock); err_root: if (want_root) spin_unlock(&fs->lock); return -ECHILD; } /** * release_open_intent - free up open intent resources * @nd: pointer to nameidata */ void release_open_intent(struct nameidata *nd) { struct file *file = nd->intent.open.file; if (file && !IS_ERR(file)) { if (file->f_path.dentry == NULL) put_filp(file); else fput(file); } } static inline int d_revalidate(struct dentry *dentry, struct nameidata *nd) { return dentry->d_op->d_revalidate(dentry, nd); } /** * complete_walk - successful completion of path walk * @nd: pointer nameidata * * If we had been in RCU mode, drop out of it and legitimize nd->path. * Revalidate the final result, unless we'd already done that during * the path walk or the filesystem doesn't ask for it. Return 0 on * success, -error on failure. In case of failure caller does not * need to drop nd->path. */ static int complete_walk(struct nameidata *nd) { struct dentry *dentry = nd->path.dentry; int status; if (nd->flags & LOOKUP_RCU) { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; spin_lock(&dentry->d_lock); if (unlikely(!__d_rcu_to_refcount(dentry, nd->seq))) { spin_unlock(&dentry->d_lock); rcu_read_unlock(); br_read_unlock(&vfsmount_lock); return -ECHILD; } BUG_ON(nd->inode != dentry->d_inode); spin_unlock(&dentry->d_lock); mntget(nd->path.mnt); rcu_read_unlock(); br_read_unlock(&vfsmount_lock); } if (likely(!(nd->flags & LOOKUP_JUMPED))) return 0; if (likely(!(dentry->d_flags & DCACHE_OP_REVALIDATE))) return 0; if (likely(!(dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT))) return 0; /* Note: we do not d_invalidate() */ status = d_revalidate(dentry, nd); if (status > 0) return 0; if (!status) status = -ESTALE; path_put(&nd->path); return status; } static __always_inline void set_root(struct nameidata *nd) { if (!nd->root.mnt) get_fs_root(current->fs, &nd->root); } static int link_path_walk(const char *, struct nameidata *); static __always_inline void set_root_rcu(struct nameidata *nd) { if (!nd->root.mnt) { struct fs_struct *fs = current->fs; unsigned seq; do { seq = read_seqcount_begin(&fs->seq); nd->root = fs->root; nd->seq = __read_seqcount_begin(&nd->root.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } } static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link) { int ret; if (IS_ERR(link)) goto fail; if (*link == '/') { set_root(nd); path_put(&nd->path); nd->path = nd->root; path_get(&nd->root); nd->flags |= LOOKUP_JUMPED; } nd->inode = nd->path.dentry->d_inode; ret = link_path_walk(link, nd); return ret; fail: path_put(&nd->path); return PTR_ERR(link); } static void path_put_conditional(struct path *path, struct nameidata *nd) { dput(path->dentry); if (path->mnt != nd->path.mnt) mntput(path->mnt); } static inline void path_to_nameidata(const struct path *path, struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { dput(nd->path.dentry); if (nd->path.mnt != path->mnt) mntput(nd->path.mnt); } nd->path.mnt = path->mnt; nd->path.dentry = path->dentry; } static inline void put_link(struct nameidata *nd, struct path *link, void *cookie) { struct inode *inode = link->dentry->d_inode; if (!IS_ERR(cookie) && inode->i_op->put_link) inode->i_op->put_link(link->dentry, nd, cookie); path_put(link); } static __always_inline int follow_link(struct path *link, struct nameidata *nd, void **p) { int error; struct dentry *dentry = link->dentry; BUG_ON(nd->flags & LOOKUP_RCU); if (link->mnt == nd->path.mnt) mntget(link->mnt); if (unlikely(current->total_link_count >= 40)) { *p = ERR_PTR(-ELOOP); /* no ->put_link(), please */ path_put(&nd->path); return -ELOOP; } cond_resched(); current->total_link_count++; touch_atime(link); nd_set_link(nd, NULL); error = security_inode_follow_link(link->dentry, nd); if (error) { *p = ERR_PTR(error); /* no ->put_link(), please */ path_put(&nd->path); return error; } nd->last_type = LAST_BIND; *p = dentry->d_inode->i_op->follow_link(dentry, nd); error = PTR_ERR(*p); if (!IS_ERR(*p)) { char *s = nd_get_link(nd); error = 0; if (s) error = __vfs_follow_link(nd, s); else if (nd->last_type == LAST_BIND) { nd->flags |= LOOKUP_JUMPED; nd->inode = nd->path.dentry->d_inode; if (nd->inode->i_op->follow_link) { /* stepped on a _really_ weird one */ path_put(&nd->path); error = -ELOOP; } } } return error; } static int follow_up_rcu(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; parent = mnt->mnt_parent; if (&parent->mnt == path->mnt) return 0; mountpoint = mnt->mnt_mountpoint; path->dentry = mountpoint; path->mnt = &parent->mnt; return 1; } /* * follow_up - Find the mountpoint of path's vfsmount * * Given a path, find the mountpoint of its source file system. * Replace @path with the path of the mountpoint in the parent mount. * Up is towards /. * * Return 1 if we went up a level and 0 if we were already at the * root. */ int follow_up(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; br_read_lock(&vfsmount_lock); parent = mnt->mnt_parent; if (&parent->mnt == path->mnt) { br_read_unlock(&vfsmount_lock); return 0; } mntget(&parent->mnt); mountpoint = dget(mnt->mnt_mountpoint); br_read_unlock(&vfsmount_lock); dput(path->dentry); path->dentry = mountpoint; mntput(path->mnt); path->mnt = &parent->mnt; return 1; } /* * Perform an automount * - return -EISDIR to tell follow_managed() to stop and return the path we * were called with. */ static int follow_automount(struct path *path, unsigned flags, bool *need_mntput) { struct vfsmount *mnt; int err; if (!path->dentry->d_op || !path->dentry->d_op->d_automount) return -EREMOTE; /* We don't want to mount if someone's just doing a stat - * unless they're stat'ing a directory and appended a '/' to * the name. * * We do, however, want to mount if someone wants to open or * create a file of any type under the mountpoint, wants to * traverse through the mountpoint or wants to open the * mounted directory. Also, autofs may mark negative dentries * as being automount points. These will need the attentions * of the daemon to instantiate them before they can be used. */ if (!(flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY | LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) && path->dentry->d_inode) return -EISDIR; current->total_link_count++; if (current->total_link_count >= 40) return -ELOOP; mnt = path->dentry->d_op->d_automount(path); if (IS_ERR(mnt)) { /* * The filesystem is allowed to return -EISDIR here to indicate * it doesn't want to automount. For instance, autofs would do * this so that its userspace daemon can mount on this dentry. * * However, we can only permit this if it's a terminal point in * the path being looked up; if it wasn't then the remainder of * the path is inaccessible and we should say so. */ if (PTR_ERR(mnt) == -EISDIR && (flags & LOOKUP_PARENT)) return -EREMOTE; return PTR_ERR(mnt); } if (!mnt) /* mount collision */ return 0; if (!*need_mntput) { /* lock_mount() may release path->mnt on error */ mntget(path->mnt); *need_mntput = true; } err = finish_automount(mnt, path); switch (err) { case -EBUSY: /* Someone else made a mount here whilst we were busy */ return 0; case 0: path_put(path); path->mnt = mnt; path->dentry = dget(mnt->mnt_root); return 0; default: return err; } } /* * Handle a dentry that is managed in some way. * - Flagged for transit management (autofs) * - Flagged as mountpoint * - Flagged as automount point * * This may only be called in refwalk mode. * * Serialization is taken care of in namespace.c */ static int follow_managed(struct path *path, unsigned flags) { struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */ unsigned managed; bool need_mntput = false; int ret = 0; /* Given that we're not holding a lock here, we retain the value in a * local variable for each dentry as we look at it so that we don't see * the components of that value change under us */ while (managed = ACCESS_ONCE(path->dentry->d_flags), managed &= DCACHE_MANAGED_DENTRY, unlikely(managed != 0)) { /* Allow the filesystem to manage the transit without i_mutex * being held. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage(path->dentry, false); if (ret < 0) break; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); if (need_mntput) mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); need_mntput = true; continue; } /* Something is mounted on this dentry in another * namespace and/or whatever was mounted there in this * namespace got unmounted before we managed to get the * vfsmount_lock */ } /* Handle an automount point */ if (managed & DCACHE_NEED_AUTOMOUNT) { ret = follow_automount(path, flags, &need_mntput); if (ret < 0) break; continue; } /* We didn't change the current path point */ break; } if (need_mntput && path->mnt == mnt) mntput(path->mnt); if (ret == -EISDIR) ret = 0; return ret < 0 ? ret : need_mntput; } int follow_down_one(struct path *path) { struct vfsmount *mounted; mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); return 1; } return 0; } static inline bool managed_dentry_might_block(struct dentry *dentry) { return (dentry->d_flags & DCACHE_MANAGE_TRANSIT && dentry->d_op->d_manage(dentry, true) < 0); } /* * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if * we meet a managed dentry that would need blocking. */ static bool __follow_mount_rcu(struct nameidata *nd, struct path *path, struct inode **inode) { for (;;) { struct mount *mounted; /* * Don't forget we might have a non-mountpoint managed dentry * that wants to block transit. */ if (unlikely(managed_dentry_might_block(path->dentry))) return false; if (!d_mountpoint(path->dentry)) break; mounted = __lookup_mnt(path->mnt, path->dentry, 1); if (!mounted) break; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |= LOOKUP_JUMPED; nd->seq = read_seqcount_begin(&path->dentry->d_seq); /* * Update the inode too. We don't need to re-check the * dentry sequence number here after this d_inode read, * because a mount-point is always pinned. */ *inode = path->dentry->d_inode; } return true; } static void follow_mount_rcu(struct nameidata *nd) { while (d_mountpoint(nd->path.dentry)) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry, 1); if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } } static int follow_dotdot_rcu(struct nameidata *nd) { set_root_rcu(nd); while (1) { if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; seq = read_seqcount_begin(&parent->d_seq); if (read_seqcount_retry(&old->d_seq, nd->seq)) goto failed; nd->path.dentry = parent; nd->seq = seq; break; } if (!follow_up_rcu(&nd->path)) break; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } follow_mount_rcu(nd); nd->inode = nd->path.dentry->d_inode; return 0; failed: nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); br_read_unlock(&vfsmount_lock); return -ECHILD; } /* * Follow down to the covering mount currently visible to userspace. At each * point, the filesystem owning that dentry may be queried as to whether the * caller is permitted to proceed or not. */ int follow_down(struct path *path) { unsigned managed; int ret; while (managed = ACCESS_ONCE(path->dentry->d_flags), unlikely(managed & DCACHE_MANAGED_DENTRY)) { /* Allow the filesystem to manage the transit without i_mutex * being held. * * We indicate to the filesystem if someone is trying to mount * something here. This gives autofs the chance to deny anyone * other than its daemon the right to mount on its * superstructure. * * The filesystem may sleep at this point. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage( path->dentry, false); if (ret < 0) return ret == -EISDIR ? 0 : ret; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); continue; } /* Don't handle automount points here */ break; } return 0; } /* * Skip to top of mountpoint pile in refwalk mode for follow_dotdot() */ static void follow_mount(struct path *path) { while (d_mountpoint(path->dentry)) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); } } static void follow_dotdot(struct nameidata *nd) { set_root(nd); while(1) { struct dentry *old = nd->path.dentry; if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { /* rare case of legitimate dget_parent()... */ nd->path.dentry = dget_parent(nd->path.dentry); dput(old); break; } if (!follow_up(&nd->path)) break; } follow_mount(&nd->path); nd->inode = nd->path.dentry->d_inode; } /* * This looks up the name in dcache, possibly revalidates the old dentry and * allocates a new one if not found or not valid. In the need_lookup argument * returns whether i_op->lookup is necessary. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir, struct nameidata *nd, bool *need_lookup) { struct dentry *dentry; int error; *need_lookup = false; dentry = d_lookup(dir, name); if (dentry) { if (d_need_lookup(dentry)) { *need_lookup = true; } else if (dentry->d_flags & DCACHE_OP_REVALIDATE) { error = d_revalidate(dentry, nd); if (unlikely(error <= 0)) { if (error < 0) { dput(dentry); return ERR_PTR(error); } else if (!d_invalidate(dentry)) { dput(dentry); dentry = NULL; } } } } if (!dentry) { dentry = d_alloc(dir, name); if (unlikely(!dentry)) return ERR_PTR(-ENOMEM); *need_lookup = true; } return dentry; } /* * Call i_op->lookup on the dentry. The dentry must be negative but may be * hashed if it was pouplated with DCACHE_NEED_LOOKUP. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct dentry *old; /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { dput(dentry); return ERR_PTR(-ENOENT); } old = dir->i_op->lookup(dir, dentry, nd); if (unlikely(old)) { dput(dentry); dentry = old; } return dentry; } static struct dentry *__lookup_hash(struct qstr *name, struct dentry *base, struct nameidata *nd) { bool need_lookup; struct dentry *dentry; dentry = lookup_dcache(name, base, nd, &need_lookup); if (!need_lookup) return dentry; return lookup_real(base->d_inode, dentry, nd); } /* * It's more convoluted than I'd like it to be, but... it's still fairly * small and for now I'd prefer to have fast path as straight as possible. * It _is_ time-critical. */ static int do_lookup(struct nameidata *nd, struct qstr *name, struct path *path, struct inode **inode) { struct vfsmount *mnt = nd->path.mnt; struct dentry *dentry, *parent = nd->path.dentry; int need_reval = 1; int status = 1; int err; /* * Rename seqlock is not required here because in the off chance * of a false negative due to a concurrent rename, we're going to * do the non-racy lookup, below. */ if (nd->flags & LOOKUP_RCU) { unsigned seq; *inode = nd->inode; dentry = __d_lookup_rcu(parent, name, &seq, inode); if (!dentry) goto unlazy; /* Memory barrier in read_seqcount_begin of child is enough */ if (__read_seqcount_retry(&parent->d_seq, nd->seq)) return -ECHILD; nd->seq = seq; if (unlikely(d_need_lookup(dentry))) goto unlazy; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) { status = d_revalidate(dentry, nd); if (unlikely(status <= 0)) { if (status != -ECHILD) need_reval = 0; goto unlazy; } } path->mnt = mnt; path->dentry = dentry; if (unlikely(!__follow_mount_rcu(nd, path, inode))) goto unlazy; if (unlikely(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT)) goto unlazy; return 0; unlazy: if (unlazy_walk(nd, dentry)) return -ECHILD; } else { dentry = __d_lookup(parent, name); } if (unlikely(!dentry)) goto need_lookup; if (unlikely(d_need_lookup(dentry))) { dput(dentry); goto need_lookup; } if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval) status = d_revalidate(dentry, nd); if (unlikely(status <= 0)) { if (status < 0) { dput(dentry); return status; } if (!d_invalidate(dentry)) { dput(dentry); goto need_lookup; } } done: path->mnt = mnt; path->dentry = dentry; err = follow_managed(path, nd->flags); if (unlikely(err < 0)) { path_put_conditional(path, nd); return err; } if (err) nd->flags |= LOOKUP_JUMPED; *inode = path->dentry->d_inode; return 0; need_lookup: BUG_ON(nd->inode != parent->d_inode); mutex_lock(&parent->d_inode->i_mutex); dentry = __lookup_hash(name, parent, nd); mutex_unlock(&parent->d_inode->i_mutex); if (IS_ERR(dentry)) return PTR_ERR(dentry); goto done; } static inline int may_lookup(struct nameidata *nd) { if (nd->flags & LOOKUP_RCU) { int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK); if (err != -ECHILD) return err; if (unlazy_walk(nd, NULL)) return -ECHILD; } return inode_permission(nd->inode, MAY_EXEC); } static inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { if (follow_dotdot_rcu(nd)) return -ECHILD; } else follow_dotdot(nd); } return 0; } static void terminate_walk(struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { path_put(&nd->path); } else { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); br_read_unlock(&vfsmount_lock); } } /* * Do we need to follow links? We _really_ want to be able * to do this check without having to look at inode->i_op, * so we keep a cache of "no, this doesn't need follow_link" * for the common case. */ static inline int should_follow_link(struct inode *inode, int follow) { if (unlikely(!(inode->i_opflags & IOP_NOFOLLOW))) { if (likely(inode->i_op->follow_link)) return follow; /* This gets set once for the inode lifetime */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_NOFOLLOW; spin_unlock(&inode->i_lock); } return 0; } static inline int walk_component(struct nameidata *nd, struct path *path, struct qstr *name, int type, int follow) { struct inode *inode; int err; /* * "." and ".." are special - ".." especially so because it has * to be able to know about the current root directory and * parent relationships. */ if (unlikely(type != LAST_NORM)) return handle_dots(nd, type); err = do_lookup(nd, name, path, &inode); if (unlikely(err)) { terminate_walk(nd); return err; } if (!inode) { path_to_nameidata(path, nd); terminate_walk(nd); return -ENOENT; } if (should_follow_link(inode, follow)) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, path->dentry))) { terminate_walk(nd); return -ECHILD; } } BUG_ON(inode != path->dentry->d_inode); return 1; } path_to_nameidata(path, nd); nd->inode = inode; return 0; } /* * This limits recursive symlink follows to 8, while * limiting consecutive symlinks to 40. * * Without that kind of total limit, nasty chains of consecutive * symlinks can cause almost arbitrarily long lookups. */ static inline int nested_symlink(struct path *path, struct nameidata *nd) { int res; if (unlikely(current->link_count >= MAX_NESTED_LINKS)) { path_put_conditional(path, nd); path_put(&nd->path); return -ELOOP; } BUG_ON(nd->depth >= MAX_NESTED_LINKS); nd->depth++; current->link_count++; do { struct path link = *path; void *cookie; res = follow_link(&link, nd, &cookie); if (!res) res = walk_component(nd, path, &nd->last, nd->last_type, LOOKUP_FOLLOW); put_link(nd, &link, cookie); } while (res > 0); current->link_count--; nd->depth--; return res; } /* * We really don't want to look at inode->i_op->lookup * when we don't have to. So we keep a cache bit in * the inode ->i_opflags field that says "yes, we can * do lookup on this inode". */ static inline int can_lookup(struct inode *inode) { if (likely(inode->i_opflags & IOP_LOOKUP)) return 1; if (likely(!inode->i_op->lookup)) return 0; /* We do this once for the lifetime of the inode */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_LOOKUP; spin_unlock(&inode->i_lock); return 1; } /* * We can do the critical dentry name comparison and hashing * operations one word at a time, but we are limited to: * * - Architectures with fast unaligned word accesses. We could * do a "get_unaligned()" if this helps and is sufficiently * fast. * * - Little-endian machines (so that we can generate the mask * of low bytes efficiently). Again, we *could* do a byte * swapping load on big-endian architectures if that is not * expensive enough to make the optimization worthless. * * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we * do not trap on the (extremely unlikely) case of a page * crossing operation. * * - Furthermore, we need an efficient 64-bit compile for the * 64-bit case in order to generate the "number of bytes in * the final mask". Again, that could be replaced with a * efficient population count instruction or similar. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> #ifdef CONFIG_64BIT static inline unsigned int fold_hash(unsigned long hash) { return hash_64(hash, 32); } #else /* 32-bit case */ #define fold_hash(x) (x) #endif unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long a, mask; unsigned long hash = 0; for (;;) { a = load_unaligned_zeropad(name); if (len < sizeof(unsigned long)) break; hash += a; hash *= 9; name += sizeof(unsigned long); len -= sizeof(unsigned long); if (!len) goto done; } mask = ~(~0ul << len*8); hash += mask & a; done: return fold_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * Calculate the length and hash of the path component, and * return the length of the component; */ static inline unsigned long hash_name(const char *name, unsigned int *hashp) { unsigned long a, mask, hash, len; hash = a = 0; len = -sizeof(unsigned long); do { hash = (hash + a) * 9; len += sizeof(unsigned long); a = load_unaligned_zeropad(name+len); /* Do we have any NUL or '/' bytes in this word? */ mask = has_zero(a) | has_zero(a ^ REPEAT_BYTE('/')); } while (!mask); /* The mask *below* the first high bit set */ mask = (mask - 1) & ~mask; mask >>= 7; hash += a & mask; *hashp = fold_hash(hash); return len + count_masked_bytes(mask); } #else unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long hash = init_name_hash(); while (len--) hash = partial_name_hash(*name++, hash); return end_name_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * We know there's a real path component here of at least * one character. */ static inline unsigned long hash_name(const char *name, unsigned int *hashp) { unsigned long hash = init_name_hash(); unsigned long len = 0, c; c = (unsigned char)*name; do { len++; hash = partial_name_hash(c, hash); c = (unsigned char)name[len]; } while (c && c != '/'); *hashp = end_name_hash(hash); return len; } #endif /* * Name resolution. * This is the basic name resolution function, turning a pathname into * the final dentry. We expect 'base' to be positive and a directory. * * Returns 0 and nd will have valid dentry and mnt on success. * Returns error and drops reference to input namei data on failure. */ static int link_path_walk(const char *name, struct nameidata *nd) { struct path next; int err; while (*name=='/') name++; if (!*name) return 0; /* At this point we know we have a real path component. */ for(;;) { struct qstr this; long len; int type; err = may_lookup(nd); if (err) break; len = hash_name(name, &this.hash); this.name = name; this.len = len; type = LAST_NORM; if (name[0] == '.') switch (len) { case 2: if (name[1] == '.') { type = LAST_DOTDOT; nd->flags |= LOOKUP_JUMPED; } break; case 1: type = LAST_DOT; } if (likely(type == LAST_NORM)) { struct dentry *parent = nd->path.dentry; nd->flags &= ~LOOKUP_JUMPED; if (unlikely(parent->d_flags & DCACHE_OP_HASH)) { err = parent->d_op->d_hash(parent, nd->inode, &this); if (err < 0) break; } } if (!name[len]) goto last_component; /* * If it wasn't NUL, we know it was '/'. Skip that * slash, and continue until no more slashes. */ do { len++; } while (unlikely(name[len] == '/')); if (!name[len]) goto last_component; name += len; err = walk_component(nd, &next, &this, type, LOOKUP_FOLLOW); if (err < 0) return err; if (err) { err = nested_symlink(&next, nd); if (err) return err; } if (can_lookup(nd->inode)) continue; err = -ENOTDIR; break; /* here ends the main loop */ last_component: nd->last = this; nd->last_type = type; return 0; } terminate_walk(nd); return err; } static int path_init(int dfd, const char *name, unsigned int flags, struct nameidata *nd, struct file **fp) { int retval = 0; int fput_needed; struct file *file; nd->last_type = LAST_ROOT; /* if there are only slashes... */ nd->flags = flags | LOOKUP_JUMPED; nd->depth = 0; if (flags & LOOKUP_ROOT) { struct inode *inode = nd->root.dentry->d_inode; if (*name) { if (!inode->i_op->lookup) return -ENOTDIR; retval = inode_permission(inode, MAY_EXEC); if (retval) return retval; } nd->path = nd->root; nd->inode = inode; if (flags & LOOKUP_RCU) { br_read_lock(&vfsmount_lock); rcu_read_lock(); nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); } else { path_get(&nd->path); } return 0; } nd->root.mnt = NULL; if (*name=='/') { if (flags & LOOKUP_RCU) { br_read_lock(&vfsmount_lock); rcu_read_lock(); set_root_rcu(nd); } else { set_root(nd); path_get(&nd->root); } nd->path = nd->root; } else if (dfd == AT_FDCWD) { if (flags & LOOKUP_RCU) { struct fs_struct *fs = current->fs; unsigned seq; br_read_lock(&vfsmount_lock); rcu_read_lock(); do { seq = read_seqcount_begin(&fs->seq); nd->path = fs->pwd; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } else { get_fs_pwd(current->fs, &nd->path); } } else { struct dentry *dentry; file = fget_raw_light(dfd, &fput_needed); retval = -EBADF; if (!file) goto out_fail; dentry = file->f_path.dentry; if (*name) { retval = -ENOTDIR; if (!S_ISDIR(dentry->d_inode->i_mode)) goto fput_fail; retval = inode_permission(dentry->d_inode, MAY_EXEC); if (retval) goto fput_fail; } nd->path = file->f_path; if (flags & LOOKUP_RCU) { if (fput_needed) *fp = file; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); br_read_lock(&vfsmount_lock); rcu_read_lock(); } else { path_get(&file->f_path); fput_light(file, fput_needed); } } nd->inode = nd->path.dentry->d_inode; return 0; fput_fail: fput_light(file, fput_needed); out_fail: return retval; } static inline int lookup_last(struct nameidata *nd, struct path *path) { if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; nd->flags &= ~LOOKUP_PARENT; return walk_component(nd, path, &nd->last, nd->last_type, nd->flags & LOOKUP_FOLLOW); } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_lookupat(int dfd, const char *name, unsigned int flags, struct nameidata *nd) { struct file *base = NULL; struct path path; int err; /* * Path walking is largely split up into 2 different synchronisation * schemes, rcu-walk and ref-walk (explained in * Documentation/filesystems/path-lookup.txt). These share much of the * path walk code, but some things particularly setup, cleanup, and * following mounts are sufficiently divergent that functions are * duplicated. Typically there is a function foo(), and its RCU * analogue, foo_rcu(). * * -ECHILD is the error number of choice (just to avoid clashes) that * is returned if some aspect of an rcu-walk fails. Such an error must * be handled by restarting a traditional ref-walk (which will always * be able to complete). */ err = path_init(dfd, name, flags | LOOKUP_PARENT, nd, &base); if (unlikely(err)) goto out; current->total_link_count = 0; err = link_path_walk(name, nd); if (!err && !(flags & LOOKUP_PARENT)) { err = lookup_last(nd, &path); while (err > 0) { void *cookie; struct path link = path; nd->flags |= LOOKUP_PARENT; err = follow_link(&link, nd, &cookie); if (!err) err = lookup_last(nd, &path); put_link(nd, &link, cookie); } } if (!err) err = complete_walk(nd); if (!err && nd->flags & LOOKUP_DIRECTORY) { if (!nd->inode->i_op->lookup) { path_put(&nd->path); err = -ENOTDIR; } } out: if (base) fput(base); if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { path_put(&nd->root); nd->root.mnt = NULL; } return err; } static int do_path_lookup(int dfd, const char *name, unsigned int flags, struct nameidata *nd) { int retval = path_lookupat(dfd, name, flags | LOOKUP_RCU, nd); if (unlikely(retval == -ECHILD)) retval = path_lookupat(dfd, name, flags, nd); if (unlikely(retval == -ESTALE)) retval = path_lookupat(dfd, name, flags | LOOKUP_REVAL, nd); if (likely(!retval)) { if (unlikely(!audit_dummy_context())) { if (nd->path.dentry && nd->inode) audit_inode(name, nd->path.dentry); } } return retval; } /* does lookup, returns the object with parent locked */ struct dentry *kern_path_locked(const char *name, struct path *path) { struct nameidata nd; struct dentry *d; int err = do_path_lookup(AT_FDCWD, name, LOOKUP_PARENT, &nd); if (err) return ERR_PTR(err); if (nd.last_type != LAST_NORM) { path_put(&nd.path); return ERR_PTR(-EINVAL); } mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); d = lookup_one_len(nd.last.name, nd.path.dentry, nd.last.len); if (IS_ERR(d)) { mutex_unlock(&nd.path.dentry->d_inode->i_mutex); path_put(&nd.path); return d; } *path = nd.path; return d; } int kern_path(const char *name, unsigned int flags, struct path *path) { struct nameidata nd; int res = do_path_lookup(AT_FDCWD, name, flags, &nd); if (!res) *path = nd.path; return res; } /** * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair * @dentry: pointer to dentry of the base directory * @mnt: pointer to vfs mount of the base directory * @name: pointer to file name * @flags: lookup flags * @path: pointer to struct path to fill */ int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt, const char *name, unsigned int flags, struct path *path) { struct nameidata nd; int err; nd.root.dentry = dentry; nd.root.mnt = mnt; BUG_ON(flags & LOOKUP_PARENT); /* the first argument of do_path_lookup() is ignored with LOOKUP_ROOT */ err = do_path_lookup(AT_FDCWD, name, flags | LOOKUP_ROOT, &nd); if (!err) *path = nd.path; return err; } /* * Restricted form of lookup. Doesn't follow links, single-component only, * needs parent already locked. Doesn't follow mounts. * SMP-safe. */ static struct dentry *lookup_hash(struct nameidata *nd) { return __lookup_hash(&nd->last, nd->path.dentry, nd); } /** * lookup_one_len - filesystem helper to lookup single pathname component * @name: pathname component to lookup * @base: base directory to lookup from * @len: maximum length @len should be interpreted to * * Note that this routine is purely a helper for filesystem usage and should * not be called by generic code. Also note that by using this function the * nameidata argument is passed to the filesystem methods and a filesystem * using this helper needs to be prepared for that. */ struct dentry *lookup_one_len(const char *name, struct dentry *base, int len) { struct qstr this; unsigned int c; int err; WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex)); this.name = name; this.len = len; this.hash = full_name_hash(name, len); if (!len) return ERR_PTR(-EACCES); while (len--) { c = *(const unsigned char *)name++; if (c == '/' || c == '\0') return ERR_PTR(-EACCES); } /* * See if the low-level filesystem might want * to use its own hash.. */ if (base->d_flags & DCACHE_OP_HASH) { int err = base->d_op->d_hash(base, base->d_inode, &this); if (err < 0) return ERR_PTR(err); } err = inode_permission(base->d_inode, MAY_EXEC); if (err) return ERR_PTR(err); return __lookup_hash(&this, base, NULL); } int user_path_at_empty(int dfd, const char __user *name, unsigned flags, struct path *path, int *empty) { struct nameidata nd; char *tmp = getname_flags(name, flags, empty); int err = PTR_ERR(tmp); if (!IS_ERR(tmp)) { BUG_ON(flags & LOOKUP_PARENT); err = do_path_lookup(dfd, tmp, flags, &nd); putname(tmp); if (!err) *path = nd.path; } return err; } int user_path_at(int dfd, const char __user *name, unsigned flags, struct path *path) { return user_path_at_empty(dfd, name, flags, path, NULL); } static int user_path_parent(int dfd, const char __user *path, struct nameidata *nd, char **name) { char *s = getname(path); int error; if (IS_ERR(s)) return PTR_ERR(s); error = do_path_lookup(dfd, s, LOOKUP_PARENT, nd); if (error) putname(s); else *name = s; return error; } /* * It's inline, so penalty for filesystems that don't use sticky bit is * minimal. */ static inline int check_sticky(struct inode *dir, struct inode *inode) { uid_t fsuid = current_fsuid(); if (!(dir->i_mode & S_ISVTX)) return 0; if (current_user_ns() != inode_userns(inode)) goto other_userns; if (inode->i_uid == fsuid) return 0; if (dir->i_uid == fsuid) return 0; other_userns: return !ns_capable(inode_userns(inode), CAP_FOWNER); } /* * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do antyhing with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int may_delete(struct inode *dir,struct dentry *victim,int isdir) { int error; if (!victim->d_inode) return -ENOENT; BUG_ON(victim->d_parent->d_inode != dir); audit_inode_child(victim, dir); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)|| IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode)) return -EPERM; if (isdir) { if (!S_ISDIR(victim->d_inode->i_mode)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (S_ISDIR(victim->d_inode->i_mode)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* Check whether we can create an object with dentry child in directory * dir. * 1. We can't do it if child already exists (open has special treatment for * this case, but since we are inlined it's OK) * 2. We can't do it if dir is read-only (done in permission()) * 3. We should have write and exec permissions on dir * 4. We can't do it if dir is immutable (done in permission()) */ static inline int may_create(struct inode *dir, struct dentry *child) { if (child->d_inode) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * p1 and p2 should be directories on the same fs. */ struct dentry *lock_rename(struct dentry *p1, struct dentry *p2) { struct dentry *p; if (p1 == p2) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); return NULL; } mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex); p = d_ancestor(p2, p1); if (p) { mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD); return p; } p = d_ancestor(p1, p2); if (p) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return p; } mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return NULL; } void unlock_rename(struct dentry *p1, struct dentry *p2) { mutex_unlock(&p1->d_inode->i_mutex); if (p1 != p2) { mutex_unlock(&p2->d_inode->i_mutex); mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex); } } int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, struct nameidata *nd) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->create) return -EACCES; /* shouldn't it be ENOSYS? */ mode &= S_IALLUGO; mode |= S_IFREG; error = security_inode_create(dir, dentry, mode); if (error) return error; error = dir->i_op->create(dir, dentry, mode, nd); if (!error) fsnotify_create(dir, dentry); return error; } static int may_open(struct path *path, int acc_mode, int flag) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; int error; /* O_PATH? */ if (!acc_mode) return 0; if (!inode) return -ENOENT; switch (inode->i_mode & S_IFMT) { case S_IFLNK: return -ELOOP; case S_IFDIR: if (acc_mode & MAY_WRITE) return -EISDIR; break; case S_IFBLK: case S_IFCHR: if (path->mnt->mnt_flags & MNT_NODEV) return -EACCES; /*FALLTHRU*/ case S_IFIFO: case S_IFSOCK: flag &= ~O_TRUNC; break; } error = inode_permission(inode, acc_mode); if (error) return error; /* * An append-only file must be opened in append mode for writing. */ if (IS_APPEND(inode)) { if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND)) return -EPERM; if (flag & O_TRUNC) return -EPERM; } /* O_NOATIME can only be set by the owner or superuser */ if (flag & O_NOATIME && !inode_owner_or_capable(inode)) return -EPERM; return 0; } static int handle_truncate(struct file *filp) { struct path *path = &filp->f_path; struct inode *inode = path->dentry->d_inode; int error = get_write_access(inode); if (error) return error; /* * Refuse to truncate files with mandatory locks held on them. */ error = locks_verify_locked(inode); if (!error) error = security_path_truncate(path); if (!error) { error = do_truncate(path->dentry, 0, ATTR_MTIME|ATTR_CTIME|ATTR_OPEN, filp); } put_write_access(inode); return error; } static inline int open_to_namei_flags(int flag) { if ((flag & O_ACCMODE) == 3) flag--; return flag; } /* * Handle the last step of open() */ static struct file *do_last(struct nameidata *nd, struct path *path, const struct open_flags *op, const char *pathname) { struct dentry *dir = nd->path.dentry; struct dentry *dentry; int open_flag = op->open_flag; int will_truncate = open_flag & O_TRUNC; int want_write = 0; int acc_mode = op->acc_mode; struct file *filp; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; switch (nd->last_type) { case LAST_DOTDOT: case LAST_DOT: error = handle_dots(nd, nd->last_type); if (error) return ERR_PTR(error); /* fallthrough */ case LAST_ROOT: error = complete_walk(nd); if (error) return ERR_PTR(error); audit_inode(pathname, nd->path.dentry); if (open_flag & O_CREAT) { error = -EISDIR; goto exit; } goto ok; case LAST_BIND: error = complete_walk(nd); if (error) return ERR_PTR(error); audit_inode(pathname, dir); goto ok; } if (!(open_flag & O_CREAT)) { int symlink_ok = 0; if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW)) symlink_ok = 1; /* we _can_ be in RCU mode here */ error = walk_component(nd, path, &nd->last, LAST_NORM, !symlink_ok); if (error < 0) return ERR_PTR(error); if (error) /* symlink */ return NULL; /* sayonara */ error = complete_walk(nd); if (error) return ERR_PTR(error); error = -ENOTDIR; if (nd->flags & LOOKUP_DIRECTORY) { if (!nd->inode->i_op->lookup) goto exit; } audit_inode(pathname, nd->path.dentry); goto ok; } /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED has been * cleared when we got to the last component we are about to look up */ error = complete_walk(nd); if (error) return ERR_PTR(error); audit_inode(pathname, dir); error = -EISDIR; /* trailing slashes? */ if (nd->last.name[nd->last.len]) goto exit; mutex_lock(&dir->d_inode->i_mutex); dentry = lookup_hash(nd); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto exit; } path->dentry = dentry; path->mnt = nd->path.mnt; /* Negative dentry, just create the file */ if (!dentry->d_inode) { umode_t mode = op->mode; if (!IS_POSIXACL(dir->d_inode)) mode &= ~current_umask(); /* * This write is needed to ensure that a * rw->ro transition does not occur between * the time when the file is created and when * a permanent write count is taken through * the 'struct file' in nameidata_to_filp(). */ error = mnt_want_write(nd->path.mnt); if (error) goto exit_mutex_unlock; want_write = 1; /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = 0; acc_mode = MAY_OPEN; error = security_path_mknod(&nd->path, dentry, mode, 0); if (error) goto exit_mutex_unlock; error = vfs_create(dir->d_inode, dentry, mode, nd); if (error) goto exit_mutex_unlock; mutex_unlock(&dir->d_inode->i_mutex); dput(nd->path.dentry); nd->path.dentry = dentry; goto common; } /* * It already exists. */ mutex_unlock(&dir->d_inode->i_mutex); audit_inode(pathname, path->dentry); error = -EEXIST; if (open_flag & O_EXCL) goto exit_dput; error = follow_managed(path, nd->flags); if (error < 0) goto exit_dput; if (error) nd->flags |= LOOKUP_JUMPED; error = -ENOENT; if (!path->dentry->d_inode) goto exit_dput; if (path->dentry->d_inode->i_op->follow_link) return NULL; path_to_nameidata(path, nd); nd->inode = path->dentry->d_inode; /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ error = complete_walk(nd); if (error) return ERR_PTR(error); error = -EISDIR; if (S_ISDIR(nd->inode->i_mode)) goto exit; ok: if (!S_ISREG(nd->inode->i_mode)) will_truncate = 0; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto exit; want_write = 1; } common: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto exit; filp = nameidata_to_filp(nd); if (!IS_ERR(filp)) { error = ima_file_check(filp, op->acc_mode); if (error) { fput(filp); filp = ERR_PTR(error); } } if (!IS_ERR(filp)) { if (will_truncate) { error = handle_truncate(filp); if (error) { fput(filp); filp = ERR_PTR(error); } } } out: if (want_write) mnt_drop_write(nd->path.mnt); path_put(&nd->path); return filp; exit_mutex_unlock: mutex_unlock(&dir->d_inode->i_mutex); exit_dput: path_put_conditional(path, nd); exit: filp = ERR_PTR(error); goto out; } static struct file *path_openat(int dfd, const char *pathname, struct nameidata *nd, const struct open_flags *op, int flags) { struct file *base = NULL; struct file *filp; struct path path; int error; filp = get_empty_filp(); if (!filp) return ERR_PTR(-ENFILE); filp->f_flags = op->open_flag; nd->intent.open.file = filp; nd->intent.open.flags = open_to_namei_flags(op->open_flag); nd->intent.open.create_mode = op->mode; error = path_init(dfd, pathname, flags | LOOKUP_PARENT, nd, &base); if (unlikely(error)) goto out_filp; current->total_link_count = 0; error = link_path_walk(pathname, nd); if (unlikely(error)) goto out_filp; filp = do_last(nd, &path, op, pathname); while (unlikely(!filp)) { /* trailing symlink */ struct path link = path; void *cookie; if (!(nd->flags & LOOKUP_FOLLOW)) { path_put_conditional(&path, nd); path_put(&nd->path); filp = ERR_PTR(-ELOOP); break; } nd->flags |= LOOKUP_PARENT; nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); error = follow_link(&link, nd, &cookie); if (unlikely(error)) filp = ERR_PTR(error); else filp = do_last(nd, &path, op, pathname); put_link(nd, &link, cookie); } out: if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) path_put(&nd->root); if (base) fput(base); release_open_intent(nd); return filp; out_filp: filp = ERR_PTR(error); goto out; } struct file *do_filp_open(int dfd, const char *pathname, const struct open_flags *op, int flags) { struct nameidata nd; struct file *filp; filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_RCU); if (unlikely(filp == ERR_PTR(-ECHILD))) filp = path_openat(dfd, pathname, &nd, op, flags); if (unlikely(filp == ERR_PTR(-ESTALE))) filp = path_openat(dfd, pathname, &nd, op, flags | LOOKUP_REVAL); return filp; } struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt, const char *name, const struct open_flags *op, int flags) { struct nameidata nd; struct file *file; nd.root.mnt = mnt; nd.root.dentry = dentry; flags |= LOOKUP_ROOT; if (dentry->d_inode->i_op->follow_link && op->intent & LOOKUP_OPEN) return ERR_PTR(-ELOOP); file = path_openat(-1, name, &nd, op, flags | LOOKUP_RCU); if (unlikely(file == ERR_PTR(-ECHILD))) file = path_openat(-1, name, &nd, op, flags); if (unlikely(file == ERR_PTR(-ESTALE))) file = path_openat(-1, name, &nd, op, flags | LOOKUP_REVAL); return file; } struct dentry *kern_path_create(int dfd, const char *pathname, struct path *path, int is_dir) { struct dentry *dentry = ERR_PTR(-EEXIST); struct nameidata nd; int error = do_path_lookup(dfd, pathname, LOOKUP_PARENT, &nd); if (error) return ERR_PTR(error); /* * Yucky last component or no last component at all? * (foo/., foo/.., /////) */ if (nd.last_type != LAST_NORM) goto out; nd.flags &= ~LOOKUP_PARENT; nd.flags |= LOOKUP_CREATE | LOOKUP_EXCL; nd.intent.open.flags = O_EXCL; /* * Do the final lookup. */ mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); if (IS_ERR(dentry)) goto fail; if (dentry->d_inode) goto eexist; /* * Special case - lookup gave negative, but... we had foo/bar/ * From the vfs_mknod() POV we just have a negative dentry - * all is fine. Let's be bastards - you had / on the end, you've * been asking for (non-existent) directory. -ENOENT for you. */ if (unlikely(!is_dir && nd.last.name[nd.last.len])) { dput(dentry); dentry = ERR_PTR(-ENOENT); goto fail; } *path = nd.path; return dentry; eexist: dput(dentry); dentry = ERR_PTR(-EEXIST); fail: mutex_unlock(&nd.path.dentry->d_inode->i_mutex); out: path_put(&nd.path); return dentry; } EXPORT_SYMBOL(kern_path_create); struct dentry *user_path_create(int dfd, const char __user *pathname, struct path *path, int is_dir) { char *tmp = getname(pathname); struct dentry *res; if (IS_ERR(tmp)) return ERR_CAST(tmp); res = kern_path_create(dfd, tmp, path, is_dir); putname(tmp); return res; } EXPORT_SYMBOL(user_path_create); int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev) { int error = may_create(dir, dentry); if (error) return error; if ((S_ISCHR(mode) || S_ISBLK(mode)) && !ns_capable(inode_userns(dir), CAP_MKNOD)) return -EPERM; if (!dir->i_op->mknod) return -EPERM; error = devcgroup_inode_mknod(mode, dev); if (error) return error; error = security_inode_mknod(dir, dentry, mode, dev); if (error) return error; error = dir->i_op->mknod(dir, dentry, mode, dev); if (!error) fsnotify_create(dir, dentry); return error; } static int may_mknod(umode_t mode) { switch (mode & S_IFMT) { case S_IFREG: case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: case 0: /* zero mode translates to S_IFREG */ return 0; case S_IFDIR: return -EPERM; default: return -EINVAL; } } SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode, unsigned, dev) { struct dentry *dentry; struct path path; int error; if (S_ISDIR(mode)) return -EPERM; dentry = user_path_create(dfd, filename, &path, 0); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = may_mknod(mode); if (error) goto out_dput; error = mnt_want_write(path.mnt); if (error) goto out_dput; error = security_path_mknod(&path, dentry, mode, dev); if (error) goto out_drop_write; switch (mode & S_IFMT) { case 0: case S_IFREG: error = vfs_create(path.dentry->d_inode,dentry,mode,NULL); break; case S_IFCHR: case S_IFBLK: error = vfs_mknod(path.dentry->d_inode,dentry,mode, new_decode_dev(dev)); break; case S_IFIFO: case S_IFSOCK: error = vfs_mknod(path.dentry->d_inode,dentry,mode,0); break; } out_drop_write: mnt_drop_write(path.mnt); out_dput: dput(dentry); mutex_unlock(&path.dentry->d_inode->i_mutex); path_put(&path); return error; } SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev) { return sys_mknodat(AT_FDCWD, filename, mode, dev); } int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { int error = may_create(dir, dentry); unsigned max_links = dir->i_sb->s_max_links; if (error) return error; if (!dir->i_op->mkdir) return -EPERM; mode &= (S_IRWXUGO|S_ISVTX); error = security_inode_mkdir(dir, dentry, mode); if (error) return error; if (max_links && dir->i_nlink >= max_links) return -EMLINK; error = dir->i_op->mkdir(dir, dentry, mode); if (!error) fsnotify_mkdir(dir, dentry); return error; } SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode) { struct dentry *dentry; struct path path; int error; dentry = user_path_create(dfd, pathname, &path, 1); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = mnt_want_write(path.mnt); if (error) goto out_dput; error = security_path_mkdir(&path, dentry, mode); if (error) goto out_drop_write; error = vfs_mkdir(path.dentry->d_inode, dentry, mode); out_drop_write: mnt_drop_write(path.mnt); out_dput: dput(dentry); mutex_unlock(&path.dentry->d_inode->i_mutex); path_put(&path); return error; } SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode) { return sys_mkdirat(AT_FDCWD, pathname, mode); } /* * The dentry_unhash() helper will try to drop the dentry early: we * should have a usage count of 1 if we're the only user of this * dentry, and if that is true (possibly after pruning the dcache), * then we drop the dentry now. * * A low-level filesystem can, if it choses, legally * do a * * if (!d_unhashed(dentry)) * return -EBUSY; * * if it cannot handle the case of removing a directory * that is still in use by something else.. */ void dentry_unhash(struct dentry *dentry) { shrink_dcache_parent(dentry); spin_lock(&dentry->d_lock); if (dentry->d_count == 1) __d_drop(dentry); spin_unlock(&dentry->d_lock); } int vfs_rmdir(struct inode *dir, struct dentry *dentry) { int error = may_delete(dir, dentry, 1); if (error) return error; if (!dir->i_op->rmdir) return -EPERM; dget(dentry); mutex_lock(&dentry->d_inode->i_mutex); error = -EBUSY; if (d_mountpoint(dentry)) goto out; error = security_inode_rmdir(dir, dentry); if (error) goto out; shrink_dcache_parent(dentry); error = dir->i_op->rmdir(dir, dentry); if (error) goto out; dentry->d_inode->i_flags |= S_DEAD; dont_mount(dentry); out: mutex_unlock(&dentry->d_inode->i_mutex); dput(dentry); if (!error) d_delete(dentry); return error; } static long do_rmdir(int dfd, const char __user *pathname) { int error = 0; char * name; struct dentry *dentry; struct nameidata nd; error = user_path_parent(dfd, pathname, &nd, &name); if (error) return error; switch(nd.last_type) { case LAST_DOTDOT: error = -ENOTEMPTY; goto exit1; case LAST_DOT: error = -EINVAL; goto exit1; case LAST_ROOT: error = -EBUSY; goto exit1; } nd.flags &= ~LOOKUP_PARENT; mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto exit2; if (!dentry->d_inode) { error = -ENOENT; goto exit3; } error = mnt_want_write(nd.path.mnt); if (error) goto exit3; error = security_path_rmdir(&nd.path, dentry); if (error) goto exit4; error = vfs_rmdir(nd.path.dentry->d_inode, dentry); exit4: mnt_drop_write(nd.path.mnt); exit3: dput(dentry); exit2: mutex_unlock(&nd.path.dentry->d_inode->i_mutex); exit1: path_put(&nd.path); putname(name); return error; } SYSCALL_DEFINE1(rmdir, const char __user *, pathname) { return do_rmdir(AT_FDCWD, pathname); } int vfs_unlink(struct inode *dir, struct dentry *dentry) { int error = may_delete(dir, dentry, 0); if (error) return error; if (!dir->i_op->unlink) return -EPERM; mutex_lock(&dentry->d_inode->i_mutex); if (d_mountpoint(dentry)) error = -EBUSY; else { error = security_inode_unlink(dir, dentry); if (!error) { error = dir->i_op->unlink(dir, dentry); if (!error) dont_mount(dentry); } } mutex_unlock(&dentry->d_inode->i_mutex); /* We don't d_delete() NFS sillyrenamed files--they still exist. */ if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) { fsnotify_link_count(dentry->d_inode); d_delete(dentry); } return error; } /* * Make sure that the actual truncation of the file will occur outside its * directory's i_mutex. Truncate can take a long time if there is a lot of * writeout happening, and we don't want to prevent access to the directory * while waiting on the I/O. */ static long do_unlinkat(int dfd, const char __user *pathname) { int error; char *name; struct dentry *dentry; struct nameidata nd; struct inode *inode = NULL; error = user_path_parent(dfd, pathname, &nd, &name); if (error) return error; error = -EISDIR; if (nd.last_type != LAST_NORM) goto exit1; nd.flags &= ~LOOKUP_PARENT; mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = lookup_hash(&nd); error = PTR_ERR(dentry); if (!IS_ERR(dentry)) { /* Why not before? Because we want correct error value */ if (nd.last.name[nd.last.len]) goto slashes; inode = dentry->d_inode; if (!inode) goto slashes; ihold(inode); error = mnt_want_write(nd.path.mnt); if (error) goto exit2; error = security_path_unlink(&nd.path, dentry); if (error) goto exit3; error = vfs_unlink(nd.path.dentry->d_inode, dentry); exit3: mnt_drop_write(nd.path.mnt); exit2: dput(dentry); } mutex_unlock(&nd.path.dentry->d_inode->i_mutex); if (inode) iput(inode); /* truncate the inode here */ exit1: path_put(&nd.path); putname(name); return error; slashes: error = !dentry->d_inode ? -ENOENT : S_ISDIR(dentry->d_inode->i_mode) ? -EISDIR : -ENOTDIR; goto exit2; } SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag) { if ((flag & ~AT_REMOVEDIR) != 0) return -EINVAL; if (flag & AT_REMOVEDIR) return do_rmdir(dfd, pathname); return do_unlinkat(dfd, pathname); } SYSCALL_DEFINE1(unlink, const char __user *, pathname) { return do_unlinkat(AT_FDCWD, pathname); } int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->symlink) return -EPERM; error = security_inode_symlink(dir, dentry, oldname); if (error) return error; error = dir->i_op->symlink(dir, dentry, oldname); if (!error) fsnotify_create(dir, dentry); return error; } SYSCALL_DEFINE3(symlinkat, const char __user *, oldname, int, newdfd, const char __user *, newname) { int error; char *from; struct dentry *dentry; struct path path; from = getname(oldname); if (IS_ERR(from)) return PTR_ERR(from); dentry = user_path_create(newdfd, newname, &path, 0); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_putname; error = mnt_want_write(path.mnt); if (error) goto out_dput; error = security_path_symlink(&path, dentry, from); if (error) goto out_drop_write; error = vfs_symlink(path.dentry->d_inode, dentry, from); out_drop_write: mnt_drop_write(path.mnt); out_dput: dput(dentry); mutex_unlock(&path.dentry->d_inode->i_mutex); path_put(&path); out_putname: putname(from); return error; } SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname) { return sys_symlinkat(oldname, AT_FDCWD, newname); } int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry) { struct inode *inode = old_dentry->d_inode; unsigned max_links = dir->i_sb->s_max_links; int error; if (!inode) return -ENOENT; error = may_create(dir, new_dentry); if (error) return error; if (dir->i_sb != inode->i_sb) return -EXDEV; /* * A link to an append-only or immutable file cannot be created. */ if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; if (!dir->i_op->link) return -EPERM; if (S_ISDIR(inode->i_mode)) return -EPERM; error = security_inode_link(old_dentry, dir, new_dentry); if (error) return error; mutex_lock(&inode->i_mutex); /* Make sure we don't allow creating hardlink to an unlinked file */ if (inode->i_nlink == 0) error = -ENOENT; else if (max_links && inode->i_nlink >= max_links) error = -EMLINK; else error = dir->i_op->link(old_dentry, dir, new_dentry); mutex_unlock(&inode->i_mutex); if (!error) fsnotify_link(dir, inode, new_dentry); return error; } /* * Hardlinks are often used in delicate situations. We avoid * security-related surprises by not following symlinks on the * newname. --KAB * * We don't follow them on the oldname either to be compatible * with linux 2.0, and to avoid hard-linking to directories * and other special files. --ADM */ SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, int, flags) { struct dentry *new_dentry; struct path old_path, new_path; int how = 0; int error; if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) return -EINVAL; /* * To use null names we require CAP_DAC_READ_SEARCH * This ensures that not everyone will be able to create * handlink using the passed filedescriptor. */ if (flags & AT_EMPTY_PATH) { if (!capable(CAP_DAC_READ_SEARCH)) return -ENOENT; how = LOOKUP_EMPTY; } if (flags & AT_SYMLINK_FOLLOW) how |= LOOKUP_FOLLOW; error = user_path_at(olddfd, oldname, how, &old_path); if (error) return error; new_dentry = user_path_create(newdfd, newname, &new_path, 0); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto out; error = -EXDEV; if (old_path.mnt != new_path.mnt) goto out_dput; error = mnt_want_write(new_path.mnt); if (error) goto out_dput; error = security_path_link(old_path.dentry, &new_path, new_dentry); if (error) goto out_drop_write; error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry); out_drop_write: mnt_drop_write(new_path.mnt); out_dput: dput(new_dentry); mutex_unlock(&new_path.dentry->d_inode->i_mutex); path_put(&new_path); out: path_put(&old_path); return error; } SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname) { return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } /* * The worst of all namespace operations - renaming directory. "Perverted" * doesn't even start to describe it. Somebody in UCB had a heck of a trip... * Problems: * a) we can get into loop creation. Check is done in is_subdir(). * b) race potential - two innocent renames can create a loop together. * That's where 4.4 screws up. Current fix: serialization on * sb->s_vfs_rename_mutex. We might be more accurate, but that's another * story. * c) we have to lock _three_ objects - parents and victim (if it exists). * And that - after we got ->i_mutex on parents (until then we don't know * whether the target exists). Solution: try to be smart with locking * order for inodes. We rely on the fact that tree topology may change * only under ->s_vfs_rename_mutex _and_ that parent of the object we * move will be locked. Thus we can rank directories by the tree * (ancestors first) and rank all non-directories after them. * That works since everybody except rename does "lock parent, lookup, * lock child" and rename is under ->s_vfs_rename_mutex. * HOWEVER, it relies on the assumption that any object with ->lookup() * has no more than 1 dentry. If "hybrid" objects will ever appear, * we'd better make sure that there's no link(2) for them. * d) conversion from fhandle to dentry may come in the wrong moment - when * we are removing the target. Solution: we will have to grab ->i_mutex * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on * ->i_mutex on parents, which works but leads to some truly excessive * locking]. */ static int vfs_rename_dir(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { int error = 0; struct inode *target = new_dentry->d_inode; unsigned max_links = new_dir->i_sb->s_max_links; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { error = inode_permission(old_dentry->d_inode, MAY_WRITE); if (error) return error; } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry); if (error) return error; dget(new_dentry); if (target) mutex_lock(&target->i_mutex); error = -EBUSY; if (d_mountpoint(old_dentry) || d_mountpoint(new_dentry)) goto out; error = -EMLINK; if (max_links && !target && new_dir != old_dir && new_dir->i_nlink >= max_links) goto out; if (target) shrink_dcache_parent(new_dentry); error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry); if (error) goto out; if (target) { target->i_flags |= S_DEAD; dont_mount(new_dentry); } out: if (target) mutex_unlock(&target->i_mutex); dput(new_dentry); if (!error) if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) d_move(old_dentry,new_dentry); return error; } static int vfs_rename_other(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct inode *target = new_dentry->d_inode; int error; error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry); if (error) return error; dget(new_dentry); if (target) mutex_lock(&target->i_mutex); error = -EBUSY; if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry)) goto out; error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry); if (error) goto out; if (target) dont_mount(new_dentry); if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) d_move(old_dentry, new_dentry); out: if (target) mutex_unlock(&target->i_mutex); dput(new_dentry); return error; } int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { int error; int is_dir = S_ISDIR(old_dentry->d_inode->i_mode); const unsigned char *old_name; if (old_dentry->d_inode == new_dentry->d_inode) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!new_dentry->d_inode) error = may_create(new_dir, new_dentry); else error = may_delete(new_dir, new_dentry, is_dir); if (error) return error; if (!old_dir->i_op->rename) return -EPERM; old_name = fsnotify_oldname_init(old_dentry->d_name.name); if (is_dir) error = vfs_rename_dir(old_dir,old_dentry,new_dir,new_dentry); else error = vfs_rename_other(old_dir,old_dentry,new_dir,new_dentry); if (!error) fsnotify_move(old_dir, new_dir, old_name, is_dir, new_dentry->d_inode, old_dentry); fsnotify_oldname_free(old_name); return error; } SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname) { struct dentry *old_dir, *new_dir; struct dentry *old_dentry, *new_dentry; struct dentry *trap; struct nameidata oldnd, newnd; char *from; char *to; int error; error = user_path_parent(olddfd, oldname, &oldnd, &from); if (error) goto exit; error = user_path_parent(newdfd, newname, &newnd, &to); if (error) goto exit1; error = -EXDEV; if (oldnd.path.mnt != newnd.path.mnt) goto exit2; old_dir = oldnd.path.dentry; error = -EBUSY; if (oldnd.last_type != LAST_NORM) goto exit2; new_dir = newnd.path.dentry; if (newnd.last_type != LAST_NORM) goto exit2; oldnd.flags &= ~LOOKUP_PARENT; newnd.flags &= ~LOOKUP_PARENT; newnd.flags |= LOOKUP_RENAME_TARGET; trap = lock_rename(new_dir, old_dir); old_dentry = lookup_hash(&oldnd); error = PTR_ERR(old_dentry); if (IS_ERR(old_dentry)) goto exit3; /* source must exist */ error = -ENOENT; if (!old_dentry->d_inode) goto exit4; /* unless the source is a directory trailing slashes give -ENOTDIR */ if (!S_ISDIR(old_dentry->d_inode->i_mode)) { error = -ENOTDIR; if (oldnd.last.name[oldnd.last.len]) goto exit4; if (newnd.last.name[newnd.last.len]) goto exit4; } /* source should not be ancestor of target */ error = -EINVAL; if (old_dentry == trap) goto exit4; new_dentry = lookup_hash(&newnd); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto exit4; /* target should not be an ancestor of source */ error = -ENOTEMPTY; if (new_dentry == trap) goto exit5; error = mnt_want_write(oldnd.path.mnt); if (error) goto exit5; error = security_path_rename(&oldnd.path, old_dentry, &newnd.path, new_dentry); if (error) goto exit6; error = vfs_rename(old_dir->d_inode, old_dentry, new_dir->d_inode, new_dentry); exit6: mnt_drop_write(oldnd.path.mnt); exit5: dput(new_dentry); exit4: dput(old_dentry); exit3: unlock_rename(new_dir, old_dir); exit2: path_put(&newnd.path); putname(to); exit1: path_put(&oldnd.path); putname(from); exit: return error; } SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname) { return sys_renameat(AT_FDCWD, oldname, AT_FDCWD, newname); } int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link) { int len; len = PTR_ERR(link); if (IS_ERR(link)) goto out; len = strlen(link); if (len > (unsigned) buflen) len = buflen; if (copy_to_user(buffer, link, len)) len = -EFAULT; out: return len; } /* * A helper for ->readlink(). This should be used *ONLY* for symlinks that * have ->follow_link() touching nd only in nd_set_link(). Using (or not * using) it for any given inode is up to filesystem. */ int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct nameidata nd; void *cookie; int res; nd.depth = 0; cookie = dentry->d_inode->i_op->follow_link(dentry, &nd); if (IS_ERR(cookie)) return PTR_ERR(cookie); res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd)); if (dentry->d_inode->i_op->put_link) dentry->d_inode->i_op->put_link(dentry, &nd, cookie); return res; } int vfs_follow_link(struct nameidata *nd, const char *link) { return __vfs_follow_link(nd, link); } /* get the link contents into pagecache */ static char *page_getlink(struct dentry * dentry, struct page **ppage) { char *kaddr; struct page *page; struct address_space *mapping = dentry->d_inode->i_mapping; page = read_mapping_page(mapping, 0, NULL); if (IS_ERR(page)) return (char*)page; *ppage = page; kaddr = kmap(page); nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1); return kaddr; } int page_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct page *page = NULL; char *s = page_getlink(dentry, &page); int res = vfs_readlink(dentry,buffer,buflen,s); if (page) { kunmap(page); page_cache_release(page); } return res; } void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd) { struct page *page = NULL; nd_set_link(nd, page_getlink(dentry, &page)); return page; } void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie) { struct page *page = cookie; if (page) { kunmap(page); page_cache_release(page); } } /* * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS */ int __page_symlink(struct inode *inode, const char *symname, int len, int nofs) { struct address_space *mapping = inode->i_mapping; struct page *page; void *fsdata; int err; char *kaddr; unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE; if (nofs) flags |= AOP_FLAG_NOFS; retry: err = pagecache_write_begin(NULL, mapping, 0, len-1, flags, &page, &fsdata); if (err) goto fail; kaddr = kmap_atomic(page); memcpy(kaddr, symname, len-1); kunmap_atomic(kaddr); err = pagecache_write_end(NULL, mapping, 0, len-1, len-1, page, fsdata); if (err < 0) goto fail; if (err < len-1) goto retry; mark_inode_dirty(inode); return 0; fail: return err; } int page_symlink(struct inode *inode, const char *symname, int len) { return __page_symlink(inode, symname, len, !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS)); } const struct inode_operations page_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, }; EXPORT_SYMBOL(user_path_at); EXPORT_SYMBOL(follow_down_one); EXPORT_SYMBOL(follow_down); EXPORT_SYMBOL(follow_up); EXPORT_SYMBOL(get_write_access); /* binfmt_aout */ EXPORT_SYMBOL(getname); EXPORT_SYMBOL(lock_rename); EXPORT_SYMBOL(lookup_one_len); EXPORT_SYMBOL(page_follow_link_light); EXPORT_SYMBOL(page_put_link); EXPORT_SYMBOL(page_readlink); EXPORT_SYMBOL(__page_symlink); EXPORT_SYMBOL(page_symlink); EXPORT_SYMBOL(page_symlink_inode_operations); EXPORT_SYMBOL(kern_path); EXPORT_SYMBOL(vfs_path_lookup); EXPORT_SYMBOL(inode_permission); EXPORT_SYMBOL(unlock_rename); EXPORT_SYMBOL(vfs_create); EXPORT_SYMBOL(vfs_follow_link); EXPORT_SYMBOL(vfs_link); EXPORT_SYMBOL(vfs_mkdir); EXPORT_SYMBOL(vfs_mknod); EXPORT_SYMBOL(generic_permission); EXPORT_SYMBOL(vfs_readlink); EXPORT_SYMBOL(vfs_rename); EXPORT_SYMBOL(vfs_rmdir); EXPORT_SYMBOL(vfs_symlink); EXPORT_SYMBOL(vfs_unlink); EXPORT_SYMBOL(dentry_unhash); EXPORT_SYMBOL(generic_readlink);
Pulshen/XKernel
fs/namei.c
C
gpl-2.0
87,242
# Puluc language: C. Game: Puluc I don't know if it is working well but if you have time, you can modify it.
vince52/Puluc
README.md
Markdown
gpl-2.0
110
#ifndef Podd_THaVDCPoint_h_ #define Podd_THaVDCPoint_h_ /////////////////////////////////////////////////////////////////////////////// // // // THaVDCPoint // // // // A pair of one U and one V VDC cluster in a given VDC chamber // // // /////////////////////////////////////////////////////////////////////////////// #include "THaCluster.h" #include "THaVDCCluster.h" class THaVDCChamber; class THaTrack; class THaVDCPoint : public THaCluster { public: THaVDCPoint( THaVDCCluster* u_cl, THaVDCCluster* v_cl, THaVDCChamber* chamber ); virtual ~THaVDCPoint() {} void CalcDetCoords(); // Get and Set Functions THaVDCCluster* GetUCluster() const { return fUClust; } THaVDCCluster* GetVCluster() const { return fVClust; } THaVDCChamber* GetChamber() const { return fChamber; } THaVDCPoint* GetPartner() const { return fPartner; } THaTrack* GetTrack() const { return fTrack; } Double_t GetU() const; Double_t GetV() const; Double_t GetX() const { return fX; } Double_t GetY() const { return fY; } Double_t GetTheta() const { return fTheta; } Double_t GetPhi() const { return fPhi; } Int_t GetTrackIndex() const; Double_t GetZU() const; Double_t GetZV() const; Double_t GetZ() const { return GetZU(); } Bool_t HasPartner() const { return (fPartner != 0); } void CalcChisquare(Double_t &chi2, Int_t &nhits) const; void SetTrack( THaTrack* track); void SetPartner( THaVDCPoint* partner) { fPartner = partner;} void SetSlopes( Double_t mu, Double_t mv ); protected: THaVDCCluster* fUClust; // Cluster in the U plane THaVDCCluster* fVClust; // Cluster in the V plane THaVDCChamber* fChamber; // Chamber of this cluster pair THaTrack* fTrack; // Track that this point is associated with THaVDCPoint* fPartner; // Point associated with this one in // the other chamber // Detector system coordinates derived from fUClust and fVClust // at the U plane (z = GetZ()). X,Y in m; theta, phi in tan(angle) Double_t fX; // X position of point in U wire plane Double_t fY; // Y position of point in U wire plane Double_t fTheta; // tan(angle between z-axis and track proj onto xz plane) Double_t fPhi; // tan(angle between z-axis and track proj onto yz plane) void Set( Double_t x, Double_t y, Double_t theta, Double_t phi ) { fX = x; fY = y; fTheta = theta; fPhi = phi; } private: // Hide copy ctor and op= THaVDCPoint( const THaVDCPoint& ); THaVDCPoint& operator=( const THaVDCPoint& ); ClassDef(THaVDCPoint,0) // Pair of one U and one V cluster in a VDC chamber }; //-------------------- inlines ------------------------------------------------ inline Double_t THaVDCPoint::GetU() const { // Return intercept of u cluster return fUClust->GetIntercept(); } //_____________________________________________________________________________ inline Double_t THaVDCPoint::GetV() const { // Return intercept of v cluster return fVClust->GetIntercept(); } /////////////////////////////////////////////////////////////////////////////// #endif
sly2j/analyzer
src/THaVDCPoint.h
C
gpl-2.0
3,527
import os, socket, sys, urllib from wx.lib.embeddedimage import PyEmbeddedImage ldc_name = "Live Debian Creator" ldc_cli_version = "1.4.0" ldc_gui_version = "1.11.0" if (sys.platform == "win32"): slash = "\\" if os.path.isfile(sys.path[0]): #fix for compiled binaries homepath = os.path.dirname(sys.path[0]) + slash else: homepath = sys.path[0] + slash else: slash = "/" #socket.setdefaulttimeout(10) def defineBrowserAgent(uiname, uiversion): class AppURLopener(urllib.FancyURLopener): version = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" #version = uiname + " " + uiversion + " / " + sys.platform urllib._urlopener = AppURLopener() bookico = PyEmbeddedImage( "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAABPZJ" "REFUWIWtl09sFFUcxz/iYN+YTZyNxewiTWiV6FZQtqhkN3pgGw6UW6unJVxEDtaThJMc9WLg" "oj1hwJhANURqQkw9NGwTla0c6JqArELSMVCzi63uKJX5UR7Bw8x0Z2d3yxJ5yctM3vu93/f7" "+ztv4CGPqamp9A/nL2Q6lTceBqht26pw7kL+7K+10S/tJ9OpBBPASCdnH/k/wFNTU+nzc/+M" "2v925a2N21Sq1yKJg/wxV7XWyIHBnYPjD53A9PS0mrv+e/6yw6gT60+72iK7AVJJSBoCBihD" "AVC6WK7O3bx3+thFyY30ycSH7+w5FNXXcQgymUzaei49+vHMX/kq/SqpYGiDRbYHlBFoigMu" "gklxHsZ1NlG4yygvKiruWauV3vsS2L59e+qZVwfHqsnB3G8LkI2ZHHzdImGBaZi+BgVaqIhi" "sqo4uQBlrQDPI2jx5gMQUFu39A3veW3ru9leMmO19aQ2JDm8C5SCuDJBgUJRM6DkKE5WFYUF" "cLSAxgOnNeiqBHZt6z2wO2UdSvXGrfimFNYrIzhHbca/LlOcTzL0coJsj8IRKC4pJhfAXvKB" "dKBFQu+AdjsnsG/AOpzc+RZWKkc8FgcFGDYApas1SgtAUjxXJOK+a1XUgRHrzc4JlMslqB5C" "ZYbg+Sws2rAYByPlSQcntNQtNSLaNGCoxv07HRJAQ63ioM6MI2fGPdt6DngKDbVK1kS9IKBV" "PQmN6P4qBNAgGlw/jqJp9vKKBtVILrA4nA+GegAPBCT8Z0P6RF0dvAfgwdRRIu2rYfU+sLKr" "mtcCq3UIPGyABmupzIBRoOIkuXzF7oyACq2KDne5FmQC2fC+UyWtZxmIlchtseg1sti2yzf2" "z8n8559kdmzbYW/evLnalgAGmLr+Lp00aw3WYomUUaDfKpNJphmIDWEZXvd1N9m80HNj+Fs5" "Pvx0TY0AE6sQUGB45SOA0m0kwyWnHfLdh8nGd5NJDGMqEwyXoi5QXJrAltmVsNxabq2mrWVi" "qHoitkpCBJwKp6uTVDbaVGKziK5wWWaQoAOGu2IbO5pGkLfuKocD5WrJwVRQXirjXC+DAdY6" "1ZSYCng8cnxNk8K1fukF/eA+FqAFpIaiMT0VXgIr5fcohUfosca23EzgTh3cDep5taFdcCN1" "bviAMTB98OZqakfAH65vx4rqKBlNm2+8grUeWGCrGW5S9yWwti7ofW5Ucx9rIBK6bIRB2lVN" "Y29tQcBonG4Ta6k/NSBeDkSH2Sp0GoiUYYsQ+AB+0rTt4hov/lpQ0lrKDT/F66y3IjLN9rmh" "VQVo1b4StHgkWhAIEjioKBFfx91GFzR5wJ5HRINpem3YQfzyklAihgCjxDT1SvLvLLLkR0rA" "jdzOmjxwotbVf656+/20YmS9wrIfvSdO8p53A0UAM0RihVqIjNSB/WXRIFpwXVhebgxCkwdu" "/33b/kXY94VD/KWPjvY9lduVvaWxCVzYYipxW1eKFhwRajcdat9RemP+vd2jbx6cCIt19Gf0" "6fETw28fKR6jf9Ci24LuuFeuMWC2IIlLXxVl70+5ZDckuxWuFuIxqIjgTDOjzvV9UC7OTbbS" "3fGvmW3bauyzE/nCFXe4dIMsy45tVX889oT+83RXV5d5bf21MXIyZD3re2WGgnyfOFK9VG0J" "/MAEOhmnTp1KXF28mlsXWzezf+/+1legyPgPTicVRBS2XfsAAAAASUVORK5CYII=") getbookicoIcon = bookico.GetIcon
godaigroup/livedebiancreator
prefs.py
Python
gpl-2.0
2,733
<?php namespace Connections_Directory\Content_Blocks\Entry\Related; use Connections_Directory\Content_Blocks\Entry\Related; /** * Class Last_Name * * @package Connections_Directory\Content_Blocks\Entry */ class Last_Name extends Related { /** * @since 9.8 * @var string */ const ID = 'entry-related-last_name'; /** * @since 9.7 * @var array */ private $properties = array( 'relation' => 'last_name', ); /** * Related constructor. * * @since 9.8 * * @param $id */ public function __construct( $id ) { $atts = array( 'context' => 'single', 'name' => __( 'Related Entries by Last Name', 'connections' ), 'permission_callback' => '__return_true', 'heading' => __( 'Related by Last Name', 'connections' ), 'script_handle' => 'Connections_Directory/Block/Carousel/Script', 'style_handle' => 'Connections_Directory/Block/Carousel/Style', ); parent::__construct( $id, $atts ); $this->setProperties( $this->properties ); $this->hooks(); } /** * Add hooks. * * @since 9.8 */ private function hooks() { // Add the last name to the Content Block heading. add_filter( 'Connections_Directory/Entry/Related/Query_Parameters', function( $queryParameters ) { if ( is_array( $queryParameters ) && array_key_exists( 'last_name', $queryParameters ) ) { $this->set( 'heading', /* translators: A surname, family name, or last name. */ sprintf( __( 'Related by Last Name - %s', 'connections' ), $queryParameters['last_name'] ) ); } return $queryParameters; } ); } }
Connections-Business-Directory/Connections
includes/Content_Blocks/Entry/Related/Last_Name.php
PHP
gpl-2.0
1,642
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>schrodinger.application.desmond.enhsamp.Series</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="schrodinger-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >Suite 2012 Schrodinger Python API</th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="schrodinger-module.html">Package&nbsp;schrodinger</a> :: <a href="schrodinger.application-module.html">Package&nbsp;application</a> :: <a href="schrodinger.application.desmond-module.html">Package&nbsp;desmond</a> :: <a href="schrodinger.application.desmond.enhsamp-module.html">Module&nbsp;enhsamp</a> :: Class&nbsp;Series </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="schrodinger.application.desmond.enhsamp.Series-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class Series</h1><p class="nomargin-top"></p> <pre class="base-tree"> object --+ | <a href="schrodinger.application.desmond.enhsamp.Node-class.html">Node</a> --+ | <strong class="uidshort">Series</strong> </pre> <hr /> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.application.desmond.enhsamp.Series-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">env</span>, <span class="summary-sig-arg">iters</span>, <span class="summary-sig-arg">value</span>)</span><br /> x.__init__(...) initializes x; see help(type(x)) for signature</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.application.desmond.enhsamp.Series-class.html#get_type" class="summary-sig-name">get_type</a>(<span class="summary-sig-arg">self</span>, <span class="summary-sig-arg">env</span>)</span></td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="schrodinger.application.desmond.enhsamp.Series-class.html#__str__" class="summary-sig-name">__str__</a>(<span class="summary-sig-arg">self</span>)</span><br /> str(x)</td> <td align="right" valign="top"> </td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="schrodinger.application.desmond.enhsamp.Node-class.html">Node</a></code></b>: <code><a href="schrodinger.application.desmond.enhsamp.Node-class.html#constant_fold">constant_fold</a></code>, <code><a href="schrodinger.application.desmond.enhsamp.Node-class.html#resolve_atomsel">resolve_atomsel</a></code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__delattr__</code>, <code>__format__</code>, <code>__getattribute__</code>, <code>__hash__</code>, <code>__new__</code>, <code>__reduce__</code>, <code>__reduce_ex__</code>, <code>__repr__</code>, <code>__setattr__</code>, <code>__sizeof__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="__init__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>, <span class="sig-arg">env</span>, <span class="sig-arg">iters</span>, <span class="sig-arg">value</span>)</span> <br /><em class="fname">(Constructor)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>x.__init__(...) initializes x; see help(type(x)) for signature</p> <dl class="fields"> <dt>Overrides: object.__init__ <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <a name="get_type"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">get_type</span>(<span class="sig-arg">self</span>, <span class="sig-arg">env</span>)</span> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <dl class="fields"> <dt>Overrides: <a href="schrodinger.application.desmond.enhsamp.Node-class.html#get_type">Node.get_type</a> </dt> </dl> </td></tr></table> </div> <a name="__str__"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">__str__</span>(<span class="sig-arg">self</span>)</span> <br /><em class="fname">(Informal representation operator)</em> </h3> </td><td align="right" valign="top" >&nbsp; </td> </tr></table> <p>str(x)</p> <dl class="fields"> <dt>Overrides: object.__str__ <dd><em class="note">(inherited documentation)</em></dd> </dt> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="schrodinger-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" >Suite 2012 Schrodinger Python API</th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Tue Sep 25 02:22:59 2012 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
platinhom/ManualHom
Schrodinger/Schrodinger_2012_docs/python_api/api/schrodinger.application.desmond.enhsamp.Series-class.html
HTML
gpl-2.0
12,010
/* This file is part of the KDevelop PHP Documentation Plugin Copyright 2012 Milian Wolff <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "phpdocsconfig.h" #include <KLocalizedString> #include <KPluginFactory> #include <KPluginLoader> #include <KConfigGroup> #include <KUrlRequester> #include <KAboutData> #include <KFile> #include <ksettings/Dispatcher> #include "phpdocssettings.h" #include "ui_phpdocsconfig.h" K_PLUGIN_FACTORY_WITH_JSON(PhpDocsConfigFactory, "kcm_kdevphpdocs.json", registerPlugin<PhpDocsConfig>();) PhpDocsConfig::PhpDocsConfig(QWidget *parent, const QVariantList &args) : KCModule(KAboutData::pluginData(QStringLiteral("kcm_kdevphpdocs")), parent, args) { QVBoxLayout * l = new QVBoxLayout( this ); QWidget* w = new QWidget; m_configWidget = new Ui::PhpDocsConfigUI; m_configWidget->setupUi( w ); m_configWidget->kcfg_phpDocLocation->setMode( KFile::Directory | KFile::ExistingOnly ); l->addWidget( w ); addConfig( PhpDocsSettings::self(), w ); load(); } void PhpDocsConfig::save() { KCModule::save(); // looks like we have to force a write so readConfig() can get the new values PhpDocsSettings::self()->save(); KSettings::Dispatcher::reparseConfiguration( componentData().componentName() ); } PhpDocsConfig::~PhpDocsConfig() { delete m_configWidget; } #include "phpdocsconfig.moc"
pprkut/kdev-php
docs/phpdocsconfig.cpp
C++
gpl-2.0
2,217
<?php $st_buttons_p = ot_get_option('st_buttons_p'); ?> <?php $sidebar_checkbox = get_post_meta($post->ID, 'sidebar_checkbox', true);?> <?php $full_width = get_post_meta($post->ID, 'portfolio_options_full', true);?> <?php $details = get_post_meta($post->ID, 'portfolio_options_repeatable', true); if($details){$details = array_filter($details);};?> <?php $terms = get_the_terms($post->ID, 'portfolio_tags' ); ?> <?php $share = get_post_meta($post->ID, 'portfolio_options_share', true);?> <?php get_header(); ?> <?php //get_template_part('includes/title-breadcrumb' ) ?> <div id="main" class="inner-page <?php if ($sidebar_checkbox){?>left-sidebar-template<?php }?>"> <div class="container"> <div class="row"> <div class="<?php if ($full_width){?>col-md-12<?php }else{?>col-md-9<?php }?> page-content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php get_template_part('includes/single-portfolio-post' );?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.', GETTEXT_DOMAIN) ?></p> <?php endif; ?> </div> <?php if (!$full_width){?> <div class="col-md-3"> <?php if ( is_active_sidebar(4)||!empty($details) || $terms || !$share ){?> <div class="sidebar"> <?php if ( !empty($details) || $terms || !$share ){?> <div class="widget portfolio-info-widget"> <ul> <?php if($details){ ?> <?php $separator = "%%"; $output = ''; foreach ($details as $item) { if($item){ list($item_text1, $item_text2) = explode($separator, trim($item)); $output .= '<li><strong>' . $item_text1 . ':</strong> ' . do_shortcode($item_text2) . '</li>'; } } echo $output;?> <?php } ?> <?php if($terms){?> <li class="tags"> <?php if($terms) : foreach ($terms as $term) { ?> <?php echo '<a title="'.$term->name.'" href="'.get_term_link($term->slug, 'portfolio_tags').'">'.$term->name.'</a>'?> <?php } endif;?> <div class="clearfix"></div> </li> <?php }?> <?php if(!$share&&$st_buttons_p){?> <li class="st-share-portfolio"><strong><?php _e( 'Share', GETTEXT_DOMAIN);?>:</strong> <?php echo $st_buttons_p;?> </li> <?php }?> </ul> </div> <?php }?> <?php if ( !function_exists( 'dynamic_sidebar' ) || !dynamic_sidebar('Portfolio Post Sidebar') ) ?> </div> <?php } ?> </div> <?php }?> </div> </div> </div> <?php get_footer(); ?>
ronykader06/Badsha
wp-content/themes/dokan.me/single-portfolio.php
PHP
gpl-2.0
2,901
/* Table of relaxations for Xtensa assembly. Copyright 2003, 2004 Free Software Foundation, Inc. This file is part of GAS, the GNU Assembler. GAS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GAS 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 GAS; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef XTENSA_RELAX_H #define XTENSA_RELAX_H #include "xtensa-isa.h" /* Data structures for the table-driven relaxations for Xtensa processors. See xtensa-relax.c for details. */ typedef struct transition_list TransitionList; typedef struct transition_table TransitionTable; typedef struct transition_rule TransitionRule; typedef struct precondition_list PreconditionList; typedef struct precondition Precondition; typedef struct req_or_option_list ReqOrOptionList; typedef struct req_or_option_list ReqOrOption; typedef struct req_option_list ReqOptionList; typedef struct req_option_list ReqOption; struct transition_table { int num_opcodes; TransitionList **table; /* Possible transitions for each opcode. */ }; struct transition_list { TransitionRule *rule; TransitionList *next; }; struct precondition_list { Precondition *precond; PreconditionList *next; }; /* The required options for a rule are represented with a two-level structure, with leaf expressions combined by logical ORs at the lower level, and the results then combined by logical ANDs at the top level. The AND terms are linked in a list, and each one can contain a reference to a list of OR terms. The leaf expressions, i.e., the OR options, can be negated by setting the is_true field to FALSE. There are two classes of leaf expressions: (1) those that are properties of the Xtensa configuration and can be evaluated once when building the tables, and (2) those that depend of the state of directives or other settings that may vary during the assembly. The following expressions may be used in group (1): IsaUse*: Xtensa configuration settings. realnop: TRUE if the instruction set includes a NOP instruction. There are currently no expressions in group (2), but they are still supported since there is a good chance they'll be needed again for something. */ struct req_option_list { ReqOrOptionList *or_option_terms; ReqOptionList *next; }; struct req_or_option_list { char *option_name; bfd_boolean is_true; ReqOrOptionList *next; }; /* Operand types and constraints on operands: */ typedef enum op_type OpType; typedef enum cmp_op CmpOp; enum op_type { OP_CONSTANT, OP_OPERAND, OP_OPERAND_LOW8, /* Sign-extended low 8 bits of immed. */ OP_OPERAND_HI24S, /* High 24 bits of immed, plus 0x100 if low 8 bits are signed. */ OP_OPERAND_F32MINUS, /* 32 - immed. */ OP_OPERAND_LOW16U, /* Low 16 bits of immed. */ OP_OPERAND_HI16U, /* High 16 bits of immed. */ OP_LITERAL, OP_LABEL }; enum cmp_op { OP_EQUAL, OP_NOTEQUAL, }; struct precondition { CmpOp cmp; int op_num; OpType typ; /* CONSTANT: op_data is a constant. OPERAND: operand op_num must equal op_data. Cannot be LITERAL or LABEL. */ int op_data; }; typedef struct build_op BuildOp; struct build_op { int op_num; OpType typ; unsigned op_data; /* CONSTANT: op_data is the value to encode. OPERAND: op_data is the field in the source instruction to take the value from and encode in the op_num field here. LITERAL or LABEL: op_data is the ordinal that identifies the appropriate one, i.e., there can be more than one literal or label in an expansion. */ BuildOp *next; }; typedef struct build_instr BuildInstr; typedef enum instr_type InstrType; enum instr_type { INSTR_INSTR, INSTR_LITERAL_DEF, INSTR_LABEL_DEF }; struct build_instr { InstrType typ; unsigned id; /* LITERAL_DEF or LABEL_DEF: an ordinal to identify which one. */ xtensa_opcode opcode; /* Unused for LITERAL_DEF or LABEL_DEF. */ BuildOp *ops; BuildInstr *next; }; struct transition_rule { xtensa_opcode opcode; PreconditionList *conditions; ReqOptionList *options; BuildInstr *to_instr; }; typedef int (*transition_cmp_fn) (const TransitionRule *, const TransitionRule *); extern TransitionTable *xg_build_simplify_table (transition_cmp_fn); extern TransitionTable *xg_build_widen_table (transition_cmp_fn); extern bfd_boolean xg_has_userdef_op_fn (OpType); extern long xg_apply_userdef_op_fn (OpType, long); #endif /* !XTENSA_RELAX_H */
guoqingzhang/binutils-coffee
gas/config/xtensa-relax.h
C
gpl-2.0
5,051
<?php /** * template_lite upper modifier plugin * * Type: modifier * Name: upper * Purpose: Wrapper for the PHP 'strtoupper' function */ function tpl_modifier_upper($string) { return strtoupper($string); } ?>
dreikanter/motoko
mtk/lib/template_lite/plugins/modifier.upper.php
PHP
gpl-2.0
235
.redux-container-switch { /*disable text selection*/ } .redux-container-switch .switch-options { min-height: 30px; margin-right: 10px; } .redux-container-switch .switch-options label { cursor: pointer; } .redux-container-switch .switch-options input { display: none; } .redux-container-switch .cb-enable span, .redux-container-switch .cb-disable span { -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -o-user-select: none; -ms-user-select: none; user-select: none; } .redux-container-switch .cb-enable, .redux-container-switch .cb-disable, .redux-container-switch .cb-enable span, .redux-container-switch .cb-disable span { display: block; float: left; } .redux-container-switch .cb-enable span, .redux-container-switch .cb-disable span { line-height: 30px; display: block; font-weight: 700; } .redux-container-switch .cb-enable, .redux-container-switch .cb-disable { padding: 0 10px; border-width: 1px; border-style: solid; -webkit-appearance: none; professional-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .redux-container-switch .cb-enable { border-right: 0; border-radius: 3px 0px 0px 3px; -moz-border-radius: 3px 0px 0px 3px; -webkit-border-radius: 3px 0px 0px 3px; } .redux-container-switch .cb-disable { border-left: 0; border-radius: 0px 3px 3px 0px; -moz-border-radius: 0px 3px 3px 0px; -webkit-border-radius: 0px 3px 3px 0px; } .redux-container-switch .cb-disable.selected { color: #fff; } .redux-container-switch .cb-enable.selected { color: #fff; }
iGeneralStore/wordpress
wp-content/themes/professional/assets/frameworks/redux/admin/redux-framework/ReduxCore/inc/fields/switch/field_switch.css
CSS
gpl-2.0
1,616
# encoding: utf-8 # module PyKDE4.kdeui # from /usr/lib/python3/dist-packages/PyKDE4/kdeui.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyKDE4.kdecore as __PyKDE4_kdecore import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui import PyQt4.QtSvg as __PyQt4_QtSvg class KPassivePopupMessageHandler(__PyQt4_QtCore.QObject, __PyKDE4_kdecore.KMessageHandler): # no doc def message(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdeui/KPassivePopupMessageHandler.py
Python
gpl-2.0
584
/* * This is free software, licensed under the GNU General Public License v2. * See /LICENSE for more information. * * Copyright (C) 2015 Álvaro Fernández Rojas <[email protected]> */ #ifndef _NAND_H #define _NAND_H #define NAND_PAGE_DEF 2048 #define NAND_OOB_DEF 64 #define NAND_CHECK_ENTRIES 1 #define DEBUG_DEF 0 #define DEBUG_PROG 5 #define pr_info(...) printf(__VA_ARGS__) #define pr_err(...) fprintf(stderr, __VA_ARGS__) enum errors { NO_ERROR = 0, ERROR_ARGS, ERROR_PTR, ERROR_FILE, ERROR_SEEK, ERROR_READ, ERROR_WRITE, ERROR_ENTRIES }; int nand_clean_oob(int debug, int ifd, int ofd, ssize_t size, int nand_page, int nand_oob, int nand_entries); void nand_tools_version(void); #endif /* _NAND_H */
openwrt-es/nandtools
nand.h
C
gpl-2.0
726
/* * Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <ace/Message_Block.h> #include <ace/OS_NS_string.h> #include <ace/OS_NS_unistd.h> #include <ace/os_include/arpa/os_inet.h> #include <ace/os_include/netinet/os_tcp.h> #include <ace/os_include/sys/os_types.h> #include <ace/os_include/sys/os_socket.h> #include <ace/OS_NS_string.h> #include <ace/Reactor.h> #include <ace/Auto_Ptr.h> #include "WorldSocket.h" #include "Common.h" #include "Player.h" #include "Util.h" #include "World.h" #include "WorldPacket.h" #include "SharedDefines.h" #include "ByteBuffer.h" #include "Opcodes.h" #include "DatabaseEnv.h" #include "BigNumber.h" #include "SHA1.h" #include "WorldSession.h" #include "WorldSocketMgr.h" #include "Log.h" #include "PacketLog.h" #include "ScriptMgr.h" #include "AccountMgr.h" #if defined(__GNUC__) #pragma pack(1) #else #pragma pack(push, 1) #endif struct ServerPktHeader { ServerPktHeader(uint32 size, uint32 cmd, AuthCrypt* _authCrypt) : size(size) { if (_authCrypt->IsInitialized()) { uint32 data = (size << 13) | cmd & MAX_OPCODE; memcpy(&header[0], &data, 4); _authCrypt->EncryptSend((uint8*)&header[0], getHeaderLength()); } else { // Dynamic header size is not needed anymore, we are using not encrypted part for only the first few packets memcpy(&header[0], &size, 2); memcpy(&header[2], &cmd, 2); } } uint8 getHeaderLength() { return 4; } const uint32 size; uint8 header[4]; }; struct AuthClientPktHeader { uint16 size; uint32 cmd; }; struct WorldClientPktHeader { uint16 size; uint16 cmd; }; #if defined(__GNUC__) #pragma pack() #else #pragma pack(pop) #endif WorldSocket::WorldSocket (void): WorldHandler(), m_LastPingTime(ACE_Time_Value::zero), m_OverSpeedPings(0), m_Session(0), m_RecvWPct(0), m_RecvPct(), m_Header(sizeof(AuthClientPktHeader)), m_WorldHeader(sizeof(WorldClientPktHeader)), m_OutBuffer(0), m_OutBufferSize(65536), m_OutActive(false), m_Seed(static_cast<uint32> (rand32())) { reference_counting_policy().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED); msg_queue()->high_water_mark(8 * 1024 * 1024); msg_queue()->low_water_mark(8 * 1024 * 1024); } WorldSocket::~WorldSocket (void) { delete m_RecvWPct; if (m_OutBuffer) m_OutBuffer->release(); closing_ = true; peer().close(); } bool WorldSocket::IsClosed (void) const { return closing_; } void WorldSocket::CloseSocket (void) { { ACE_GUARD (LockType, Guard, m_OutBufferLock); if (closing_) return; closing_ = true; peer().close_writer(); } { ACE_GUARD (LockType, Guard, m_SessionLock); m_Session = NULL; } } const std::string& WorldSocket::GetRemoteAddress (void) const { return m_Address; } int WorldSocket::SendPacket(WorldPacket const& pct) { ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1); if (closing_) return -1; // Dump outgoing packet if (sPacketLog->CanLogPacket()) sPacketLog->LogPacket(pct, SERVER_TO_CLIENT); WorldPacket const* pkt = &pct; // Empty buffer used in case packet should be compressed // Disable compression for now :) /* WorldPacket buff; if (m_Session && pkt->size() > 0x400) { buff.Compress(m_Session->GetCompressionStream(), pkt); pkt = &buff; }*/ uint16 opcodeNumber = serveurOpcodeTable[pkt->GetOpcode()]->OpcodeNumber; if (m_Session) TC_LOG_TRACE("network.opcode", "S->C: %s %s", m_Session->GetPlayerInfo().c_str(), GetOpcodeNameForLogging(pkt->GetOpcode(), true).c_str()); sScriptMgr->OnPacketSend(this, *pkt); ServerPktHeader header(!m_Crypt.IsInitialized() ? pkt->size() + 2 : pct.size(), opcodeNumber, &m_Crypt); if (m_OutBuffer->space() >= pkt->size() + header.getHeaderLength() && msg_queue()->is_empty()) { // Put the packet on the buffer. if (m_OutBuffer->copy((char*) header.header, header.getHeaderLength()) == -1) ACE_ASSERT (false); if (!pkt->empty()) if (m_OutBuffer->copy((char*) pkt->contents(), pkt->size()) == -1) ACE_ASSERT (false); } else { // Enqueue the packet. ACE_Message_Block* mb; ACE_NEW_RETURN(mb, ACE_Message_Block(pkt->size() + header.getHeaderLength()), -1); mb->copy((char*) header.header, header.getHeaderLength()); if (!pkt->empty()) mb->copy((const char*)pkt->contents(), pkt->size()); if (msg_queue()->enqueue_tail(mb, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1) { TC_LOG_ERROR("network", "WorldSocket::SendPacket enqueue_tail failed"); mb->release(); return -1; } } return 0; } long WorldSocket::AddReference (void) { return static_cast<long> (add_reference()); } long WorldSocket::RemoveReference (void) { return static_cast<long> (remove_reference()); } int WorldSocket::open (void *a) { ACE_UNUSED_ARG (a); // Prevent double call to this func. if (m_OutBuffer) return -1; // This will also prevent the socket from being Updated // while we are initializing it. m_OutActive = true; // Hook for the manager. if (sWorldSocketMgr->OnSocketOpen(this) == -1) return -1; // Allocate the buffer. ACE_NEW_RETURN (m_OutBuffer, ACE_Message_Block (m_OutBufferSize), -1); // Store peer address. ACE_INET_Addr remote_addr; if (peer().get_remote_addr(remote_addr) == -1) { TC_LOG_ERROR("network", "WorldSocket::open: peer().get_remote_addr errno = %s", ACE_OS::strerror (errno)); return -1; } m_Address = remote_addr.get_host_addr(); // not an opcode. this packet sends raw string WORLD OF WARCRAFT CONNECTION - SERVER TO CLIENT" // because of our implementation, bytes "WO" become the opcode WorldPacket packet(MSG_VERIFY_CONNECTIVITY); packet << std::string("RLD OF WARCRAFT CONNECTION - SERVER TO CLIENT"); if (SendPacket(packet) == -1) return -1; // Register with ACE Reactor if (reactor()->register_handler(this, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK) == -1) { TC_LOG_ERROR("network", "WorldSocket::open: unable to register client handler errno = %s", ACE_OS::strerror (errno)); return -1; } // reactor takes care of the socket from now on remove_reference(); return 0; } int WorldSocket::close (u_long) { shutdown(); closing_ = true; remove_reference(); return 0; } int WorldSocket::handle_input (ACE_HANDLE) { if (closing_) return -1; switch (handle_input_missing_data()) { case -1 : { if ((errno == EWOULDBLOCK) || (errno == EAGAIN)) { return Update(); // interesting line, isn't it ? } TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno)); errno = ECONNRESET; return -1; } case 0: { TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer has closed connection"); errno = ECONNRESET; return -1; } case 1: return 1; default: return Update(); // another interesting line ;) } ACE_NOTREACHED(return -1); } int WorldSocket::handle_output (ACE_HANDLE) { ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1); if (closing_) return -1; size_t send_len = m_OutBuffer->length(); if (send_len == 0) return handle_output_queue(Guard); #ifdef MSG_NOSIGNAL ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len, MSG_NOSIGNAL); #else ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len); #endif // MSG_NOSIGNAL if (n == 0) return -1; else if (n == -1) { if (errno == EWOULDBLOCK || errno == EAGAIN) return schedule_wakeup_output (Guard); return -1; } else if (n < (ssize_t)send_len) //now n > 0 { m_OutBuffer->rd_ptr (static_cast<size_t> (n)); // move the data to the base of the buffer m_OutBuffer->crunch(); return schedule_wakeup_output (Guard); } else //now n == send_len { m_OutBuffer->reset(); return handle_output_queue (Guard); } ACE_NOTREACHED (return 0); } int WorldSocket::handle_output_queue (GuardType& g) { if (msg_queue()->is_empty()) return cancel_wakeup_output(g); ACE_Message_Block* mblk; if (msg_queue()->dequeue_head(mblk, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1) { TC_LOG_ERROR("network", "WorldSocket::handle_output_queue dequeue_head"); return -1; } const size_t send_len = mblk->length(); #ifdef MSG_NOSIGNAL ssize_t n = peer().send(mblk->rd_ptr(), send_len, MSG_NOSIGNAL); #else ssize_t n = peer().send(mblk->rd_ptr(), send_len); #endif // MSG_NOSIGNAL if (n == 0) { mblk->release(); return -1; } else if (n == -1) { if (errno == EWOULDBLOCK || errno == EAGAIN) { msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero); return schedule_wakeup_output (g); } mblk->release(); return -1; } else if (n < (ssize_t)send_len) //now n > 0 { mblk->rd_ptr(static_cast<size_t> (n)); if (msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero) == -1) { TC_LOG_ERROR("network", "WorldSocket::handle_output_queue enqueue_head"); mblk->release(); return -1; } return schedule_wakeup_output (g); } else //now n == send_len { mblk->release(); return msg_queue()->is_empty() ? cancel_wakeup_output(g) : ACE_Event_Handler::WRITE_MASK; } ACE_NOTREACHED(return -1); } int WorldSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask) { // Critical section { ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1); closing_ = true; if (h == ACE_INVALID_HANDLE) peer().close_writer(); } // Critical section { ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1); m_Session = NULL; } reactor()->remove_handler(this, ACE_Event_Handler::DONT_CALL | ACE_Event_Handler::ALL_EVENTS_MASK); return 0; } int WorldSocket::Update (void) { if (closing_) return -1; if (m_OutActive) return 0; { ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, 0); if (m_OutBuffer->length() == 0 && msg_queue()->is_empty()) return 0; } int ret; do ret = handle_output(get_handle()); while (ret > 0); return ret; } int WorldSocket::handle_input_header (void) { ACE_ASSERT(m_RecvWPct == NULL); if (m_Crypt.IsInitialized()) { ACE_ASSERT(m_WorldHeader.length() == sizeof(WorldClientPktHeader)); uint8* uintHeader = (uint8*)m_WorldHeader.rd_ptr(); m_Crypt.DecryptRecv(uintHeader, sizeof(WorldClientPktHeader)); WorldClientPktHeader& header = *(WorldClientPktHeader*)uintHeader; uint32 value = *(uint32*)uintHeader; header.cmd = value & 0x1FFF; header.size = ((value & ~(uint32)0x1FFF) >> 13); if (header.size > 10236) { Player* _player = m_Session ? m_Session->GetPlayer() : NULL; TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)", m_Session ? m_Session->GetAccountId() : 0, _player ? _player->GetGUIDLow() : 0, _player ? _player->GetName().c_str() : "<none>", header.size, header.cmd); errno = EINVAL; return -1; } uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd); ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1); m_RecvWPct->SetReceivedOpcode(opcodeNumber); if (header.size > 0) { m_RecvWPct->resize(header.size); m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size()); } else ACE_ASSERT(m_RecvPct.space() == 0); } else { ACE_ASSERT(m_Header.length() == sizeof(AuthClientPktHeader)); uint8* uintHeader = (uint8*)m_Header.rd_ptr(); AuthClientPktHeader& header = *((AuthClientPktHeader*)uintHeader); if ((header.size < 4) || (header.size > 10240)) { Player* _player = m_Session ? m_Session->GetPlayer() : NULL; TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)", m_Session ? m_Session->GetAccountId() : 0, _player ? _player->GetGUIDLow() : 0, _player ? _player->GetName().c_str() : "<none>", header.size, header.cmd); errno = EINVAL; return -1; } header.size -= 4; uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd); ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1); m_RecvWPct->SetReceivedOpcode(opcodeNumber); if (header.size > 0) { m_RecvWPct->resize(header.size); m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size()); } else ACE_ASSERT(m_RecvPct.space() == 0); } return 0; } int WorldSocket::handle_input_payload (void) { // set errno properly here on error !!! // now have a header and payload if (m_Crypt.IsInitialized()) { ACE_ASSERT (m_RecvPct.space() == 0); ACE_ASSERT (m_WorldHeader.space() == 0); ACE_ASSERT (m_RecvWPct != NULL); const int ret = ProcessIncoming (m_RecvWPct); m_RecvPct.base (NULL, 0); m_RecvPct.reset(); m_RecvWPct = NULL; m_WorldHeader.reset(); if (ret == -1) errno = EINVAL; return ret; } else { ACE_ASSERT(m_RecvPct.space() == 0); ACE_ASSERT(m_Header.space() == 0); ACE_ASSERT(m_RecvWPct != NULL); const int ret = ProcessIncoming(m_RecvWPct); m_RecvPct.base(NULL, 0); m_RecvPct.reset(); m_RecvWPct = NULL; m_Header.reset(); if (ret == -1) errno = EINVAL; return ret; } } int WorldSocket::handle_input_missing_data (void) { char buf [4096]; ACE_Data_Block db (sizeof (buf), ACE_Message_Block::MB_DATA, buf, 0, 0, ACE_Message_Block::DONT_DELETE, 0); ACE_Message_Block message_block(&db, ACE_Message_Block::DONT_DELETE, 0); const size_t recv_size = message_block.space(); const ssize_t n = peer().recv (message_block.wr_ptr(), recv_size); if (n <= 0) return int(n); message_block.wr_ptr (n); while (message_block.length() > 0) { if (m_Crypt.IsInitialized()) { if (m_WorldHeader.space() > 0) { //need to receive the header const size_t to_header = (message_block.length() > m_WorldHeader.space() ? m_WorldHeader.space() : message_block.length()); m_WorldHeader.copy (message_block.rd_ptr(), to_header); message_block.rd_ptr (to_header); if (m_WorldHeader.space() > 0) { // Couldn't receive the whole header this time. ACE_ASSERT (message_block.length() == 0); errno = EWOULDBLOCK; return -1; } // We just received nice new header if (handle_input_header() == -1) { ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN)); return -1; } } } else { if (m_Header.space() > 0) { //need to receive the header const size_t to_header = (message_block.length() > m_Header.space() ? m_Header.space() : message_block.length()); m_Header.copy (message_block.rd_ptr(), to_header); message_block.rd_ptr (to_header); if (m_Header.space() > 0) { // Couldn't receive the whole header this time. ACE_ASSERT (message_block.length() == 0); errno = EWOULDBLOCK; return -1; } // We just received nice new header if (handle_input_header() == -1) { ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN)); return -1; } } } // Its possible on some error situations that this happens // for example on closing when epoll receives more chunked data and stuff // hope this is not hack, as proper m_RecvWPct is asserted around if (!m_RecvWPct) { TC_LOG_ERROR("network", "Forcing close on input m_RecvWPct = NULL"); errno = EINVAL; return -1; } // We have full read header, now check the data payload if (m_RecvPct.space() > 0) { //need more data in the payload const size_t to_data = (message_block.length() > m_RecvPct.space() ? m_RecvPct.space() : message_block.length()); m_RecvPct.copy (message_block.rd_ptr(), to_data); message_block.rd_ptr (to_data); if (m_RecvPct.space() > 0) { // Couldn't receive the whole data this time. ACE_ASSERT (message_block.length() == 0); errno = EWOULDBLOCK; return -1; } } //just received fresh new payload if (handle_input_payload() == -1) { ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN)); return -1; } } return size_t(n) == recv_size ? 1 : 2; } int WorldSocket::cancel_wakeup_output (GuardType& g) { if (!m_OutActive) return 0; m_OutActive = false; g.release(); if (reactor()->cancel_wakeup (this, ACE_Event_Handler::WRITE_MASK) == -1) { // would be good to store errno from reactor with errno guard TC_LOG_ERROR("network", "WorldSocket::cancel_wakeup_output"); return -1; } return 0; } int WorldSocket::schedule_wakeup_output (GuardType& g) { if (m_OutActive) return 0; m_OutActive = true; g.release(); if (reactor()->schedule_wakeup (this, ACE_Event_Handler::WRITE_MASK) == -1) { TC_LOG_ERROR("network", "WorldSocket::schedule_wakeup_output"); return -1; } return 0; } int WorldSocket::ProcessIncoming(WorldPacket* new_pct) { ACE_ASSERT (new_pct); // manage memory ;) ACE_Auto_Ptr<WorldPacket> aptr(new_pct); Opcodes opcode = new_pct->GetOpcode(); if (closing_) return -1; // Dump received packet. if (sPacketLog->CanLogPacket()) sPacketLog->LogPacket(*new_pct, CLIENT_TO_SERVER); std::string opcodeName = GetOpcodeNameForLogging(opcode, false); if (m_Session) TC_LOG_TRACE("network.opcode", "C->S: %s %s", m_Session->GetPlayerInfo().c_str(), opcodeName.c_str()); try { switch (opcode) { case CMSG_PING: return HandlePing(*new_pct); case CMSG_AUTH_SESSION: if (m_Session) { TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming: received duplicate CMSG_AUTH_SESSION from %s", m_Session->GetPlayerInfo().c_str()); return -1; } sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct)); return HandleAuthSession(*new_pct); //case CMSG_KEEP_ALIVE: // sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct)); // return 0; case CMSG_LOG_DISCONNECT: new_pct->rfinish(); // contains uint32 disconnectReason; sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct)); return 0; // not an opcode, client sends string "WORLD OF WARCRAFT CONNECTION - CLIENT TO SERVER" without opcode // first 4 bytes become the opcode (2 dropped) case MSG_VERIFY_CONNECTIVITY: { sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct)); std::string str; *new_pct >> str; if (str != "D OF WARCRAFT CONNECTION - CLIENT TO SERVER") return -1; return HandleSendAuthSession(); } /*case CMSG_ENABLE_NAGLE: { TC_LOG_DEBUG("network", "%s", opcodeName.c_str()); sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct)); return m_Session ? m_Session->HandleEnableNagleAlgorithm() : -1; }*/ default: { ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); if (!m_Session) { TC_LOG_ERROR("network.opcode", "ProcessIncoming: Client not authed opcode = %u", uint32(opcode)); return -1; } // prevent invalid memory access/crash with custom opcodes if (opcode >= NUM_OPCODES) return 0; OpcodeHandler const* handler = clientOpcodeTable[opcode]; if (!handler || handler->Status == STATUS_UNHANDLED) { TC_LOG_ERROR("network.opcode", "No defined handler for opcode %s sent by %s", GetOpcodeNameForLogging(new_pct->GetOpcode(), false, new_pct->GetReceivedOpcode()).c_str(), m_Session->GetPlayerInfo().c_str()); return 0; } // Our Idle timer will reset on any non PING opcodes. // Catches people idling on the login screen and any lingering ingame connections. m_Session->ResetTimeOutTime(); // OK, give the packet to WorldSession aptr.release(); // WARNING here we call it with locks held. // Its possible to cause deadlock if QueuePacket calls back m_Session->QueuePacket(new_pct); return 0; } } } catch (ByteBufferException &) { TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet %s from client %s, accountid=%i. Disconnected client.", opcodeName.c_str(), GetRemoteAddress().c_str(), m_Session ? int32(m_Session->GetAccountId()) : -1); new_pct->hexlike(); return -1; } ACE_NOTREACHED (return 0); } int WorldSocket::HandleSendAuthSession() { WorldPacket packet(SMSG_AUTH_CHALLENGE, 37); packet << uint16(0); for (int i = 0; i < 8; i++) packet << uint32(0); packet << uint8(1); packet << uint32(m_Seed); return SendPacket(packet); } int WorldSocket::HandleAuthSession(WorldPacket& recvPacket) { uint8 digest[20]; uint32 clientSeed; uint8 security; uint16 clientBuild; uint32 id; uint32 addonSize; LocaleConstant locale; std::string account; SHA1Hash sha; BigNumber k; WorldPacket addonsData; recvPacket.read_skip<uint32>(); recvPacket.read_skip<uint32>(); recvPacket >> digest[18]; recvPacket >> digest[14]; recvPacket >> digest[3]; recvPacket >> digest[4]; recvPacket >> digest[0]; recvPacket.read_skip<uint32>(); recvPacket >> digest[11]; recvPacket >> clientSeed; recvPacket >> digest[19]; recvPacket.read_skip<uint8>(); recvPacket.read_skip<uint8>(); recvPacket >> digest[2]; recvPacket >> digest[9]; recvPacket >> digest[12]; recvPacket.read_skip<uint64>(); recvPacket.read_skip<uint32>(); recvPacket >> digest[16]; recvPacket >> digest[5]; recvPacket >> digest[6]; recvPacket >> digest[8]; recvPacket >> clientBuild; recvPacket >> digest[17]; recvPacket >> digest[7]; recvPacket >> digest[13]; recvPacket >> digest[15]; recvPacket >> digest[1]; recvPacket >> digest[10]; recvPacket >> addonSize; addonsData.resize(addonSize); recvPacket.read((uint8*)addonsData.contents(), addonSize); recvPacket.ReadBit(); uint32 accountNameLength = recvPacket.ReadBits(11); account = recvPacket.ReadString(accountNameLength); if (sWorld->IsClosed()) { SendAuthResponseError(AUTH_REJECT); TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: World closed, denying client (%s).", GetRemoteAddress().c_str()); return -1; } // Get the account information from the realmd database // 0 1 2 3 4 5 6 7 8 // SELECT id, sessionkey, last_ip, locked, expansion, mutetime, locale, recruiter, os FROM account WHERE username = ? PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME); stmt->setString(0, account); PreparedQueryResult result = LoginDatabase.Query(stmt); // Stop if the account is not found if (!result) { SendAuthResponseError(AUTH_UNKNOWN_ACCOUNT); TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (unknown account)."); return -1; } Field* fields = result->Fetch(); uint8 expansion = fields[4].GetUInt8(); uint32 world_expansion = sWorld->getIntConfig(CONFIG_EXPANSION); if (expansion > world_expansion) expansion = world_expansion; ///- Re-check ip locking (same check as in realmd). if (fields[3].GetUInt8() == 1) // if ip is locked { if (strcmp (fields[2].GetCString(), GetRemoteAddress().c_str())) { SendAuthResponseError(AUTH_FAILED); TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs)."); return -1; } } id = fields[0].GetUInt32(); k.SetHexStr(fields[1].GetCString()); int64 mutetime = fields[5].GetInt64(); //! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now. if (mutetime < 0) { mutetime = time(NULL) + llabs(mutetime); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN); stmt->setInt64(0, mutetime); stmt->setUInt32(1, id); LoginDatabase.Execute(stmt); } locale = LocaleConstant (fields[6].GetUInt8()); if (locale >= TOTAL_LOCALES) locale = LOCALE_enUS; uint32 recruiter = fields[7].GetUInt32(); std::string os = fields[8].GetString(); // Must be done before WorldSession is created if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED) && os != "Win" && os != "OSX") { SendAuthResponseError(AUTH_REJECT); TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client %s attempted to log in using invalid client OS (%s).", GetRemoteAddress().c_str(), os.c_str()); return -1; } // Checks gmlevel per Realm stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_GMLEVEL_BY_REALMID); stmt->setUInt32(0, id); stmt->setInt32(1, int32(realmID)); result = LoginDatabase.Query(stmt); if (!result) security = 0; else { fields = result->Fetch(); security = fields[0].GetUInt8(); } // Re-check account ban (same check as in realmd) stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BANS); stmt->setUInt32(0, id); stmt->setString(1, GetRemoteAddress()); PreparedQueryResult banresult = LoginDatabase.Query(stmt); if (banresult) // if account banned { SendAuthResponseError(AUTH_BANNED); TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account banned)."); return -1; } // Check locked state for serveur AccountTypes allowedAccountType = sWorld->GetPlayerSecurityLimit(); TC_LOG_DEBUG("network", "Allowed Level: %u Player Level %u", allowedAccountType, AccountTypes(security)); if (allowedAccountType > SEC_PLAYER && AccountTypes(security) < allowedAccountType) { SendAuthResponseError(AUTH_UNAVAILABLE); TC_LOG_INFO("network", "WorldSocket::HandleAuthSession: User tries to login but his security level is not enough"); return -1; } // Check that Key and account name are the same on client and serveur uint32 t = 0; uint32 seed = m_Seed; sha.UpdateData(account); sha.UpdateData((uint8*)&t, 4); sha.UpdateData((uint8*)&clientSeed, 4); sha.UpdateData((uint8*)&seed, 4); sha.UpdateBigNumbers(&k, NULL); sha.Finalize(); std::string address = GetRemoteAddress(); if (memcmp(sha.GetDigest(), digest, 20)) { SendAuthResponseError(AUTH_FAILED); TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Authentication failed for account: %u ('%s') address: %s", id, account.c_str(), address.c_str()); return -1; } TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.", account.c_str(), address.c_str()); // Check if this user is by any chance a recruiter stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_RECRUITER); stmt->setUInt32(0, id); result = LoginDatabase.Query(stmt); bool isRecruiter = false; if (result) isRecruiter = true; // Update the last_ip in the database stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_IP); stmt->setString(0, address); stmt->setString(1, account); LoginDatabase.Execute(stmt); // NOTE ATM the socket is single-threaded, have this in mind ... ACE_NEW_RETURN(m_Session, WorldSession(id, this, AccountTypes(security), expansion, mutetime, locale, recruiter, isRecruiter), -1); m_Crypt.Init(&k); m_Session->LoadGlobalAccountData(); m_Session->LoadTutorialsData(); m_Session->ReadAddonsInfo(addonsData); m_Session->LoadPermissions(); // Initialize Warden system only if it is enabled by config if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED)) m_Session->InitWarden(&k, os); // Sleep this Network thread for uint32 sleepTime = sWorld->getIntConfig(CONFIG_SESSION_ADD_DELAY); ACE_OS::sleep(ACE_Time_Value(0, sleepTime)); sWorld->AddSession(m_Session); return 0; } int WorldSocket::HandlePing (WorldPacket& recvPacket) { uint32 ping; uint32 latency; // Get the ping packet content recvPacket >> latency; recvPacket >> ping; if (m_LastPingTime == ACE_Time_Value::zero) m_LastPingTime = ACE_OS::gettimeofday(); // for 1st ping else { ACE_Time_Value cur_time = ACE_OS::gettimeofday(); ACE_Time_Value diff_time (cur_time); diff_time -= m_LastPingTime; m_LastPingTime = cur_time; if (diff_time < ACE_Time_Value (27)) { ++m_OverSpeedPings; uint32 max_count = sWorld->getIntConfig (CONFIG_MAX_OVERSPEED_PINGS); if (max_count && m_OverSpeedPings > max_count) { ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1); if (m_Session && !m_Session->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_OVERSPEED_PING)) { TC_LOG_ERROR("network", "WorldSocket::HandlePing: %s kicked for over-speed pings (address: %s)", m_Session->GetPlayerInfo().c_str(), GetRemoteAddress().c_str()); return -1; } } } else m_OverSpeedPings = 0; } // critical section { ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1); if (m_Session) { m_Session->SetLatency (latency); m_Session->ResetClientTimeDelay(); } else { TC_LOG_ERROR("network", "WorldSocket::HandlePing: peer sent CMSG_PING, " "but is not authenticated or got recently kicked, " " address = %s", GetRemoteAddress().c_str()); return -1; } } WorldPacket packet(SMSG_PONG, 4); packet << ping; return SendPacket(packet); } void WorldSocket::SendAuthResponseError(uint8 code) { WorldPacket packet(SMSG_AUTH_RESPONSE, 1); packet.WriteBit(0); // has account info packet.WriteBit(0); // has queue info packet << uint8(code); SendPacket(packet); }
MistyWorld/MistyWorld_6xx
src/serveur/jeu/Server/WorldSocket.cpp
C++
gpl-2.0
34,533
<HTML> <HEAD> <TITLE>Jan Kerouac Biography</TITLE> </HEAD> <BODY BACKGROUND="" BGCOLOR="#e7e7ff" TEXT="#000000" LINK="#004fcf" ALINK="#ffff00" VLINK="#006faf"> <H3><IMG ALIGN=MIDDLE SRC="images/jan.jpg">About Jan Kerouac </H3> Jan Kerouac, daughter of Beat Generation novelist Jack Kerouac, was born in 1952 in Albany, New York. Raised on the Lower East Side of New York, she traveled extensively in Mexico and South America in her teenage years and early twenties. Returning to live with her mother Joan Haverty Stuart in Washington State in the late 1970's, she completed her first novel BABY DRIVER, which was published in 1981 by St. Martin's. <P> Her second novel TRAIN SONG was published by Henry Holt in 1988. She has also published and read her poetry at a wide variety of places, and she has taken part in a number of the symposiums on the Beat writers, including the Amsterdam Poetry Festival in 1983, the ON THE ROAD celebration at the Naropa Institute in 1982 and the dedication of the Jack Kerouac Memorial in Lowell in 1988. She was a featured speaker at the international Beat Generation conference at NYU in May, 1994, and she continues to speak out, despite her bad health, about the need to preserve her father's entire archive in a library or a museum. <P> She is currently working on her third novel, PARROT FEVER. A I 10,000-word excerpt is available as a collector's chapbook, signed and numbered, in an edition of 135, for $50 each plus $3 postage and handling. Make checks payable to Jan Kerouac Benefit Fund, 11 Palm Ave., Corte Madera, CA 94925.<P> <A HREF="../LitKicks.html">Literary Kicks</A><BR> <I><A HREF="../IKL/IKL.html">Inside the Kerouac Legacy</A></I><BR> A Special Section Maintained by <A HREF="../IKL/RalphVirgo.html">Ralph Virgo</A> = [email protected]<P> </BODY></HTML>
marceliotstein/literarykicks
IKL/JanBio.html
HTML
gpl-2.0
1,829
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CompanyDirectoryDF.Models { using System; using System.Collections.Generic; public partial class Directory { public Directory() { this.Addresses = new HashSet<Address>(); this.Departments = new HashSet<Department>(); this.DirectoryEmployees = new HashSet<DirectoryEmployee>(); this.PhoneLists = new HashSet<PhoneList>(); this.WebURLWebLocations = new HashSet<WebURLWebLocation>(); } public int ID { get; set; } public string Name { get; set; } public virtual ICollection<Address> Addresses { get; set; } public virtual ICollection<Department> Departments { get; set; } public virtual ICollection<DirectoryEmployee> DirectoryEmployees { get; set; } public virtual ICollection<PhoneList> PhoneLists { get; set; } public virtual ICollection<WebURLWebLocation> WebURLWebLocations { get; set; } } }
Jricklefs/Employee-Directory
CompanyDirectoryDF/Models/Directory.cs
C#
gpl-2.0
1,403
<?php /** * The admin-specific functionality of the plugin. * * @link kjhuer.com * @since 1.0.0 * * @package Za_Collect * @subpackage Za_Collect/admin */ /** * The admin-specific functionality of the plugin. * * Defines the plugin name, version, and two examples hooks for how to * enqueue the admin-specific stylesheet and JavaScript. * * @package Za_Collect * @subpackage Za_Collect/admin * @author Kevin J Huer <[email protected]> */ class Za_Collect_Admin { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. */ public function __construct( $plugin_name, $version ) { $this->plugin_name = $plugin_name; $this->version = $version; } /** * Register the stylesheets for the admin area. * * @since 1.0.0 */ public function enqueue_styles() { wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/za-collect-admin.css', array(), $this->version, 'all' ); } /** * Register the JavaScript for the admin area. * * @since 1.0.0 */ public function enqueue_scripts() { wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/za-collect-admin.js', array( 'jquery' ), $this->version, false ); } /** * Add options page for zaCollect * * @since 1.0.0 */ public function add_plugin_admin_menu(){ add_options_page('zaCollect','zaCollect','manage_options',$this->plugin_name,array($this,'display_plugin_setup_page')); } public function add_action_links( $links ) { /* * Documentation : https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name) */ $settings_link = array( '<a href="' . admin_url( 'options-general.php?page=' . $this->plugin_name ) . '">' . __('Settings', $this->plugin_name) . '</a>', ); return array_merge( $settings_link, $links ); } /** * Render the settings page for this plugin. * * @since 1.0.0 */ public function display_plugin_setup_page() { include_once( 'partials/za-collect-admin-display.php' ); } public function options_update() { register_setting($this->plugin_name, $this->plugin_name, array($this, 'validate')); } public function validate( $input ){ $valid = array(); $valid['referral_id'] = (isset($input['referral_id']) && !empty($input['referral_id']) && preg_match( '/^[0-9]{18}$/', $input['referral_id'] ) ) ? sanitize_text_field($input['referral_id']) : ''; if ( empty($valid['referral_id']) && !empty($input['referral_id']) ) { add_settings_error( 'referral_id', // Setting title 'referral_id_texterror', // Error ID 'Please enter a valid referral ID (18 numbers, no spaces or extra characters)', // Error message 'error' // Type of message ); } $valid['buy_button_text'] =(isset($input['buy_button_text']) && !empty($input['buy_button_text'])) ? sanitize_text_field($input['buy_button_text']) : ''; $valid['accent_color'] = (isset($input['accent_color']) && !empty($input['accent_color'])) ? sanitize_text_field($input['accent_color']) : ''; if ( !empty($valid['accent_color']) && !preg_match( '/^#[a-f0-9]{6}$/i', $valid['accent_color'] ) ) { // if user insert a HEX color with # add_settings_error( 'accent_color', // Setting title 'accent_color_texterror', // Error ID 'Please enter a valid hex value color for accent color', // Error message 'error' // Type of message ); } $valid['accent_text_color'] = (isset($input['accent_text_color']) && !empty($input['accent_text_color'])) ? sanitize_text_field($input['accent_text_color']) : ''; if ( !empty($valid['accent_text_color']) && !preg_match( '/^#[a-f0-9]{6}$/i', $valid['accent_text_color'] ) ) { // if user insert a HEX color with # add_settings_error( 'accent_text_color', // Setting title 'accent_text_color_texterror', // Error ID 'Please enter a valid hex value color for accent text color', // Error message 'error' // Type of message ); } $valid['new_window'] = (isset($input['new_window']) && !empty($input['new_window'])) ? 1 : 0; return $valid; } }
kjameshuer/za-collect
admin/class-za-collect-admin.php
PHP
gpl-2.0
5,664
/* a10 513 * Copyright (c) 2001-2012 Nicolas Léveillé <knos.free.fr> * * You should have received this file ('src/lib/cokus.c') with a license * agreement. ('LICENSE' file) * * Copying, using, modifying and distributing this file are rights * covered under this licensing agreement and are conditioned by its * full acceptance and understanding. * e 513 */ // This is the ``Mersenne Twister'' random number generator MT19937, which // generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) // starting from any odd seed in 0..(2^32 - 1). This version is a recode // by Shawn Cokus ([email protected]) on March 8, 1998 of a version by // Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in // July-August 1997). // // Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha // running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to // generate 300 million random numbers; after recoding: 24.0 sec. for the same // (i.e., 46.5% of original time), so speed is now about 12.5 million random // number generations per second on this machine. // // According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html> // (and paraphrasing a bit in places), the Mersenne Twister is ``designed // with consideration of the flaws of various existing generators,'' has // a period of 2^19937 - 1, gives a sequence that is 623-dimensionally // equidistributed, and ``has passed many stringent tests, including the // die-hard test of G. Marsaglia and the load test of P. Hellekalek and // S. Wegenkittl.'' It is efficient in memory usage (typically using 2506 // to 5012 bytes of static data, depending on data type sizes, and the code // is quite short as well). It generates random numbers in batches of 624 // at a time, so the caching and pipelining of modern systems is exploited. // It is also divide- and mod-free. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published by // the Free Software Foundation (either version 2 of the License or, at your // option, any later version). This library is distributed in the hope that // it will be useful, but WITHOUT ANY WARRANTY, without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU Library General Public License for more details. You should have // received a copy of the GNU Library General Public License along with this // library; if not, write to the Free Software Foundation, Inc., 59 Temple // Place, Suite 330, Boston, MA 02111-1307, USA. // // The code as Shawn received it included the following notice: // // Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When // you use this, send an e-mail to <[email protected]> with // an appropriate reference to your work. // // It would be nice to CC: <[email protected]> when you write. // #include <libc/stdio.h> #include <libc/stdlib.h> #include <libc/stdint.h> // // uint32_t must be an unsigned integer type capable of holding at least 32 // bits; exactly 32 should be fastest, but 64 is better on an Alpha with // GCC at -O3 optimization so try your options and see what's best for you // #define N (624) // length of state vector #define M (397) // a period parameter #define K (0x9908B0DFU) // a magic constant #define hiBit(u) ((u)&0x80000000U) // mask all but highest bit of u #define loBit(u) ((u)&0x00000001U) // mask all but lowest bit of u #define loBits(u) ((u)&0x7FFFFFFFU) // mask the highest bit of u #define mixBits(u, v) (hiBit(u) | loBits(v)) // move hi bit of u to hi bit of v static uint32_t state[N + 1]; // state vector + 1 extra to not violate ANSI C static uint32_t *next; // next random value is computed from here static int left = -1; // can *next++ this many times before reloading extern void seedMT(uint32_t seed) { // // We initialize state[0..(N-1)] via the generator // // x_new = (69069 * x_old) mod 2^32 // // from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's // _The Art of Computer Programming_, Volume 2, 3rd ed. // // Notes (SJC): I do not know what the initial state requirements // of the Mersenne Twister are, but it seems this seeding generator // could be better. It achieves the maximum period for its modulus // (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if // x_initial can be even, you have sequences like 0, 0, 0, ...; // 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, // 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. // // Even if x_initial is odd, if x_initial is 1 mod 4 then // // the lowest bit of x is always 1, // the next-to-lowest bit of x is always 0, // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , // the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , // ... // // and if x_initial is 3 mod 4 then // // the lowest bit of x is always 1, // the next-to-lowest bit of x is always 1, // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , // the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , // ... // // The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is // 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It // also does well in the dimension 2..5 spectral tests, but it could be // better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). // // Note that the random number user does not see the values generated // here directly since reloadMT() will always munge them first, so maybe // none of all of this matters. In fact, the seed values made here could // even be extra-special desirable if the Mersenne Twister theory says // so-- that's why the only change I made is to restrict to odd seeds. // register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state; register int j; for (left = 0, *s++ = x, j = N; --j; *s++ = (x *= 69069U) & 0xFFFFFFFFU) ; } extern uint32_t reloadMT(void) { register uint32_t *p0 = state, *p2 = state + 2, *pM = state + M, s0, s1; register int j; if (left < -1) seedMT(4357U); left = N - 1, next = state + 1; for (s0 = state[0], s1 = state[1], j = N - M + 1; --j; s0 = s1, s1 = *p2++) *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); for (pM = state, j = M; --j; s0 = s1, s1 = *p2++) *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); s1 = state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9D2C5680U; s1 ^= (s1 << 15) & 0xEFC60000U; return (s1 ^ (s1 >> 18)); } extern uint32_t randomMT(void) { uint32_t y; if (--left < 0) return (reloadMT()); y = *next++; y ^= (y >> 11); y ^= (y << 7) & 0x9D2C5680U; y ^= (y << 15) & 0xEFC60000U; return (y ^ (y >> 18)); } #if 0 int main(void) { int j; // you can seed with any uint32_t, but the best are odds in 0..(2^32 - 1) seedMT(4357U); // print the first 2,002 random numbers seven to a line as an example for(j=0; j<2002; j++) printf(" %10lu%s", (unsigned long) randomMT(), (j%7)==6 ? "\n" : ""); return(EXIT_SUCCESS); } #endif
uucidl/plus-one-minus-one
src/lib/cokus.c
C
gpl-2.0
7,813
/* * Copyright (C) ST-Ericsson SA 2010,2011 * * Author: Chris Blair <[email protected]> for ST-Ericsson * * License terms: GNU General Public License (GPL) version 2 * * U9500 <-> M6718 IPC protocol implementation using SPI. * state machine definition and functionality. */ #include <linux/modem/m6718_spi/modem_driver.h> #include "modem_statemachine.h" #include "modem_util.h" #include "modem_netlink.h" #include "modem_debug.h" #include "modem_queue.h" #include "modem_protocol.h" #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE #include "modem_state.h" #endif #define CMD_BOOTREQ (1) #define CMD_BOOTRESP (2) #define CMD_WRITE (3) #define CMD_READ (4) static u8 sm_init_enter(u8 event, struct ipc_link_context *context) { #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE /* if modem is off un-configure the IPC GPIO pins for low-power */ if (modem_state_get_state() == MODEM_STATE_OFF) { dev_info(&context->sdev->dev, "link %d: modem is off, un-configuring GPIO\n", context->link->id); ipc_util_link_gpio_unconfig(context); } #endif /* nothing more to do until an event happens */ return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_init_exit(u8 event, struct ipc_link_context *context) { bool int_active = false; /* * For reset event just re-enter init in case the modem has * powered off - we need to reconfigure our GPIO pins */ if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_INIT); /* re-sample link INT pin */ int_active = ipc_util_int_is_active(context); atomic_set(&context->state_int, int_active); dev_info(&context->sdev->dev, "link %d: link initialised; SS:INACTIVE(%d) INT:%s(%d)\n", context->link->id, ipc_util_ss_level_inactive(context), int_active ? "ACTIVE" : "INACTIVE", int_active ? ipc_util_int_level_active(context) : ipc_util_int_level_inactive(context)); /* handshake is only on link 0 */ if (context->link->id == 0) { if (!int_active) { dev_info(&context->sdev->dev, "link %d: slave INT signal is inactive\n", context->link->id); /* start boot handshake */ return ipc_sm_state(IPC_SM_SLW_TX_BOOTREQ); } else { /* wait for slave INT signal to stabilise inactive */ return ipc_sm_state(IPC_SM_WAIT_SLAVE_STABLE); } } else { dev_info(&context->sdev->dev, "link %d: boot sync not needed, going idle\n", context->link->id); return ipc_sm_state(IPC_SM_IDL); } } static const struct ipc_sm_state *sm_init_aud_exit(u8 event, struct ipc_link_context *context) { bool int_active = false; /* * For reset event just re-enter init in case the modem has * powered off - we need to reconfigure our GPIO pins */ if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_INIT_AUD); /* re-sample link INT pin */ int_active = ipc_util_int_is_active(context); atomic_set(&context->state_int, int_active); dev_info(&context->sdev->dev, "link %d: link initialised; SS:INACTIVE(%d) INT:%s(%d)\n", context->link->id, ipc_util_ss_level_inactive(context), int_active ? "ACTIVE" : "INACTIVE", int_active ? ipc_util_int_level_active(context) : ipc_util_int_level_inactive(context)); dev_info(&context->sdev->dev, "link %d: boot sync not needed, going idle\n", context->link->id); return ipc_sm_state(IPC_SM_IDL_AUD); } static u8 sm_wait_slave_stable_enter(u8 event, struct ipc_link_context *context) { static unsigned long printk_warn_time; if (printk_timed_ratelimit(&printk_warn_time, 60 * 1000)) dev_info(&context->sdev->dev, "link %d: waiting for stable inactive slave INT\n", context->link->id); ipc_util_start_slave_stable_timer(context); return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_wait_slave_stable_exit(u8 event, struct ipc_link_context *context) { if (!ipc_util_int_is_active(context)) { dev_info(&context->sdev->dev, "link %d: slave INT signal is stable inactive\n", context->link->id); return ipc_sm_state(IPC_SM_SLW_TX_BOOTREQ); } else { return ipc_sm_state(IPC_SM_WAIT_SLAVE_STABLE); } } static u8 sm_wait_handshake_inactive_enter(u8 event, struct ipc_link_context *context) { dev_info(&context->sdev->dev, "link %d: waiting for stable inactive slave INT\n", context->link->id); ipc_util_start_slave_stable_timer(context); return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_wait_handshake_inactive_exit(u8 event, struct ipc_link_context *context) { int i; if (!ipc_util_int_is_active(context)) { dev_info(&context->sdev->dev, "link %d: slave INT signal is inactive, going idle\n", context->link->id); /* modem sync is done */ atomic_inc(&l1_context.boot_sync_done); ipc_broadcast_modem_online(context); /* * Kick the state machine for any initialised links - skip link0 * since this link has just completed handshake */ for (i = 1; i < IPC_NBR_SUPPORTED_SPI_LINKS; i++) if (l1_context.device_context[i].state != NULL) { dev_dbg(&context->sdev->dev, "link %d has already been probed, " "kicking state machine\n", i); ipc_sm_kick(IPC_SM_RUN_INIT, &l1_context.device_context[i]); } return ipc_sm_state(IPC_SM_IDL); } else { return ipc_sm_state(IPC_SM_WAIT_HANDSHAKE_INACTIVE); } } static u8 sm_idl_enter(u8 event, struct ipc_link_context *context) { ipc_util_deactivate_ss(context); ipc_dbg_enter_idle(context); /* check if tx queue contains items */ if (atomic_read(&context->tx_q_count) > 0) { dev_dbg(&context->sdev->dev, "link %d: tx queue contains items\n", context->link->id); return IPC_SM_RUN_TX_REQ; } /* check if modem has already requested transaction start */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); return IPC_SM_RUN_SLAVE_IRQ; } dev_dbg(&context->sdev->dev, "link %d: going idle\n", context->link->id); return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_idl_exit(u8 event, struct ipc_link_context *context) { ipc_dbg_exit_idle(context); if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else if (event == IPC_SM_RUN_TX_REQ) return ipc_sm_state(IPC_SM_SLW_TX_WR_CMD); else if (event == IPC_SM_RUN_SLAVE_IRQ) return ipc_sm_state(IPC_SM_SLW_TX_RD_CMD); else return ipc_sm_state(IPC_SM_HALT); } static const struct ipc_sm_state *sm_idl_aud_exit(u8 event, struct ipc_link_context *context) { ipc_dbg_exit_idle(context); if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET_AUD); /* always transmit data first */ return ipc_sm_state(IPC_SM_SLW_TX_WR_DAT_AUD); } static u8 sm_slw_tx_wr_cmd_enter(u8 event, struct ipc_link_context *context) { struct ipc_tx_queue *frame; /* get the frame from the head of the tx queue */ if (ipc_queue_is_empty(context)) { dev_err(&context->sdev->dev, "link %d error: tx queue is empty!\n", context->link->id); return IPC_SM_RUN_ABORT; } frame = ipc_queue_get_frame(context); ipc_dbg_dump_frame(&context->sdev->dev, context->link->id, frame, true); context->cmd = ipc_util_make_l1_header(CMD_WRITE, frame->counter, frame->len); dev_dbg(&context->sdev->dev, "link %d: TX FRAME cmd %08x (type %d counter %d len %d)\n", context->link->id, context->cmd, ipc_util_get_l1_cmd(context->cmd), ipc_util_get_l1_counter(context->cmd), ipc_util_get_l1_length(context->cmd)); ipc_util_spi_message_prepare(context, &context->cmd, NULL, IPC_L1_HDR_SIZE); context->frame = frame; /* slave might already have signalled ready to transmit */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } static const struct ipc_sm_state *sm_slw_tx_wr_cmd_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else if (event == IPC_SM_RUN_COMMS_TMO) return ipc_sm_state(IPC_SM_HALT); else return ipc_sm_state(IPC_SM_ACT_TX_WR_CMD); } static u8 sm_act_tx_wr_cmd_enter(u8 event, struct ipc_link_context *context) { int err; /* slave is ready - start the spi transfer */ dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_tx_wr_cmd_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else return ipc_sm_state(IPC_SM_SLW_TX_WR_DAT); } static u8 sm_slw_tx_wr_dat_enter(u8 event, struct ipc_link_context *context) { /* prepare to transfer the frame tx data */ ipc_util_spi_message_prepare(context, context->frame->data, NULL, context->frame->len); /* slave might already have signalled ready to transmit */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } static u8 sm_slw_tx_wr_dat_aud_enter(u8 event, struct ipc_link_context *context) { struct ipc_tx_queue *frame = NULL; /* check if there is a frame to be sent */ if (!ipc_queue_is_empty(context)) { frame = ipc_queue_get_frame(context); } else { /* no frame to send, create an empty one */ dev_dbg(&context->sdev->dev, "link %d: no frame to send, allocating dummy\n", context->link->id); frame = ipc_queue_new_frame(context, 0); if (frame == NULL) return IPC_SM_RUN_ABORT; } ipc_dbg_dump_frame(&context->sdev->dev, context->link->id, frame, true); /* prepare to transfer the frame tx data */ context->frame = frame; ipc_util_spi_message_prepare(context, context->frame->data, NULL, context->frame->len); /* slave might already have signalled ready to transmit */ if (event == IPC_SM_RUN_SLAVE_IRQ || atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } static const struct ipc_sm_state *sm_slw_tx_wr_dat_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else if (event == IPC_SM_RUN_COMMS_TMO) return ipc_sm_state(IPC_SM_HALT); else return ipc_sm_state(IPC_SM_ACT_TX_WR_DAT); } static const struct ipc_sm_state *sm_slw_tx_wr_dat_aud_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET_AUD); else if (event == IPC_SM_RUN_COMMS_TMO) return ipc_sm_state(IPC_SM_HALT_AUD); else return ipc_sm_state(IPC_SM_ACT_TX_WR_DAT_AUD); } static u8 sm_act_tx_wr_dat_enter(u8 event, struct ipc_link_context *context) { int err; /* slave is ready - start the spi transfer */ dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_tx_wr_dat_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT /* frame is sent, increment link tx counter */ context->tx_bytes += context->frame->actual_len; #endif #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_VERIFY_FRAMES { u8 channel; channel = ipc_util_get_l2_channel(*(u32 *)context->frame->data); if (ipc_util_channel_is_loopback(channel)) { context->last_frame = context->frame; } else { ipc_queue_delete_frame(context->frame); context->frame = NULL; } } #else /* free the sent frame */ ipc_queue_delete_frame(context->frame); context->frame = NULL; #endif return ipc_sm_state(IPC_SM_SLW_TX_RD_CMD); } static const struct ipc_sm_state *sm_act_tx_wr_dat_aud_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET_AUD); #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT /* frame is sent, increment link tx counter */ context->tx_bytes += context->frame->actual_len; #endif #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_VERIFY_FRAMES { u8 channel; channel = ipc_util_get_l2_channel(*(u32 *)context->frame->data); if (ipc_util_channel_is_loopback(channel)) { /* create a copy of the frame */ context->last_frame = ipc_queue_new_frame(context, context->frame->actual_len); memcpy(context->last_frame->data, context->frame->data, context->frame->actual_len); } } #endif return ipc_sm_state(IPC_SM_SLW_RX_WR_DAT_AUD); } static u8 sm_slw_tx_rd_cmd_enter(u8 event, struct ipc_link_context *context) { context->cmd = ipc_util_make_l1_header(CMD_READ, 0, 0); dev_dbg(&context->sdev->dev, "link %d: cmd %08x (type %d)\n", context->link->id, context->cmd, ipc_util_get_l1_cmd(context->cmd)); /* prepare the spi message to transfer */ ipc_util_spi_message_prepare(context, &context->cmd, NULL, IPC_L1_HDR_SIZE); /* check if the slave requested this transaction */ if (event == IPC_SM_RUN_SLAVE_IRQ) { dev_dbg(&context->sdev->dev, "link %d: slave initiated transaction, continue\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { /* slave might already have signalled ready to transmit */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } } static const struct ipc_sm_state *sm_slw_tx_rd_cmd_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else if (event == IPC_SM_RUN_COMMS_TMO) return ipc_sm_state(IPC_SM_HALT); else return ipc_sm_state(IPC_SM_ACT_TX_RD_CMD); } static u8 sm_act_tx_rd_cmd_enter(u8 event, struct ipc_link_context *context) { int err; /* slave is ready - start the spi transfer */ dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_tx_rd_cmd_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else return ipc_sm_state(IPC_SM_SLW_RX_WR_CMD); } static u8 sm_slw_rx_wr_cmd_enter(u8 event, struct ipc_link_context *context) { /* prepare to receive MESSAGE WRITE frame header */ ipc_util_spi_message_prepare(context, NULL, &context->cmd, IPC_L1_HDR_SIZE); /* slave might already have signalled ready to transmit */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } static const struct ipc_sm_state *sm_slw_rx_wr_cmd_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); else if (event == IPC_SM_RUN_COMMS_TMO) return ipc_sm_state(IPC_SM_HALT); else return ipc_sm_state(IPC_SM_ACT_RX_WR_CMD); } static u8 sm_act_rx_wr_cmd_enter(u8 event, struct ipc_link_context *context) { int err; /* slave is ready - start the spi transfer */ dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_rx_wr_cmd_exit(u8 event, struct ipc_link_context *context) { u8 cmd_type = ipc_util_get_l1_cmd(context->cmd); int counter = ipc_util_get_l1_counter(context->cmd); int length = ipc_util_get_l1_length(context->cmd); dev_dbg(&context->sdev->dev, "link %d: RX HEADER %08x (type %d counter %d length %d)\n", context->link->id, context->cmd, cmd_type, counter, length); if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); if (cmd_type == CMD_WRITE) { /* slave has data to send - allocate a frame to hold it */ context->frame = ipc_queue_new_frame(context, length); if (context->frame == NULL) return ipc_sm_state(IPC_SM_IDL); context->frame->counter = counter; ipc_util_spi_message_prepare(context, NULL, context->frame->data, context->frame->len); return ipc_sm_state(IPC_SM_ACT_RX_WR_DAT); } else { if (cmd_type != 0) dev_err(&context->sdev->dev, "link %d error: received invalid frame type %x " "(%08x)! assuming TRANSACTION_END...\n", context->link->id, cmd_type, context->cmd); /* slave has no data to send */ dev_dbg(&context->sdev->dev, "link %d: slave has no data to send\n", context->link->id); return ipc_sm_state(IPC_SM_IDL); } } static u8 sm_slw_rx_wr_dat_aud_enter(u8 event, struct ipc_link_context *context) { /* * We're using the same frame buffer we just sent, so no need for a * new allocation here, just prepare the spi message */ ipc_util_spi_message_prepare(context, NULL, context->frame->data, context->frame->len); /* slave might already have signalled ready to transmit */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } static const struct ipc_sm_state *sm_slw_rx_wr_dat_aud_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET_AUD); else if (event == IPC_SM_RUN_COMMS_TMO) return ipc_sm_state(IPC_SM_HALT_AUD); else return ipc_sm_state(IPC_SM_ACT_RX_WR_DAT_AUD); } static u8 sm_act_rx_wr_dat_enter(u8 event, struct ipc_link_context *context) { int err; /* assume slave is still ready - prepare and start the spi transfer */ ipc_util_spi_message_prepare(context, NULL, context->frame->data, context->frame->len); dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static u8 sm_act_rx_wr_dat_aud_enter(u8 event, struct ipc_link_context *context) { int err; dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_rx_wr_dat_exit(u8 event, struct ipc_link_context *context) { u32 frame_hdr; unsigned char l2_header; unsigned int l2_length; u8 *l2_data; if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET); dev_dbg(&context->sdev->dev, "link %d: RX PAYLOAD %d bytes\n", context->link->id, context->frame->len); #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT /* frame is received, increment link rx counter */ context->rx_bytes += context->frame->len; #endif /* decode L2 header */ frame_hdr = *(u32 *)context->frame->data; l2_header = ipc_util_get_l2_channel(frame_hdr); l2_length = ipc_util_get_l2_length(frame_hdr); l2_data = (u8 *)context->frame->data + IPC_L2_HDR_SIZE; context->frame->actual_len = l2_length + IPC_L2_HDR_SIZE; ipc_dbg_dump_frame(&context->sdev->dev, context->link->id, context->frame, false); if (l2_length > (context->frame->len - 4)) { dev_err(&context->sdev->dev, "link %d: suspicious frame: L1 len %d L2 len %d\n", context->link->id, context->frame->len, l2_length); } dev_dbg(&context->sdev->dev, "link %d: L2 PDU decode: header 0x%08x channel %d length %d " "data[%02x%02x%02x...]\n", context->link->id, frame_hdr, l2_header, l2_length, l2_data[0], l2_data[1], l2_data[2]); if (ipc_util_channel_is_loopback(l2_header)) ipc_dbg_verify_rx_frame(context); /* pass received frame up to L2mux layer */ if (!modem_protocol_channel_is_open(l2_header)) { dev_err(&context->sdev->dev, "link %d error: received frame on invalid channel %d, " "frame discarded\n", context->link->id, l2_header); } else { #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT /* * Discard loopback frames if we are taking throughput * measurements - we'll be loading the links and so will likely * overload the buffers. */ if (!ipc_util_channel_is_loopback(l2_header)) #endif modem_m6718_spi_receive(context->sdev, l2_header, l2_length, l2_data); } /* data is copied by L2mux so free the frame here */ ipc_queue_delete_frame(context->frame); context->frame = NULL; /* check tx queue for content */ if (!ipc_queue_is_empty(context)) { dev_dbg(&context->sdev->dev, "link %d: tx queue not empty\n", context->link->id); return ipc_sm_state(IPC_SM_SLW_TX_WR_CMD); } else { dev_dbg(&context->sdev->dev, "link %d: tx queue empty\n", context->link->id); return ipc_sm_state(IPC_SM_SLW_TX_RD_CMD); } } static const struct ipc_sm_state *sm_act_rx_wr_dat_aud_exit(u8 event, struct ipc_link_context *context) { u32 frame_hdr; unsigned char l2_header; unsigned int l2_length; u8 *l2_data; if (event == IPC_SM_RUN_RESET) return ipc_sm_state(IPC_SM_RESET_AUD); dev_dbg(&context->sdev->dev, "link %d: RX PAYLOAD %d bytes\n", context->link->id, context->frame->len); /* decode L2 header */ frame_hdr = *(u32 *)context->frame->data; l2_header = ipc_util_get_l2_channel(frame_hdr); l2_length = ipc_util_get_l2_length(frame_hdr); l2_data = (u8 *)context->frame->data + IPC_L2_HDR_SIZE; #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT /* frame is received, increment link rx counter */ context->rx_bytes += l2_length; #endif if (frame_hdr != 0) context->frame->actual_len = l2_length + IPC_L2_HDR_SIZE; else context->frame->actual_len = 0; ipc_dbg_dump_frame(&context->sdev->dev, context->link->id, context->frame, false); if (l2_length > (context->frame->len - 4)) dev_err(&context->sdev->dev, "link %d: suspicious frame: L1 len %d L2 len %d\n", context->link->id, context->frame->len, l2_length); dev_dbg(&context->sdev->dev, "link %d: L2 PDU decode: header 0x%08x channel %d length %d " "data[%02x%02x%02x...]\n", context->link->id, frame_hdr, l2_header, l2_length, l2_data[0], l2_data[1], l2_data[2]); if (ipc_util_channel_is_loopback(l2_header)) ipc_dbg_verify_rx_frame(context); /* did the slave actually have anything to send? */ if (frame_hdr != 0) { /* pass received frame up to L2mux layer */ if (!modem_protocol_channel_is_open(l2_header)) { dev_err(&context->sdev->dev, "link %d error: received frame on invalid " "channel %d, frame discarded\n", context->link->id, l2_header); } else { #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_THROUGHPUT_MEASUREMENT /* * Discard loopback frames if we are taking throughput * measurements - we'll be loading the links and so will * likely overload the buffers. */ if (!ipc_util_channel_is_loopback(l2_header)) #endif modem_m6718_spi_receive(context->sdev, l2_header, l2_length, l2_data); } } else { dev_dbg(&context->sdev->dev, "link %d: received dummy frame, discarding\n", context->link->id); } /* data is copied by L2mux so free the frame here */ ipc_queue_delete_frame(context->frame); context->frame = NULL; /* audio link goes idle ready for next transaction */ return ipc_sm_state(IPC_SM_IDL_AUD); } static u8 sm_halt_enter(u8 event, struct ipc_link_context *context) { dev_err(&context->sdev->dev, "link %d error: HALTED\n", context->link->id); #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE /* * Force modem reset, this will cause a reset event from the modemstate * driver which will reset the links. If debugfs is enabled then there * is a userspace file which controls whether MSR is enabled or not. */ #ifdef CONFIG_DEBUG_FS if (l1_context.msr_disable) { dev_info(&context->sdev->dev, "link %d: MSR is disabled by user, " "not requesting modem reset\n", context->link->id); return IPC_SM_RUN_RESET; } #endif modem_state_force_reset(); #endif return IPC_SM_RUN_RESET; } static const struct ipc_sm_state *sm_halt_exit(u8 event, struct ipc_link_context *context) { return ipc_sm_state(IPC_SM_RESET); } static const struct ipc_sm_state *sm_halt_aud_exit(u8 event, struct ipc_link_context *context) { return ipc_sm_state(IPC_SM_RESET_AUD); } static u8 sm_reset_enter(u8 event, struct ipc_link_context *context) { dev_err(&context->sdev->dev, "link %d resetting\n", context->link->id); if (context->link->id == 0) ipc_broadcast_modem_reset(context); ipc_util_deactivate_ss(context); ipc_queue_reset(context); if (context->frame != NULL) { ipc_queue_delete_frame(context->frame); context->frame = NULL; } #ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_VERIFY_FRAMES if (context->last_frame != NULL) { ipc_queue_delete_frame(context->last_frame); context->last_frame = NULL; } #endif dev_dbg(&context->sdev->dev, "link %d reset completed\n", context->link->id); return IPC_SM_RUN_RESET; } static const struct ipc_sm_state *sm_reset_exit(u8 event, struct ipc_link_context *context) { return ipc_sm_state(IPC_SM_INIT); } static const struct ipc_sm_state *sm_reset_aud_exit(u8 event, struct ipc_link_context *context) { return ipc_sm_state(IPC_SM_INIT_AUD); } static u8 sm_slw_tx_bootreq_enter(u8 event, struct ipc_link_context *context) { dev_info(&context->sdev->dev, "link %d: waiting for boot sync\n", context->link->id); ipc_util_activate_ss(context); context->cmd = ipc_util_make_l1_header(CMD_BOOTREQ, 0, IPC_DRIVER_VERSION); dev_dbg(&context->sdev->dev, "link %d: TX HEADER cmd %08x (type %x)\n", context->link->id, context->cmd, ipc_util_get_l1_cmd(context->cmd)); ipc_util_spi_message_prepare(context, &context->cmd, NULL, IPC_L1_HDR_SIZE); /* wait now for the slave to indicate ready... */ return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_slw_tx_bootreq_exit(u8 event, struct ipc_link_context *context) { return ipc_sm_state(IPC_SM_ACT_TX_BOOTREQ); } static u8 sm_act_tx_bootreq_enter(u8 event, struct ipc_link_context *context) { int err; /* slave is ready - start the spi transfer */ dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_tx_bootreq_exit(u8 event, struct ipc_link_context *context) { return ipc_sm_state(IPC_SM_SLW_RX_BOOTRESP); } static u8 sm_slw_rx_bootresp_enter(u8 event, struct ipc_link_context *context) { /* prepare to receive BOOTRESP frame header */ ipc_util_spi_message_prepare(context, NULL, &context->cmd, IPC_L1_HDR_SIZE); /* slave might already have signalled ready to transmit */ if (atomic_read(&context->state_int)) { dev_dbg(&context->sdev->dev, "link %d: slave has already signalled ready\n", context->link->id); ipc_util_activate_ss(context); return IPC_SM_RUN_SLAVE_IRQ; } else { ipc_util_activate_ss_with_tmo(context); return IPC_SM_RUN_NONE; } } static const struct ipc_sm_state *sm_slw_rx_bootresp_exit(u8 event, struct ipc_link_context *context) { if (event == IPC_SM_RUN_COMMS_TMO) { /* * Modem timeout: was it really ready or just noise? * Revert to waiting for handshake to start. */ ipc_util_deactivate_ss(context); return ipc_sm_state(IPC_SM_SLW_TX_BOOTREQ); } else { return ipc_sm_state(IPC_SM_ACT_RX_BOOTRESP); } } static u8 sm_act_rx_bootresp_enter(u8 event, struct ipc_link_context *context) { int err; /* slave is ready - start the spi transfer */ dev_dbg(&context->sdev->dev, "link %d: starting spi tfr\n", context->link->id); err = spi_async(context->sdev, &context->spi_message); if (err < 0) { dev_err(&context->sdev->dev, "link %d error: spi tfr start failed, error %d\n", context->link->id, err); return IPC_SM_RUN_ABORT; } return IPC_SM_RUN_NONE; } static const struct ipc_sm_state *sm_act_rx_bootresp_exit(u8 event, struct ipc_link_context *context) { u8 cmd_type = ipc_util_get_l1_cmd(context->cmd); u8 modem_ver; dev_dbg(&context->sdev->dev, "link %d: RX HEADER %08x (type %d)\n", context->link->id, context->cmd, cmd_type); if (cmd_type == CMD_BOOTRESP) { modem_ver = ipc_util_get_l1_bootresp_ver(context->cmd); dev_info(&context->sdev->dev, "link %d: boot sync done; " "APE version %02x, MODEM version %02x\n", context->link->id, IPC_DRIVER_VERSION, modem_ver); /* check for minimum required modem version */ if (modem_ver < IPC_DRIVER_MODEM_MIN_VER) { dev_warn(&context->sdev->dev, "link %d warning: modem version mismatch! " "minimum required version is %02x\n", context->link->id, IPC_DRIVER_MODEM_MIN_VER); } return ipc_sm_state(IPC_SM_WAIT_HANDSHAKE_INACTIVE); } else { /* invalid response... this is not our slave */ dev_err(&context->sdev->dev, "link %d error: expected %x (BOOTRESP), received %x.\n", context->link->id, CMD_BOOTRESP, cmd_type); return ipc_sm_state(IPC_SM_HALT); } } /* the driver protocol state machine */ static const struct ipc_sm_state state_machine[IPC_SM_STATE_ID_NBR] = { [IPC_SM_INIT] = { .id = IPC_SM_INIT, .enter = sm_init_enter, .exit = sm_init_exit, .events = IPC_SM_RUN_INIT | IPC_SM_RUN_RESET }, [IPC_SM_HALT] = { .id = IPC_SM_HALT, .enter = sm_halt_enter, .exit = sm_halt_exit, .events = IPC_SM_RUN_RESET }, [IPC_SM_RESET] = { .id = IPC_SM_RESET, .enter = sm_reset_enter, .exit = sm_reset_exit, .events = IPC_SM_RUN_RESET }, [IPC_SM_WAIT_SLAVE_STABLE] = { .id = IPC_SM_WAIT_SLAVE_STABLE, .enter = sm_wait_slave_stable_enter, .exit = sm_wait_slave_stable_exit, .events = IPC_SM_RUN_STABLE_TMO }, [IPC_SM_WAIT_HANDSHAKE_INACTIVE] = { .id = IPC_SM_WAIT_HANDSHAKE_INACTIVE, .enter = sm_wait_handshake_inactive_enter, .exit = sm_wait_handshake_inactive_exit, .events = IPC_SM_RUN_STABLE_TMO }, [IPC_SM_SLW_TX_BOOTREQ] = { .id = IPC_SM_SLW_TX_BOOTREQ, .enter = sm_slw_tx_bootreq_enter, .exit = sm_slw_tx_bootreq_exit, .events = IPC_SM_RUN_SLAVE_IRQ }, [IPC_SM_ACT_TX_BOOTREQ] = { .id = IPC_SM_ACT_TX_BOOTREQ, .enter = sm_act_tx_bootreq_enter, .exit = sm_act_tx_bootreq_exit, .events = IPC_SM_RUN_TFR_COMPLETE }, [IPC_SM_SLW_RX_BOOTRESP] = { .id = IPC_SM_SLW_RX_BOOTRESP, .enter = sm_slw_rx_bootresp_enter, .exit = sm_slw_rx_bootresp_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO }, [IPC_SM_ACT_RX_BOOTRESP] = { .id = IPC_SM_ACT_RX_BOOTRESP, .enter = sm_act_rx_bootresp_enter, .exit = sm_act_rx_bootresp_exit, .events = IPC_SM_RUN_TFR_COMPLETE }, [IPC_SM_IDL] = { .id = IPC_SM_IDL, .enter = sm_idl_enter, .exit = sm_idl_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_TX_REQ | IPC_SM_RUN_RESET }, [IPC_SM_SLW_TX_WR_CMD] = { .id = IPC_SM_SLW_TX_WR_CMD, .enter = sm_slw_tx_wr_cmd_enter, .exit = sm_slw_tx_wr_cmd_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO | IPC_SM_RUN_RESET }, [IPC_SM_ACT_TX_WR_CMD] = { .id = IPC_SM_ACT_TX_WR_CMD, .enter = sm_act_tx_wr_cmd_enter, .exit = sm_act_tx_wr_cmd_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET }, [IPC_SM_SLW_TX_WR_DAT] = { .id = IPC_SM_SLW_TX_WR_DAT, .enter = sm_slw_tx_wr_dat_enter, .exit = sm_slw_tx_wr_dat_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO | IPC_SM_RUN_RESET }, [IPC_SM_ACT_TX_WR_DAT] = { .id = IPC_SM_ACT_TX_WR_DAT, .enter = sm_act_tx_wr_dat_enter, .exit = sm_act_tx_wr_dat_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET }, [IPC_SM_SLW_TX_RD_CMD] = { .id = IPC_SM_SLW_TX_RD_CMD, .enter = sm_slw_tx_rd_cmd_enter, .exit = sm_slw_tx_rd_cmd_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO | IPC_SM_RUN_RESET }, [IPC_SM_ACT_TX_RD_CMD] = { .id = IPC_SM_ACT_TX_RD_CMD, .enter = sm_act_tx_rd_cmd_enter, .exit = sm_act_tx_rd_cmd_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET }, [IPC_SM_SLW_RX_WR_CMD] = { .id = IPC_SM_SLW_RX_WR_CMD, .enter = sm_slw_rx_wr_cmd_enter, .exit = sm_slw_rx_wr_cmd_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO | IPC_SM_RUN_RESET }, [IPC_SM_ACT_RX_WR_CMD] = { .id = IPC_SM_ACT_RX_WR_CMD, .enter = sm_act_rx_wr_cmd_enter, .exit = sm_act_rx_wr_cmd_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET }, [IPC_SM_ACT_RX_WR_DAT] = { .id = IPC_SM_ACT_RX_WR_DAT, .enter = sm_act_rx_wr_dat_enter, .exit = sm_act_rx_wr_dat_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET }, /* audio link states below */ [IPC_SM_INIT_AUD] = { .id = IPC_SM_INIT_AUD, .enter = sm_init_enter, .exit = sm_init_aud_exit, .events = IPC_SM_RUN_INIT | IPC_SM_RUN_RESET }, [IPC_SM_HALT_AUD] = { .id = IPC_SM_HALT_AUD, .enter = sm_halt_enter, .exit = sm_halt_aud_exit, .events = IPC_SM_RUN_RESET }, [IPC_SM_RESET_AUD] = { .id = IPC_SM_RESET_AUD, .enter = sm_reset_enter, .exit = sm_reset_aud_exit, .events = IPC_SM_RUN_RESET }, [IPC_SM_IDL_AUD] = { .id = IPC_SM_IDL_AUD, .enter = sm_idl_enter, .exit = sm_idl_aud_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_TX_REQ | IPC_SM_RUN_RESET }, [IPC_SM_SLW_TX_WR_DAT_AUD] = { .id = IPC_SM_SLW_TX_WR_DAT_AUD, .enter = sm_slw_tx_wr_dat_aud_enter, .exit = sm_slw_tx_wr_dat_aud_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO | IPC_SM_RUN_RESET }, [IPC_SM_ACT_TX_WR_DAT_AUD] = { .id = IPC_SM_ACT_TX_WR_DAT_AUD, .enter = sm_act_tx_wr_dat_enter, .exit = sm_act_tx_wr_dat_aud_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET }, [IPC_SM_SLW_RX_WR_DAT_AUD] = { .id = IPC_SM_SLW_RX_WR_DAT_AUD, .enter = sm_slw_rx_wr_dat_aud_enter, .exit = sm_slw_rx_wr_dat_aud_exit, .events = IPC_SM_RUN_SLAVE_IRQ | IPC_SM_RUN_COMMS_TMO | IPC_SM_RUN_RESET }, [IPC_SM_ACT_RX_WR_DAT_AUD] = { .id = IPC_SM_ACT_RX_WR_DAT_AUD, .enter = sm_act_rx_wr_dat_aud_enter, .exit = sm_act_rx_wr_dat_aud_exit, .events = IPC_SM_RUN_TFR_COMPLETE | IPC_SM_RUN_RESET } }; const struct ipc_sm_state *ipc_sm_idle_state(struct ipc_link_context *context) { if (context->link->id == IPC_LINK_AUDIO) return ipc_sm_state(IPC_SM_IDL_AUD); else return ipc_sm_state(IPC_SM_IDL); } const struct ipc_sm_state *ipc_sm_init_state(struct ipc_link_context *context) { if (context->link->id == IPC_LINK_AUDIO) return ipc_sm_state(IPC_SM_INIT_AUD); else return ipc_sm_state(IPC_SM_INIT); } const struct ipc_sm_state *ipc_sm_state(u8 id) { BUG_ON(id >= IPC_SM_STATE_ID_NBR); return &state_machine[id]; } bool ipc_sm_valid_for_state(u8 event, const struct ipc_sm_state *state) { return (state->events & event) == event; } static void state_machine_run(struct ipc_link_context *context, u8 event) { struct modem_m6718_spi_link_platform_data *link = context->link; struct spi_device *sdev = context->sdev; const struct ipc_sm_state *cur_state = context->state; /* some sanity checking */ if (context == NULL || link == NULL || cur_state == NULL) { pr_err("M6718 IPC protocol error: " "inconsistent driver state, ignoring event\n"); return; } dev_dbg(&sdev->dev, "link %d: RUNNING in %s (%s)\n", link->id, ipc_dbg_state_id(cur_state), ipc_dbg_event(event)); /* valid trigger event for current state? */ if (!ipc_sm_valid_for_state(event, cur_state)) { dev_dbg(&sdev->dev, "link %d: ignoring invalid event\n", link->id); ipc_dbg_ignoring_event(context, event); return; } ipc_dbg_handling_event(context, event); /* run machine while state entry functions trigger new changes */ do { if (event == IPC_SM_RUN_SLAVE_IRQ && !ipc_util_int_is_active(context)) { dev_err(&sdev->dev, "link %d error: slave is not ready! (%s)", link->id, ipc_dbg_state_id(cur_state)); } if (event == IPC_SM_RUN_ABORT) { dev_err(&sdev->dev, "link %d error: abort event\n", link->id); /* reset state to idle */ context->state = ipc_sm_idle_state(context); break; } else { /* exit current state */ dev_dbg(&sdev->dev, "link %d: exit %s (%s)\n", link->id, ipc_dbg_state_id(cur_state), ipc_dbg_event(event)); cur_state = cur_state->exit(event, context); context->state = cur_state; } /* reset state of slave irq to prepare for next event */ if (event == IPC_SM_RUN_SLAVE_IRQ) atomic_set(&context->state_int, 0); /* enter new state */ dev_dbg(&sdev->dev, "link %d: enter %s (%s)\n", link->id, ipc_dbg_state_id(cur_state), ipc_dbg_event(event)); event = context->state->enter(event, context); ipc_dbg_entering_state(context); } while (event != IPC_SM_RUN_NONE); dev_dbg(&sdev->dev, "link %d: STOPPED in %s\n", link->id, ipc_dbg_state_id(cur_state)); } void ipc_sm_kick(u8 event, struct ipc_link_context *context) { unsigned long flags; struct modem_m6718_spi_link_platform_data *link = context->link; struct spi_device *sdev = context->sdev; struct spi_message *msg = &context->spi_message; u8 i; spin_lock_irqsave(&context->sm_lock, flags); switch (event) { case IPC_SM_RUN_SLAVE_IRQ: dev_dbg(&sdev->dev, "link %d EVENT: slave-ready irq\n", link->id); del_timer(&context->comms_timer); atomic_set(&context->state_int, ipc_util_int_is_active(context)); break; case IPC_SM_RUN_TFR_COMPLETE: dev_dbg(&sdev->dev, "link %d EVENT: spi tfr complete (status %d len %d)\n", link->id, msg->status, msg->actual_length); ipc_dbg_dump_spi_tfr(context); break; case IPC_SM_RUN_COMMS_TMO: { char *statestr; struct ipc_link_context *contexts = l1_context.device_context; statestr = ipc_dbg_link_state_str(context); dev_err(&sdev->dev, "link %d EVENT: modem comms timeout (%s)!\n", link->id, ipc_dbg_state_id(context->state)); if (statestr != NULL) { dev_err(&sdev->dev, "%s", statestr); kfree(statestr); } /* cancel all link timeout timers except this one */ for (i = 0; i < IPC_NBR_SUPPORTED_SPI_LINKS; i++) if (contexts[i].link->id != link->id) del_timer(&contexts[i].comms_timer); break; } case IPC_SM_RUN_STABLE_TMO: dev_dbg(&sdev->dev, "link %d EVENT: slave-stable timeout\n", link->id); break; case IPC_SM_RUN_RESET: dev_dbg(&sdev->dev, "link %d EVENT: reset\n", link->id); del_timer(&context->comms_timer); break; default: break; } if (!ipc_util_link_is_suspended(context)) state_machine_run(context, event); else dev_dbg(&sdev->dev, "link %d is suspended, waiting for resume\n", link->id); spin_unlock_irqrestore(&context->sm_lock, flags); }
janrinze/snowballkernel
drivers/modem/m6718_spi/statemachine.c
C
gpl-2.0
40,413
/* ** tr2latex - troff to LaTeX converter ** $Id: setups.h,v 1.1.1.1 1992/04/27 15:20:56 teuben Exp $ ** COPYRIGHT (C) 1987 Kamal Al-Yahya, 1991,1992 Christian Engel ** ** Module: setups.h ** ** setup file */ #ifdef __TURBOC__ # ifndef __COMPACT__ # error "The COMPACT model is needed" # endif #endif #include <stdio.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <time.h> #if defined(__TURBOC__) | defined(MSC) # include <io.h> /* for type declarations */ #endif #ifdef UCB # include <strings.h> #else # include <string.h> #endif #ifdef VMS # define GOOD 1 #else # define GOOD 0 #endif #ifdef __TURBOC__ /*--- ONE MEGABYTE for EACH BUFFER? Really? - not for a brain-dead cpu like the 8086 or 80286. Would my account on the VAX let me have this much? Maybe, one day when we all have an 80386+, or a SPARC, or a real cpu.... ---*/ #define MAXLEN (0xfff0) /* maximum length of document */ /* A segment is 64k bytes! */ #else /* ... but no problem on virtual operating systems */ #define MAXLEN (1024*1024) /* maximum length of document */ #endif #define MAXWORD 250 /* maximum word length */ #define MAXLINE 500 /* maximum line length */ #define MAXDEF 200 /* maximum number of defines */ #define MAXARGS 128 /* maximal number of arguments */ #define EOS '\0' /* end of string */ #if defined(__TURBOC__) | defined (VAXC) # define index strchr #endif #ifdef MAIN /* can only declare globals once */ # define GLOBAL #else # define GLOBAL extern #endif GLOBAL int math_mode, /* math mode status */ de_arg, /* .de argument */ IP_stat, /* IP status */ QP_stat, /* QP status */ TP_stat; /* TP status */ #ifdef DEBUG GLOBAL int debug_o; GLOBAL int debug_v; #endif GLOBAL struct defs { char *def_macro; char *replace; int illegal; } def[MAXDEF]; GLOBAL struct mydefs { char *def_macro; char *replace; int illegal; int arg_no; int par; /* if it impiles (or contains) a par break */ } mydef[MAXDEF]; GLOBAL struct measure { char old_units[MAXWORD]; float old_value; char units[MAXWORD]; float value; char def_units[MAXWORD]; /* default units */ int def_value; /* default value: 0 means take last one */ } linespacing, indent, tmpind, space, vspace; typedef unsigned char bool; extern int errno;
jobovy/nemo
src/tools/tr2latex/setups.h
C
gpl-2.0
2,412
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script src="js/jquery.min.js"></script> <script type="text/javascript" src="js/js.cookie.js"></script> <title>BenchmarkTest00250</title> </head> <body> <form action="/benchmark/BenchmarkTest00250" method="POST" id="FormBenchmarkTest00250"> <div><label>Please explain your answer:</label></div> <br/> <div><textarea rows="4" cols="50" id="vectorArea" name="vectorArea" value=""></textarea></div> <div><label>Any additional note for the reviewer:</label></div> <div><input type="text" id="answer" name="answer"></input></div> <br/> <div><label>An AJAX request will be sent with a header named vector and value:</label> <input type="text" id="vector" name="vector" value="color" class="safe"></input></div> <div><input type="button" id="login-btn" value="Login" /></div> </form> <div id="ajax-form-msg1"><pre><code class="prettyprint" id="code"></code></pre></div> <script> $('.safe').keypress(function (e) { if (e.which == 13) { $('#login-btn').trigger('click'); return false; } }); $("#login-btn").click(function(){ var formData = $("#FormBenchmarkTest00250").serializeArray(); var URL = $("#FormBenchmarkTest00250").attr("action"); var text = $("#FormBenchmarkTest00250 input[id=vector]").val(); $.ajax({ beforeSend: function (request){ request.setRequestHeader($("#FormBenchmarkTest00250 input[id=vector]").val(), 'vector'); }, url : URL, type: "POST", data : formData, success: function(data, textStatus, jqXHR){ $("#code").text(data); }, error: function (jqXHR, textStatus, errorThrown){ console.error(errorThrown);} }); }); </script> </body> </html>
thc202/Benchmark
src/main/webapp/BenchmarkTest00250.html
HTML
gpl-2.0
1,881
#!/usr/bin/python #CHANGE ONLY, IF YOU KNOW, WHAT YOU DO! #OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID! import subprocess import argparse import time import calendar import string import sys class RegisterAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): print "Official Repository" # Name print "web" # Type (maybe web for web, or anything else for usb) print "http://www.gcw-zero.com/files/upload/opk/" #URL print "official.py --update" #Call for updating the list print "O" #letter to show class UpdateAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/gcw-repos/count.php',stdout=subprocess.PIPE,shell=True) process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://www.gcw-zero.com/downloads',stdout=subprocess.PIPE,shell=True) #process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/temp/test.htm',stdout=subprocess.PIPE,shell=True) #process = subprocess.Popen('cat downloads',stdout=subprocess.PIPE,shell=True) output = process.stdout.read().split('<div class="downloads_overview">') for output_part in output: part = output_part.split('\n') line_number = 0; not_found = 1; while (line_number < len(part)): if (part[line_number].strip().startswith('<span class="downloads_title">')): not_found = 0; break; line_number += 1; if not_found: continue; program_name_description = part[line_number]; name = program_name_description.split('>')[1].split('<')[0]; if (name == ""): continue line_number = 0; not_found = 1; while (line_number < len(part)): if (part[line_number].strip().startswith('<a class="downloads_link"')): not_found = 0; break; line_number += 1; if not_found: continue; filename = part[line_number].split('href="file.php?file=')[1].split('">')[0]; print "["+name+"]" description = program_name_description.split('>')[3]; print "description: "+description print "filename: " + filename l = len(part) found_version = 0 found_image = 0 found_long = 0; for i in range(0,l-1): if string.find(part[i],'Publication Date') != -1: version = part[i+1] version = version.split('>')[1] version = version.split('<')[0] t = time.strptime(version,"%A, %d %b %Y") print "version: " + str(calendar.timegm(t)) #NEEDED! found_version = 1 if string.find(part[i],'<div class="downloads_preview"') != -1: image = part[i]; image = image.split("background-image: url('")[1].split("');")[0]; print "image_url: http://www.gcw-zero.com/" + image if string.find(part[i],'<p class="more fade">') != -1: long_description = part[i]; long_description = long_description.split('<p class="more fade">')[1].split("</p>")[0]; long_description = long_description.replace('<br /> ','\\n') long_description = long_description.split('>') sys.stdout.write("long_description: ") for long_description_part in long_description: sys.stdout.write(long_description_part.split('<')[0]) sys.stdout.write('\n') found_long = 1 if (found_version and found_image and found_long): break print "" def main(): parser = argparse.ArgumentParser(description="Ziz's Repository script") parser.add_argument('--register', nargs=0, action=RegisterAction) parser.add_argument('--update', nargs=1, action=UpdateAction) args = parser.parse_args() if __name__ == "__main__": main()
theZiz/OPKManager
repositories/official.py
Python
gpl-2.0
3,617
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log: CMAny.hpp,v $ * Revision 1.2 2001/05/11 13:27:14 tng * Copyright update. * * Revision 1.1 2001/02/27 14:48:46 tng * Schema: Add CMAny and ContentLeafNameTypeVector, by Pei Yong Zhang * */ #if !defined(CMANY_HPP) #define CMANY_HPP #include <util/XercesDefs.hpp> #include <validators/common/CMNode.hpp> class CMStateSet; class CMAny : public CMNode { public : // ----------------------------------------------------------------------- // Constructors // ----------------------------------------------------------------------- CMAny ( const ContentSpecNode::NodeTypes type , const unsigned int URI , const unsigned int position ); ~CMAny(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- unsigned int getURI() const; unsigned int getPosition() const; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- void setPosition(const unsigned int newPosition); // ----------------------------------------------------------------------- // Implementation of the public CMNode virtual interface // ----------------------------------------------------------------------- bool isNullable() const; protected : // ----------------------------------------------------------------------- // Implementation of the protected CMNode virtual interface // ----------------------------------------------------------------------- void calcFirstPos(CMStateSet& toSet) const; void calcLastPos(CMStateSet& toSet) const; private : // ----------------------------------------------------------------------- // Private data members // // fURI; // URI of the any content model. This value is set if the type is // of the following: // XMLContentSpec.CONTENTSPECNODE_ANY, // XMLContentSpec.CONTENTSPECNODE_ANY_OTHER. // // fPosition // Part of the algorithm to convert a regex directly to a DFA // numbers each leaf sequentially. If its -1, that means its an // epsilon node. Zero and greater are non-epsilon positions. // ----------------------------------------------------------------------- unsigned int fURI; unsigned int fPosition; }; #endif
stippi/Clockwerk
include/xerces/validators/common/CMAny.hpp
C++
gpl-2.0
5,208
<?php // $Id: report.php,v 1.29 2008/11/30 21:33:58 skodak Exp $ if (!defined('MOODLE_INTERNAL')) { die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page } $courses = get_courses('all','c.shortname','c.id,c.shortname,c.fullname'); $courseoptions = array(); foreach ($courses as $c) { $context = get_context_instance(CONTEXT_COURSE, $c->id); if (has_capability('coursereport/stats:view', $context)) { $courseoptions[$c->id] = $c->shortname; } } $reportoptions = stats_get_report_options($course->id, $mode); $timeoptions = report_stats_timeoptions($mode); if (empty($timeoptions)) { print_error('nostatstodisplay', '', $CFG->wwwroot.'/course/view.php?id='.$course->id); } $table->width = 'auto'; if ($mode == STATS_MODE_DETAILED) { $param = stats_get_parameters($time,null,$course->id,$mode); // we only care about the table and the time string (if we have time) //TODO: lceanup this ugly mess $sql = 'SELECT DISTINCT s.userid, u.firstname, u.lastname, u.idnumber FROM {stats_user_'.$param->table.'} s JOIN {user} u ON u.id = s.userid WHERE courseid = '.$course->id . ((!empty($param->stattype)) ? ' AND stattype = \''.$param->stattype.'\'' : '') . ((!empty($time)) ? ' AND timeend >= '.$param->timeafter : '') .' ORDER BY u.lastname, u.firstname ASC'; if (!$us = $DB->get_records_sql($sql, $param->params)) { print_error('nousers'); } foreach ($us as $u) { $users[$u->userid] = fullname($u, true); } $table->align = array('left','left','left','left','left','left','left','left'); $table->data[] = array(get_string('course'),choose_from_menu($courseoptions,'course',$course->id,'','','',true), get_string('users'),choose_from_menu($users,'userid',$userid,'','','',true), get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true), get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true), '<input type="submit" value="'.get_string('view').'" />') ; } else if ($mode == STATS_MODE_RANKED) { $table->align = array('left','left','left','left','left','left'); $table->data[] = array(get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true), get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true), '<input type="submit" value="'.get_string('view').'" />') ; } else if ($mode == STATS_MODE_GENERAL) { $table->align = array('left','left','left','left','left','left','left'); $table->data[] = array(get_string('course'),choose_from_menu($courseoptions,'course',$course->id,'','','',true), get_string('statsreporttype'),choose_from_menu($reportoptions,'report',($report == 5) ? $report.$roleid : $report,'','','',true), get_string('statstimeperiod'),choose_from_menu($timeoptions,'time',$time,'','','',true), '<input type="submit" value="'.get_string('view').'" />') ; } echo '<form action="index.php" method="post">'."\n" .'<div>'."\n" .'<input type="hidden" name="mode" value="'.$mode.'" />'."\n"; print_table($table); echo '</div>'; echo '</form>'; if (!empty($report) && !empty($time)) { if ($report == STATS_REPORT_LOGINS && $course->id != SITEID) { print_error('reportnotavailable'); } $param = stats_get_parameters($time,$report,$course->id,$mode); if ($mode == STATS_MODE_DETAILED) { $param->table = 'user_'.$param->table; } if (!empty($param->sql)) { $sql = $param->sql; } else { //TODO: lceanup this ugly mess $sql = 'SELECT '.((empty($param->fieldscomplete)) ? 'id,roleid,timeend,' : '').$param->fields .' FROM {stats_'.$param->table.'} WHERE ' .(($course->id == SITEID) ? '' : ' courseid = '.$course->id.' AND ') .((!empty($userid)) ? ' userid = '.$userid.' AND ' : '') .((!empty($roleid)) ? ' roleid = '.$roleid.' AND ' : '') . ((!empty($param->stattype)) ? ' stattype = \''.$param->stattype.'\' AND ' : '') .' timeend >= '.$param->timeafter .' '.$param->extras .' ORDER BY timeend DESC'; } $stats = $DB->get_records_sql($sql, $params); if (empty($stats)) { notify(get_string('statsnodata')); } else { $stats = stats_fix_zeros($stats,$param->timeafter,$param->table,(!empty($param->line2))); print_heading(format_string($course->shortname).' - '.get_string('statsreport'.$report) .((!empty($user)) ? ' '.get_string('statsreportforuser').' ' .fullname($user,true) : '') .((!empty($roleid)) ? ' '.$DB->get_field('role','name', array('id'=>$roleid)) : '')); if (empty($CFG->gdversion)) { echo "(".get_string("gdneed").")"; } else { if ($mode == STATS_MODE_DETAILED) { echo '<div class="graph"><img src="'.$CFG->wwwroot.'/course/report/stats/graph.php?mode='.$mode.'&amp;course='.$course->id.'&amp;time='.$time.'&amp;report='.$report.'&amp;userid='.$userid.'" alt="'.get_string('statisticsgraph').'" /></div'; } else { echo '<div class="graph"><img src="'.$CFG->wwwroot.'/course/report/stats/graph.php?mode='.$mode.'&amp;course='.$course->id.'&amp;time='.$time.'&amp;report='.$report.'&amp;roleid='.$roleid.'" alt="'.get_string('statisticsgraph').'" /></div>'; } } $table = new StdClass; $table->align = array('left','center','center','center'); $param->table = str_replace('user_','',$param->table); switch ($param->table) { case 'daily' : $period = get_string('day'); break; case 'weekly' : $period = get_string('week'); break; case 'monthly': $period = get_string('month', 'form'); break; default : $period = ''; } $table->head = array(get_string('periodending','moodle',$period)); if (empty($param->crosstab)) { $table->head[] = $param->line1; if (!empty($param->line2)) { $table->head[] = $param->line2; } } if (empty($param->crosstab)) { foreach ($stats as $stat) { $a = array(userdate($stat->timeend-(60*60*24),get_string('strftimedate'),$CFG->timezone),$stat->line1); if (isset($stat->line2)) { $a[] = $stat->line2; } if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) { if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id))) { $a[] = '<a href="'.$CFG->wwwroot.'/course/report/log/index.php?id='. $course->id.'&amp;chooselog=1&amp;showusers=1&amp;showcourses=1&amp;user=' .$userid.'&amp;date='.usergetmidnight($stat->timeend-(60*60*24)).'">' .get_string('course').' ' .get_string('logs').'</a>&nbsp;'; } else { $a[] = ''; } } $table->data[] = $a; } } else { $data = array(); $roles = array(); $times = array(); $missedlines = array(); $rolenames = get_all_roles(); foreach ($rolenames as $r) { $rolenames[$r->id] = $r->name; } $rolenames = role_fix_names($rolenames, get_context_instance(CONTEXT_COURSE, $course->id)); foreach ($stats as $stat) { if (!empty($stat->zerofixed)) { $missedlines[] = $stat->timeend; } $data[$stat->timeend][$stat->roleid] = $stat->line1; if ($stat->roleid != 0) { if (!array_key_exists($stat->roleid,$roles)) { $roles[$stat->roleid] = $rolenames[$stat->roleid]; } } else { if (!array_key_exists($stat->roleid,$roles)) { $roles[$stat->roleid] = get_string('all'); } } if (!array_key_exists($stat->timeend,$times)) { $times[$stat->timeend] = userdate($stat->timeend,get_string('strftimedate'),$CFG->timezone); } } foreach ($data as $time => $rolesdata) { if (in_array($time,$missedlines)) { $rolesdata = array(); foreach ($roles as $roleid => $guff) { $rolesdata[$roleid] = 0; } } else { foreach (array_keys($roles) as $r) { if (!array_key_exists($r, $rolesdata)) { $rolesdata[$r] = 0; } } } krsort($rolesdata); $row = array_merge(array($times[$time]),$rolesdata); if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) { if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_COURSE, $course->id))) { $row[] = '<a href="'.$CFG->wwwroot.'/course/report/log/index.php?id=' .$course->id.'&amp;chooselog=1&amp;showusers=1&amp;showcourses=1&amp;user='.$userid .'&amp;date='.usergetmidnight($time-(60*60*24)).'">' .get_string('course').' ' .get_string('logs').'</a>&nbsp;'; } else { $row[] = ''; } } $table->data[] = $row; } krsort($roles); $table->head = array_merge($table->head,$roles); } $table->head[] = get_string('logs'); if (!empty($lastrecord)) { $lastrecord[] = $lastlink; $table->data[] = $lastrecord; } print_table($table); } } ?>
nicolasconnault/moodle2.0
course/report/stats/report.php
PHP
gpl-2.0
11,351
module Actions module Pulp3 module Repository class CreatePublication < Pulp3::AbstractAsyncTask middleware.use Actions::Middleware::ExecuteIfContentsChanged def plan(repository, smart_proxy, options) sequence do action = plan_self(:repository_id => repository.id, :smart_proxy_id => smart_proxy.id, :contents_changed => options[:contents_changed], :options => options) plan_action(SavePublication, repository, action.output, :contents_changed => options[:contents_changed]) end end def invoke_external_task repository = ::Katello::Repository.find(input[:repository_id]) smart_proxy = ::SmartProxy.find(input[:smart_proxy_id]) if repository.publication_href.nil? || input[:options][:force] output[:response] = repository.backend_service(smart_proxy).create_publication else [] end end end end end end
ares/katello
app/lib/actions/pulp3/repository/create_publication.rb
Ruby
gpl-2.0
984
'use strict'; app.controller('orderController', ['$scope', '$rootScope', 'toastrService', 'orderService', function ($scope, $rootScope, toastrService, orderService) { $scope.paging = 1; $scope.disabledMore = false; $scope.data = []; $scope.getOrders = function () { orderService.get($scope.paging).then(function (data) { if (data.length > 0) { $scope.data.push.apply($scope.data, data); } else { $scope.disabledMore = true; } }); } $scope.more = function () { $scope.paging++; $scope.getOrders(); }; $scope.refresh = function () { $scope.paging = 1; $scope.data = []; $scope.getOrders(); }; $scope.getOrders(); $scope.openOrder = function (item, $index) { $scope.order = item; $scope.order.$index = $index; $('#modal-order').modal({ backdrop: true }); }; } ]);
ozalvarez/elcubo9
elcubo9.admin/app/controllers/orderController.js
JavaScript
gpl-2.0
1,103
obj-$(CONFIG_ICDTCP3_ITD) += itddrv.o obj-$(CONFIG_ICDTCP3_LCD) += hd44780drv.o obj-$(CONFIG_ICDTCP3) += icdcommon.o
insofter/linux
drivers/icdtcp3/Makefile
Makefile
gpl-2.0
120
#!/usr/bin/env python #################################### # # --- TEXTPATGEN TEMPLATE --- # # Users can change the output by editing # this file directly. # #################################### import sys sys.stdout.write('####################################\n') sys.stdout.write('#\n') sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n') sys.stdout.write('#\n') sys.stdout.write('# -- Created from a Python script.\n') sys.stdout.write('#\n') sys.stdout.write("####################################\n") num=0 for length in range(0, 16): for width in range(0, 15): sys.stdout.write('X-%04X ' % num) num=num+1 width=width+1 length=length+1 sys.stdout.write('X-%04X\n' % num) num=num+1 sys.stdout.write('# -- End of file.\n'); sys.stdout.flush()
kevinleake01/textpatgen
12-workspace-py/tpl-py-0001.py
Python
gpl-2.0
774
<!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <title><?php /* * Print the <title> tag based on what is being viewed. */ global $page, $paged; wp_title( '|', true, 'right' ); // Add the blog name. bloginfo( 'name' ); // Add the blog description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) echo " | $site_description"; // Add a page number if necessary: if ( $paged >= 2 || $page >= 2 ) echo ' | ' . sprintf( __( 'Page %s', 'twentyten' ), max( $paged, $page ) ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_url'); ?>/css/skin.css" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <?php /* We add some JavaScript to pages with the comment form * to support sites with threaded comments (when in use). */ if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); /* Always have wp_head() just before the closing </head> * tag of your theme, or you will break many plugins, which * generally use this hook to add elements to <head> such * as styles, scripts, and meta tags. */ wp_head(); ?> <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascript/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/javascript/jquery.jcarousel.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('#mycarousel').jcarousel({ scroll:3, auto:5, wrap:"both" }); }); </script> </head> <a name="menu"></a> <body <?php body_class(); ?>> <div class="centralizarCorpo content"> <div class="header"> <div class='img_header_detalhe img_header_detalhe_size'> <div class="img_header_logo_jzconsultoria img_header_logo_jzconsultoria_size"></div> <div class="img_header_consultoria_treinamento img_header_consultoria_treinamento_size"></div> </div> <div class="img_header_menu img_header_menu_size"></div> <div class="img_header_line img_header_line_size"></div> <div class="menu"> <a class="bt_empresa" href="#empresa"><div class="img_header_bt1 img_header_bt1_size"></div></a> <a class="bt_consultoria" href="#consultoria"><div class="img_header_bt2 img_header_bt2_size"></div></a> <a class="bt_treinamentos" href="#treinamento"><div class="img_header_bt3 img_header_bt3_size"></div></a> <a class="bt_clientes" href="#clientes"><div class="img_header_bt4 img_header_bt4_size"></div></a> <a class="bt_contato" href="#contato"><div class="img_header_bt5 img_header_bt5_size"></div></a> </div> </div>
fearzendron/jzconsultoria
wp-content/themes/jzconsultoria/header-home.php
PHP
gpl-2.0
2,963
from .. import config from .. import fixtures from ..assertions import eq_ from ..assertions import in_ from ..schema import Column from ..schema import Table from ... import bindparam from ... import case from ... import Computed from ... import exists from ... import false from ... import func from ... import Integer from ... import literal from ... import literal_column from ... import null from ... import select from ... import String from ... import testing from ... import text from ... import true from ... import tuple_ from ... import union from ... import util class CollateTest(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("data", String(100)), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "data": "collate data1"}, {"id": 2, "data": "collate data2"}, ], ) def _assert_result(self, select, result): eq_(config.db.execute(select).fetchall(), result) @testing.requires.order_by_collation def test_collate_order_by(self): collation = testing.requires.get_order_by_collation(testing.config) self._assert_result( select([self.tables.some_table]).order_by( self.tables.some_table.c.data.collate(collation).asc() ), [(1, "collate data1"), (2, "collate data2")], ) class OrderByLabelTest(fixtures.TablesTest): """Test the dialect sends appropriate ORDER BY expressions when labels are used. This essentially exercises the "supports_simple_order_by_label" setting. """ __backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), Column("q", String(50)), Column("p", String(50)), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2, "q": "q1", "p": "p3"}, {"id": 2, "x": 2, "y": 3, "q": "q2", "p": "p2"}, {"id": 3, "x": 3, "y": 4, "q": "q3", "p": "p1"}, ], ) def _assert_result(self, select, result): eq_(config.db.execute(select).fetchall(), result) def test_plain(self): table = self.tables.some_table lx = table.c.x.label("lx") self._assert_result(select([lx]).order_by(lx), [(1,), (2,), (3,)]) def test_composed_int(self): table = self.tables.some_table lx = (table.c.x + table.c.y).label("lx") self._assert_result(select([lx]).order_by(lx), [(3,), (5,), (7,)]) def test_composed_multiple(self): table = self.tables.some_table lx = (table.c.x + table.c.y).label("lx") ly = (func.lower(table.c.q) + table.c.p).label("ly") self._assert_result( select([lx, ly]).order_by(lx, ly.desc()), [(3, util.u("q1p3")), (5, util.u("q2p2")), (7, util.u("q3p1"))], ) def test_plain_desc(self): table = self.tables.some_table lx = table.c.x.label("lx") self._assert_result( select([lx]).order_by(lx.desc()), [(3,), (2,), (1,)] ) def test_composed_int_desc(self): table = self.tables.some_table lx = (table.c.x + table.c.y).label("lx") self._assert_result( select([lx]).order_by(lx.desc()), [(7,), (5,), (3,)] ) @testing.requires.group_by_complex_expression def test_group_by_composed(self): table = self.tables.some_table expr = (table.c.x + table.c.y).label("lx") stmt = ( select([func.count(table.c.id), expr]) .group_by(expr) .order_by(expr) ) self._assert_result(stmt, [(1, 3), (1, 5), (1, 7)]) class LimitOffsetTest(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2}, {"id": 2, "x": 2, "y": 3}, {"id": 3, "x": 3, "y": 4}, {"id": 4, "x": 4, "y": 5}, ], ) def _assert_result(self, select, result, params=()): eq_(config.db.execute(select, params).fetchall(), result) def test_simple_limit(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).limit(2), [(1, 1, 2), (2, 2, 3)], ) @testing.requires.offset def test_simple_offset(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).offset(2), [(3, 3, 4), (4, 4, 5)], ) @testing.requires.offset def test_simple_limit_offset(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).limit(2).offset(1), [(2, 2, 3), (3, 3, 4)], ) @testing.requires.offset def test_limit_offset_nobinds(self): """test that 'literal binds' mode works - no bound params.""" table = self.tables.some_table stmt = select([table]).order_by(table.c.id).limit(2).offset(1) sql = stmt.compile( dialect=config.db.dialect, compile_kwargs={"literal_binds": True} ) sql = str(sql) self._assert_result(sql, [(2, 2, 3), (3, 3, 4)]) @testing.requires.bound_limit_offset def test_bound_limit(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).limit(bindparam("l")), [(1, 1, 2), (2, 2, 3)], params={"l": 2}, ) @testing.requires.bound_limit_offset def test_bound_offset(self): table = self.tables.some_table self._assert_result( select([table]).order_by(table.c.id).offset(bindparam("o")), [(3, 3, 4), (4, 4, 5)], params={"o": 2}, ) @testing.requires.bound_limit_offset def test_bound_limit_offset(self): table = self.tables.some_table self._assert_result( select([table]) .order_by(table.c.id) .limit(bindparam("l")) .offset(bindparam("o")), [(2, 2, 3), (3, 3, 4)], params={"l": 2, "o": 1}, ) class CompoundSelectTest(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2}, {"id": 2, "x": 2, "y": 3}, {"id": 3, "x": 3, "y": 4}, {"id": 4, "x": 4, "y": 5}, ], ) def _assert_result(self, select, result, params=()): eq_(config.db.execute(select, params).fetchall(), result) def test_plain_union(self): table = self.tables.some_table s1 = select([table]).where(table.c.id == 2) s2 = select([table]).where(table.c.id == 3) u1 = union(s1, s2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]) def test_select_from_plain_union(self): table = self.tables.some_table s1 = select([table]).where(table.c.id == 2) s2 = select([table]).where(table.c.id == 3) u1 = union(s1, s2).alias().select() self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]) @testing.requires.order_by_col_from_union @testing.requires.parens_in_union_contained_select_w_limit_offset def test_limit_offset_selectable_in_unions(self): table = self.tables.some_table s1 = ( select([table]) .where(table.c.id == 2) .limit(1) .order_by(table.c.id) ) s2 = ( select([table]) .where(table.c.id == 3) .limit(1) .order_by(table.c.id) ) u1 = union(s1, s2).limit(2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]) @testing.requires.parens_in_union_contained_select_wo_limit_offset def test_order_by_selectable_in_unions(self): table = self.tables.some_table s1 = select([table]).where(table.c.id == 2).order_by(table.c.id) s2 = select([table]).where(table.c.id == 3).order_by(table.c.id) u1 = union(s1, s2).limit(2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]) def test_distinct_selectable_in_unions(self): table = self.tables.some_table s1 = select([table]).where(table.c.id == 2).distinct() s2 = select([table]).where(table.c.id == 3).distinct() u1 = union(s1, s2).limit(2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]) @testing.requires.parens_in_union_contained_select_w_limit_offset def test_limit_offset_in_unions_from_alias(self): table = self.tables.some_table s1 = ( select([table]) .where(table.c.id == 2) .limit(1) .order_by(table.c.id) ) s2 = ( select([table]) .where(table.c.id == 3) .limit(1) .order_by(table.c.id) ) # this necessarily has double parens u1 = union(s1, s2).alias() self._assert_result( u1.select().limit(2).order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)] ) def test_limit_offset_aliased_selectable_in_unions(self): table = self.tables.some_table s1 = ( select([table]) .where(table.c.id == 2) .limit(1) .order_by(table.c.id) .alias() .select() ) s2 = ( select([table]) .where(table.c.id == 3) .limit(1) .order_by(table.c.id) .alias() .select() ) u1 = union(s1, s2).limit(2) self._assert_result(u1.order_by(u1.c.id), [(2, 2, 3), (3, 3, 4)]) class ExpandingBoundInTest(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), Column("z", String(50)), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "x": 1, "y": 2, "z": "z1"}, {"id": 2, "x": 2, "y": 3, "z": "z2"}, {"id": 3, "x": 3, "y": 4, "z": "z3"}, {"id": 4, "x": 4, "y": 5, "z": "z4"}, ], ) def _assert_result(self, select, result, params=()): eq_(config.db.execute(select, params).fetchall(), result) def test_multiple_empty_sets(self): # test that any anonymous aliasing used by the dialect # is fine with duplicates table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.x.in_(bindparam("q", expanding=True))) .where(table.c.y.in_(bindparam("p", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [], params={"q": [], "p": []}) @testing.requires.tuple_in def test_empty_heterogeneous_tuples(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where( tuple_(table.c.x, table.c.z).in_( bindparam("q", expanding=True) ) ) .order_by(table.c.id) ) self._assert_result(stmt, [], params={"q": []}) @testing.requires.tuple_in def test_empty_homogeneous_tuples(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where( tuple_(table.c.x, table.c.y).in_( bindparam("q", expanding=True) ) ) .order_by(table.c.id) ) self._assert_result(stmt, [], params={"q": []}) def test_bound_in_scalar(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.x.in_(bindparam("q", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [(2,), (3,), (4,)], params={"q": [2, 3, 4]}) @testing.requires.tuple_in def test_bound_in_two_tuple(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where( tuple_(table.c.x, table.c.y).in_( bindparam("q", expanding=True) ) ) .order_by(table.c.id) ) self._assert_result( stmt, [(2,), (3,), (4,)], params={"q": [(2, 3), (3, 4), (4, 5)]} ) @testing.requires.tuple_in def test_bound_in_heterogeneous_two_tuple(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where( tuple_(table.c.x, table.c.z).in_( bindparam("q", expanding=True) ) ) .order_by(table.c.id) ) self._assert_result( stmt, [(2,), (3,), (4,)], params={"q": [(2, "z2"), (3, "z3"), (4, "z4")]}, ) def test_empty_set_against_integer(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.x.in_(bindparam("q", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [], params={"q": []}) def test_empty_set_against_integer_negation(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.x.notin_(bindparam("q", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []}) def test_empty_set_against_string(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.z.in_(bindparam("q", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [], params={"q": []}) def test_empty_set_against_string_negation(self): table = self.tables.some_table stmt = ( select([table.c.id]) .where(table.c.z.notin_(bindparam("q", expanding=True))) .order_by(table.c.id) ) self._assert_result(stmt, [(1,), (2,), (3,), (4,)], params={"q": []}) def test_null_in_empty_set_is_false(self): stmt = select( [ case( [ ( null().in_( bindparam("foo", value=(), expanding=True) ), true(), ) ], else_=false(), ) ] ) in_(config.db.execute(stmt).fetchone()[0], (False, 0)) class LikeFunctionsTest(fixtures.TablesTest): __backend__ = True run_inserts = "once" run_deletes = None @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("data", String(50)), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "data": "abcdefg"}, {"id": 2, "data": "ab/cdefg"}, {"id": 3, "data": "ab%cdefg"}, {"id": 4, "data": "ab_cdefg"}, {"id": 5, "data": "abcde/fg"}, {"id": 6, "data": "abcde%fg"}, {"id": 7, "data": "ab#cdefg"}, {"id": 8, "data": "ab9cdefg"}, {"id": 9, "data": "abcde#fg"}, {"id": 10, "data": "abcd9fg"}, ], ) def _test(self, expr, expected): some_table = self.tables.some_table with config.db.connect() as conn: rows = { value for value, in conn.execute( select([some_table.c.id]).where(expr) ) } eq_(rows, expected) def test_startswith_unescaped(self): col = self.tables.some_table.c.data self._test(col.startswith("ab%c"), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) def test_startswith_autoescape(self): col = self.tables.some_table.c.data self._test(col.startswith("ab%c", autoescape=True), {3}) def test_startswith_sqlexpr(self): col = self.tables.some_table.c.data self._test( col.startswith(literal_column("'ab%c'")), {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, ) def test_startswith_escape(self): col = self.tables.some_table.c.data self._test(col.startswith("ab##c", escape="#"), {7}) def test_startswith_autoescape_escape(self): col = self.tables.some_table.c.data self._test(col.startswith("ab%c", autoescape=True, escape="#"), {3}) self._test(col.startswith("ab#c", autoescape=True, escape="#"), {7}) def test_endswith_unescaped(self): col = self.tables.some_table.c.data self._test(col.endswith("e%fg"), {1, 2, 3, 4, 5, 6, 7, 8, 9}) def test_endswith_sqlexpr(self): col = self.tables.some_table.c.data self._test( col.endswith(literal_column("'e%fg'")), {1, 2, 3, 4, 5, 6, 7, 8, 9} ) def test_endswith_autoescape(self): col = self.tables.some_table.c.data self._test(col.endswith("e%fg", autoescape=True), {6}) def test_endswith_escape(self): col = self.tables.some_table.c.data self._test(col.endswith("e##fg", escape="#"), {9}) def test_endswith_autoescape_escape(self): col = self.tables.some_table.c.data self._test(col.endswith("e%fg", autoescape=True, escape="#"), {6}) self._test(col.endswith("e#fg", autoescape=True, escape="#"), {9}) def test_contains_unescaped(self): col = self.tables.some_table.c.data self._test(col.contains("b%cde"), {1, 2, 3, 4, 5, 6, 7, 8, 9}) def test_contains_autoescape(self): col = self.tables.some_table.c.data self._test(col.contains("b%cde", autoescape=True), {3}) def test_contains_escape(self): col = self.tables.some_table.c.data self._test(col.contains("b##cde", escape="#"), {7}) def test_contains_autoescape_escape(self): col = self.tables.some_table.c.data self._test(col.contains("b%cd", autoescape=True, escape="#"), {3}) self._test(col.contains("b#cd", autoescape=True, escape="#"), {7}) class ComputedColumnTest(fixtures.TablesTest): __backend__ = True __requires__ = ("computed_columns",) @classmethod def define_tables(cls, metadata): Table( "square", metadata, Column("id", Integer, primary_key=True), Column("side", Integer), Column("area", Integer, Computed("side * side")), Column("perimeter", Integer, Computed("4 * side")), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.square.insert(), [{"id": 1, "side": 10}, {"id": 10, "side": 42}], ) def test_select_all(self): with config.db.connect() as conn: res = conn.execute( select([text("*")]) .select_from(self.tables.square) .order_by(self.tables.square.c.id) ).fetchall() eq_(res, [(1, 10, 100, 40), (10, 42, 1764, 168)]) def test_select_columns(self): with config.db.connect() as conn: res = conn.execute( select( [self.tables.square.c.area, self.tables.square.c.perimeter] ) .select_from(self.tables.square) .order_by(self.tables.square.c.id) ).fetchall() eq_(res, [(100, 40), (1764, 168)]) class ExistsTest(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "stuff", metadata, Column("id", Integer, primary_key=True), Column("data", String(50)), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.stuff.insert(), [ {"id": 1, "data": "some data"}, {"id": 2, "data": "some data"}, {"id": 3, "data": "some data"}, {"id": 4, "data": "some other data"}, ], ) def test_select_exists(self, connection): stuff = self.tables.stuff eq_( connection.execute( select([literal(1)]).where( exists().where(stuff.c.data == "some data") ) ).fetchall(), [(1,)], ) def test_select_exists_false(self, connection): stuff = self.tables.stuff eq_( connection.execute( select([literal(1)]).where( exists().where(stuff.c.data == "no data") ) ).fetchall(), [], ) class IsOrIsNotDistinctFromTest(fixtures.TablesTest): __backend__ = True __requires__ = ("supports_is_distinct_from",) @classmethod def define_tables(cls, metadata): Table( "is_distinct_test", metadata, Column("id", Integer, primary_key=True), Column("col_a", Integer, nullable=True), Column("col_b", Integer, nullable=True), ) @testing.combinations( ("both_int_different", 0, 1, 1), ("both_int_same", 1, 1, 0), ("one_null_first", None, 1, 1), ("one_null_second", 0, None, 1), ("both_null", None, None, 0), id_="iaaa", argnames="col_a_value, col_b_value, expected_row_count_for_is", ) def test_is_or_isnot_distinct_from( self, col_a_value, col_b_value, expected_row_count_for_is, connection ): tbl = self.tables.is_distinct_test connection.execute( tbl.insert(), [{"id": 1, "col_a": col_a_value, "col_b": col_b_value}], ) result = connection.execute( tbl.select(tbl.c.col_a.is_distinct_from(tbl.c.col_b)) ).fetchall() eq_( len(result), expected_row_count_for_is, ) expected_row_count_for_isnot = ( 1 if expected_row_count_for_is == 0 else 0 ) result = connection.execute( tbl.select(tbl.c.col_a.isnot_distinct_from(tbl.c.col_b)) ).fetchall() eq_( len(result), expected_row_count_for_isnot, )
gltn/stdm
stdm/third_party/sqlalchemy/testing/suite/test_select.py
Python
gpl-2.0
24,377
// ********************************************************************** // // Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** #ifndef ICE_INTERFACE_BY_VALUE_H #define ICE_INTERFACE_BY_VALUE_H #include <Ice/Value.h> #include <Ice/OutputStream.h> #include <Ice/InputStream.h> #ifdef ICE_CPP11_MAPPING namespace Ice { template<typename T> class InterfaceByValue : public ValueHelper<InterfaceByValue<T>, Value> { public: virtual std::string ice_id() const { return T::ice_staticId(); } static const std::string& ice_staticId() { return T::ice_staticId(); } std::tuple<> ice_tuple() const { return std::tie(); } }; } #endif #endif
ljx0305/ice
cpp/include/Ice/InterfaceByValue.h
C
gpl-2.0
911
<?lsmb FILTER latex -?> \documentclass{scrartcl} \usepackage{xltxtra} \setmainfont{Verdana} \usepackage{tabularx} \usepackage[letterpaper,top=2cm,bottom=1.5cm,left=1.1cm,right=1.5cm]{geometry} \usepackage{graphicx} \setlength{\parindent}{0pt} \begin{document} \pagestyle{myheadings} \thispagestyle{empty} <?lsmb INCLUDE letterhead.tex ?> \centerline{\MakeUppercase{\textbf{<?lsmb text('AP Transaction') ?>}}} \vspace*{0.5cm} \parbox[t]{.5\textwidth}{ <?lsmb name ?> <?lsmb address1 ?> <?lsmb address2 ?> <?lsmb city ?> <?lsmb IF state ?> \hspace{-0.1cm}, <?lsmb state ?> <?lsmb END ?> <?lsmb zipcode ?> <?lsmb country ?> \vspace{0.3cm} <?lsmb IF contact ?> <?lsmb contact ?> \vspace{0.2cm} <?lsmb END ?> <?lsmb IF vendorphone ?> Tel: <?lsmb vendorphone ?> <?lsmb END ?> <?lsmb IF vendorfax ?> Fax: <?lsmb vendorfax ?> <?lsmb END ?> <?lsmb email ?> <?lsmb IF vendortaxnumber ?> Tax Number: <?lsmb vendortaxnumber ?> <?lsmb END ?> } \hfill \begin{tabular}[t]{ll} \textbf{<?lsmb text('Invoice #') ?>} & <?lsmb invnumber ?> \\ \textbf{<?lsmb text('Date') ?>} & <?lsmb invdate ?> \\ \textbf{<?lsmb text('Due') ?>} & <?lsmb duedate ?> \\ <?lsmb IF ponumber ?> \textbf{<?lsmb text('PO #') ?>} & <?lsmb ponumber ?> \\ <?lsmb END ?> <?lsmb IF ordnumber ?> \textbf{<?lsmb text('Order #') ?>} & <?lsmb ordnumber ?> \\ <?lsmb END ?> \textbf{<?lsmb text('Employee') ?>} & <?lsmb employee ?> \\ \end{tabular} \vspace{1cm} \begin{tabularx}{\textwidth}[t]{@{}llrX@{\hspace{1cm}}l@{}} <?lsmb FOREACH amount ?> <?lsmb lc = loop.count - 1 ?> <?lsmb accno.${lc} ?> & <?lsmb account.${lc} ?> & <?lsmb amount.${lc} ?> & <?lsmb description.${lc} ?> & <?lsmb projectnumber.${lc} ?> \\ <?lsmb END ?> \multicolumn{2}{r}{\textbf{Subtotal}} & <?lsmb subtotal ?> & \\ <?lsmb FOREACH tax ?> <?lsmb lc = loop.count - 1 ?> \multicolumn{2}{r}{\textbf{<?lsmb taxdescription.${lc} ?> @ <?lsmb taxrate.${lc} ?> \%}} & <?lsmb tax.${lc} ?> & \\ <?lsmb END ?> \multicolumn{2}{r}{\textbf{Total}} & <?lsmb invtotal ?> & \\ \end{tabularx} \vspace{0.3cm} <?lsmb text_amount ?> ***** <?lsmb decimal ?>/100 <?lsmb currency ?> <?lsmb IF notes ?> \vspace{0.3cm} <?lsmb FOREACH P IN notes.split('\n\n') ?> <?lsmb P ?>\medskip <?lsmb END ?> <?lsmb END ?> \vspace{0.3cm} <?lsmb IF paid_1 ?> \begin{tabular}{@{}llllr@{}} \multicolumn{5}{c}{\textbf{<?lsmb text('Payments') ?>}} \\ \hline \textbf{<?lsmb text('Date') ?>} & & \textbf{<?lsmb text('Source') ?>} & \textbf{<?lsmb text('Memo') ?>} & \textbf{<?lsmb text('Amount') ?>} \\ <?lsmb END ?> <?lsmb FOREACH payment ?> <?lsmb lc = loop.count - 1 ?> <?lsmb paymentdate.${lc} ?> & <?lsmb paymentaccount.${lc} ?> & <?lsmb paymentsource.${lc} ?> & <?lsmb paymentmemo.${lc} ?> & <?lsmb payment.${lc} ?> \\ <?lsmb END ?> <?lsmb IF paid_1 ?> \end{tabular} <?lsmb END ?> \end{document} <?lsmb END ?>
yec/ledgersmb
templates/xedemo/ap_transaction.tex
TeX
gpl-2.0
2,872
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC ([email protected]) * @Copyright (C) 2014 VINADES.,JSC. All rights reserved * @License GNU/GPL version 2 or any later version * @Createdate 9/9/2010, 6:38 */ if (! defined('NV_IS_FILE_WEBTOOLS')) { die('Stop!!!'); } $contents = 'Error Access!!!'; $checksess = $nv_Request->get_title('checksess', 'get', ''); if ($checksess == md5($global_config['sitekey'] . session_id()) and file_exists(NV_ROOTDIR . '/install/update_data.php')) { $contents = ''; $list_file_docs = nv_scandir(NV_ROOTDIR . '/install', '/^update_docs_([a-z]{2})\.html$/'); // Xoa cac file docs foreach ($list_file_docs as $docsfile) { $check_del = nv_deletefile(NV_ROOTDIR . '/install/' . $docsfile); if ($check_del[0] == 0) { $contents .= $check_del[1] . ' ' . $lang_module['update_manual_delete']; } } // Xoa file du lieu nang cap $check_delete_file = nv_deletefile(NV_ROOTDIR . '/install/update_data.php'); if ($check_delete_file[0] == 0) { $contents .= $check_delete_file[1] . ' ' . $lang_module['update_manual_delete']; } // Xoa thu muc file thay doi if (file_exists(NV_ROOTDIR . '/install/update')) { $check_delete_dir = nv_deletefile(NV_ROOTDIR . '/install/update', true); if ($check_delete_dir[0] == 0) { $contents .= $check_delete_dir[1] . ' ' . $lang_module['update_manual_delete']; } } // Xoa file log $list_file_logs = nv_scandir(NV_ROOTDIR . '/' . NV_DATADIR, '/^config_update_NVUD([A-Z0-9]+)\.php$/'); foreach ($list_file_logs as $logsfile) { $check_del = nv_deletefile(NV_ROOTDIR . '/' . NV_DATADIR . '/' . $logsfile); if ($check_del[0] == 0) { $contents .= $check_del[1] . ' ' . $lang_module['update_manual_delete']; } } clearstatcache(); } if ($contents == '') { $contents = 'OK'; } include NV_ROOTDIR . '/includes/header.php'; echo $contents; include NV_ROOTDIR . '/includes/footer.php';
nukeplus/nuke
admin/webtools/deleteupdate.php
PHP
gpl-2.0
2,041
/* Theme Name: Hughes Benefits Site Theme URI: http://coverwaco.com Description: A custom WordPress theme for Hughes Benefits. Author: Heath Hughes Author URI: http://heathwhughes.com Version: 1.0 Tags: responsive, insurance, simple License: GNU General Public License v2.0 License URI: http://www.gnu.org/licenses/gpl-2.0.html */ @import url(http://fonts.googleapis.com/css?family=Quicksand:400,700|Paytone+One|Montserrat+Alternates:400,700|Josefin+Sans:400,600,700,400italic|Wendy+One|Fredoka+One|Raleway:400,600,500,700|Righteous|Passion+One:700,400,900|Comfortaa:700,400|Open+Sans:700,400); /* VARIABLES */ /* navy */ /* bright light blue #7ECEFD */ /* muted blue (darker) */ /* light muted blue */ /* orange #D57E01 #ED8C01 */ /* muted yellow */ /* light orange */ /* white - the background-color for the header, body, and footer */ /* grey - the main text on the site */ /* */ /* super light blue */ /* FONT */ /******************************** GENERAL ********************************/ html { height: 100%; font-size: 1.2em; } html, body, button, input, select, textarea { font-family: "Josefin Sans", san-seriff; } body { height: 100%; background-color: #fff; color: #7A7A7A; } a { text-decoration: none; color: #71B9E4; } div#wrapper, div#header-wrapper { max-width: 1200px; margin: 0 auto; padding: 0 5%; height: 100%; } h2 { color: #346098; margin: .75em 0; font-size: 2em; } h3 { color: #71B9E4; margin: .5em 0; font-size: 1.4em; } h4 { font-size: 1.2em; margin: .75em 0; } p { margin: .35em 0; } ul { margin: .5em 0; } img { width: 100%; } /******************************** HEADING ********************************/ header { float: left; margin: 0 0 1.6em 0; padding: 5px 0 0 0; width: 100%; background-color: #346098; } #logo { text-align: center; margin: 0; } h1 { font-family: "Josefin Sans", san-seriff; margin: 15px 0; font-size: 2.2em; font-weight: bold; line-height: 0.8em; } h1 .logo-1 { color: #FFA347; } h1 .logo-2 { color: #F5C149; } h1 .logo-3 { color: #ACACAC; font-size: .75em; /* for the ".com" */ } p#slogan { color: #ACACAC; font-style: italic; position: relative; top: -15px; left: 5px; margin: 0; } /********************************* NAVIGATION ********************************/ nav { text-align: center; padding: 10px 0 0 0; margin: 0; /* end ul */ /* end li */ /* end a */ } nav ul { list-style: none; margin: 0 10px; padding: 0; } nav li { display: inline-block; margin-bottom: 10px; } nav li.current_page_item { border-bottom: 3px solid #F5C149; } nav a { font-size: 1em; font-weight: 600; padding: 0 10px; font-family: "Josefin Sans", san-seriff; text-transform: uppercase; } nav a:hover { border-bottom: 3px solid #F5C149; } /* end nav */ /******************************** FOOTER ********************************/ footer { font-size: 0.75em; text-align: center; clear: both; padding-top: 50px; color: #7A7A7A; margin-bottom: 30px; } footer hr { position: relative; top: 25px; } footer p { line-height: 50px; /* this should match the max-height of the image */ border-top: solid #7A7A7A 1.9px; } footer img { max-height: 50px; position: relative; top: 30px; padding: 5px; width: auto; } /******************************* PAGE: HOME ********************************/ #home-2 h3, #home-3 h3 { margin-top: 0; } h2.cta { margin: 0 0 .75em 0; } section#home-1 { clear: left; position: relative; top: -1.6em; } /* section#home-2 { margin-top: 56px;; }*/ img#home-img { width: 100%; height: 250px; display: none; /* this default will be overridden when the screen get's wider than 480px */ } section#home-4:after { content: ""; visibility: hidden; display: block; height: 0; clear: both; } section#home-4 { margin-bottom: 1em; } section#home-4 div { margin: 12px; } section#home-4 div span { margin-left: 5em; } .btn, .button-orange { -moz-box-shadow: inset 0px 1px 0px 0px #fce2c1; -webkit-box-shadow: inset 0px 1px 0px 0px #fce2c1; box-shadow: inset 0px 1px 0px 0px #fce2c1; background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffc477), color-stop(1, #FFA347)); background: -moz-linear-gradient(center top, #ffc477 5%, #ffa347 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffc477', endColorstr='#ffa347'); background-color: #ffc477; -webkit-border-top-left-radius: 13px; -moz-border-radius-topleft: 13px; border-top-left-radius: 13px; -webkit-border-top-right-radius: 13px; -moz-border-radius-topright: 13px; border-top-right-radius: 13px; -webkit-border-bottom-right-radius: 13px; -moz-border-radius-bottomright: 13px; border-bottom-right-radius: 13px; -webkit-border-bottom-left-radius: 13px; -moz-border-radius-bottomleft: 13px; border-bottom-left-radius: 13px; text-indent: 0px; border: 1px solid #eeb44f; display: inline-block; color: #ffffff; /*font-family:Trebuchet MS;*/ font-size: 20px; font-weight: bold; font-style: normal; height: 39px; line-height: 39px; width: 250px; text-decoration: none; text-align: center; text-shadow: 1px 1px 0px #cc9f52; } .button-orange:hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #FFA347), color-stop(1, #ffc477)); background: -moz-linear-gradient(center top, #FFA347 5%, #ffc477 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa347', endColorstr='#ffc477'); background-color: #FFA347; } .button-1:active { position: relative; top: 1px; } /* This button was generated using CSSButtonGenerator.com */ .button-yellow { -moz-box-shadow: inset 0px 1px 0px 0px #fae7c0; -webkit-box-shadow: inset 0px 1px 0px 0px #fae7c0; box-shadow: inset 0px 1px 0px 0px #fae7c0; background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f8d480), color-stop(1, #F5C149)); background: -moz-linear-gradient(center top, #f8d480 5%, #F5C149 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f8d480', endColorstr='#f5c149'); background-color: #f8d480; /*-webkit-border-top-left-radius:13px; -moz-border-radius-topleft:13px; border-top-left-radius:13px; -webkit-border-top-right-radius:13px; -moz-border-radius-topright:13px; border-top-right-radius:13px; -webkit-border-bottom-right-radius:13px; -moz-border-radius-bottomright:13px; border-bottom-right-radius:13px; -webkit-border-bottom-left-radius:13px; -moz-border-radius-bottomleft:13px; border-bottom-left-radius:13px; text-indent:0px;*/ border: 1px solid #edc651; /*display:inline-block; color:#ffffff; font-family:Trebuchet MS; font-size:15px; font-weight:bold; font-style:normal; height:39px; line-height:39px; width:200px; text-decoration:none; text-align:center;*/ text-shadow: 1px 1px 0px #cc9f52; } .button-yellow:hover { background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #F5C149), color-stop(1, #f8d480)); background: -moz-linear-gradient(center top, #F5C149 5%, #f8d480 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f5c149', endColorstr='#f8d480'); background-color: #F5C149; } .button-yellow:active { /*position:relative; top:1px;*/ } h4.cta { clear: both; } html, body { overflow-x: hidden; } /******************************** PAGE: CONTACT ********************************/ /* keep the help boxes from being huge */ img.ninja-forms-help-text { /* "width: auto is the fallback for IE not supporting width: initial" */ width: auto; width: initial; } /* for smaller widths - the meeting time drop down shoudln't be wider than the viewport */ select#ninja_forms_field_8 { max-width: 100%; } .ninja-forms-required-items { display: none; } #contact-2 h3 { margin: 0 0 .5em 0; } div#gmap { width: 100% !important; /*260px*/ } /******************************** PAGE: OPTIONS/SERVICES ********************************/ /* Styles for the income thresholds table */ .CSSTableGenerator { margin: 0px; padding: 0px; width: 100%; border: 1px solid #000000; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } .CSSTableGenerator table { border-collapse: collapse; border-spacing: 0; width: 100%; height: 100%; margin: 0px; padding: 0px; } .CSSTableGenerator tr:last-child td:last-child { -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; } .CSSTableGenerator table tr:first-child td:first-child { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } .CSSTableGenerator table tr:first-child td:last-child { -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; } .CSSTableGenerator tr:last-child td:first-child { -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; } .CSSTableGenerator tr:hover td { background-color: #ffffff; } .CSSTableGenerator td { vertical-align: middle; background-color: #fcfcfc; border: 1px solid #000000; border-width: 0px 1px 1px 0px; text-align: center; padding: 7px; /*font-size:10px; font-family:Arial; font-weight:bold; color:#000000;*/ } .CSSTableGenerator tr:last-child td { border-width: 0px 1px 0px 0px; } .CSSTableGenerator tr td:last-child { border-width: 0px 0px 1px 0px; } .CSSTableGenerator tr:last-child td:last-child { border-width: 0px 0px 0px 0px; } .CSSTableGenerator tr:first-child td { background: -o-linear-gradient(bottom, #ffa347 5%, #ffa347 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffa347), color-stop(1, #ffa347)); background: -moz-linear-gradient(center top, #ffa347 5%, #ffa347 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffa347", endColorstr="#ffa347"); background: -o-linear-gradient(top, #ffa347, ffa347); background-color: #ffa347; border: 0px solid #000000; text-align: center; border-width: 0px 0px 1px 1px; /*font-size:14px; font-family:Arial; font-weight:bold; color:#ffffff;*/ } .CSSTableGenerator tr:first-child:hover td { background: -o-linear-gradient(bottom, #ffa347 5%, #ffa347 100%); background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ffa347), color-stop(1, #ffa347)); background: -moz-linear-gradient(center top, #ffa347 5%, #ffa347 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffa347", endColorstr="#ffa347"); background: -o-linear-gradient(top, #ffa347, ffa347); background-color: #ffa347; } .CSSTableGenerator tr:first-child td:first-child { border-width: 0px 0px 1px 0px; } .CSSTableGenerator tr:first-child td:last-child { border-width: 0px 0px 1px 1px; } .CSSTableGenerator { max-width: 800px; } table#income_chart { font-size: .88em; } /*# sourceMappingURL=style.css.map */
heathwhughes/benafix-site
wp-content/themes/hbenefits/style.css
CSS
gpl-2.0
11,552
<?php /** * Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br /> * File: securimage_show_example2.php<br /> * * Copyright (c) 2011, Drew Phillips * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Any modifications to the library should be indicated clearly in the source code * to inform users that the changes are not a part of the original software.<br /><br /> * * If you found this script useful, please take a quick moment to rate it.<br /> * http://www.hotscripts.com/rate/49400.html Thanks. * * @link http://www.phpcaptcha.org Securimage PHP CAPTCHA * @link http://www.phpcaptcha.org/latest.zip Download Latest Version * @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation * @copyright 2011 Drew Phillips * @author Drew Phillips <[email protected]> * @version 3.0 (October 2011) * @package Securimage * */ require_once dirname(__FILE__) . '/securimage.php'; $img = new Securimage(); //Change some settings $img->image_width = 280; $img->image_height = 100; $img->perturbation = 0.9; // high level of distortion $img->code_length = rand(5,6); // random code length $img->image_bg_color = new Securimage_Color("#ffffff"); $img->num_lines = 12; $img->noise_level = 5; $img->text_color = new Securimage_Color("#000000"); $img->noise_color = $img->text_color; $img->line_color = new Securimage_Color("#cccccc"); $img->show();
scorpioinfotech/mariasplace2
wp-content/plugins/qa/securimage/securimage_show_example2.php
PHP
gpl-2.0
2,746
#ifndef FILEZILLA_INTERFACE_CLEARPRIVATEDATA_HEADER #define FILEZILLA_INTERFACE_CLEARPRIVATEDATA_HEADER #include "dialogex.h" #include <wx/timer.h> class CMainFrame; class CClearPrivateDataDialog final : public wxDialogEx { public: static CClearPrivateDataDialog* Create(CMainFrame* pMainFrame) { return new CClearPrivateDataDialog(pMainFrame); } void Run(); void Delete(); protected: CClearPrivateDataDialog(CMainFrame* pMainFrame); virtual ~CClearPrivateDataDialog() = default; bool ClearReconnect(); void RemoveXmlFile(const wxString& name); CMainFrame* const m_pMainFrame; wxTimer m_timer; DECLARE_EVENT_TABLE() void OnTimer(wxTimerEvent& event); }; #endif
madnight/filezilla
src/interface/clearprivatedata.h
C
gpl-2.0
684
# encoding: utf-8 # # Copyright 2017 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ An abstract event that can be stored in the database. """ from __future__ import absolute_import import datetime import itertools import mx.DateTime import pytz import cereconf class _VerbSingleton(type): """ A metaclass that makes each EventType verb a singleton. """ verbs = {} def __call__(cls, verb, *args): if verb not in cls.verbs: cls.verbs[verb] = super(_VerbSingleton, cls).__call__(verb, *args) return cls.verbs[verb] def get_verb(cls, verb): return cls.verbs.get(verb) class EventType(_VerbSingleton('EventTypeSingleton', (object,), {})): """Holds an event type.""" __slots__ = ['verb', 'description', ] def __init__(self, verb, description): """ Initialize EventType. :verb: Scim verb :description: HR description text """ self.verb = verb self.description = description def __repr__(self): return '<{0.__class__.__name__!s} {0.verb}>'.format(self) def __eq__(self, other): """Equality.""" return isinstance(other, EventType) and other.verb == self.verb def __hash__(self): """Hash.""" return hash(self.verb) # Define event types: ADD = EventType('add', 'Add an object to subject') CREATE = EventType('create', 'Create a new subject') ACTIVATE = EventType('activate', 'Subject has no longer quarantines in system') MODIFY = EventType('modify', 'Attributes has changed') DEACTIVATE = EventType('deactivate', 'Quarantine is activated') DELETE = EventType('delete', 'Subject is deleted') REMOVE = EventType('remove', 'Remove an object from subject') PASSWORD = EventType('password', 'Subject has changed password') JOIN = EventType('join', 'Join two objects') class EntityRef(object): """ Representation of a single entity. The entity_id can be used internally to identify which object we reference The entity_type and ident is used to generate a reference to the object that other systems can use. """ __slots__ = ['ident', 'entity_type', 'entity_id', ] def __init__(self, entity_id, entity_type, ident): self.entity_id = int(entity_id) self.entity_type = entity_type self.ident = ident def __repr__(self): return ("<{0.__class__.__name__}" " id={0.entity_id!r}" " type={0.entity_type!r}" " ident={0.ident!r}>").format(self) def __eq__(self, other): return (isinstance(other, EntityRef) and self.entity_id == other.entity_id) def to_dict(self): return { 'ident': self.ident, 'entity_id': self.entity_id, 'entity_type': self.entity_type, } class DateTimeDescriptor(object): """ Datetime descriptor that handles timezones. When setting the datetime, this method will try to localize it with the default_timezone in the following ways: - mx.DateTime.DateTimeType: Naive datetime, assume in default_timezone - datetime.datetime: Assume in default_timezone if naive - integer: Assume timestamp in UTC The returned object will always be a localized datetime.datetime """ default_timezone = pytz.timezone(cereconf.TIMEZONE) def __init__(self, slot): """ Creates a new datetime descriptor. :param str slot: The attribute name where the actual value is stored. """ self.slot = slot def __repr__(self): return '{0.__class__.__name__}({0.slot!r})'.format(self) def __get__(self, obj, cls=None): if not obj: return self return getattr(obj, self.slot, None) def __set__(self, obj, value): if value is None: self.__delete__(obj) return if isinstance(value, (int, long, )): # UTC timestamp value = pytz.utc.localize( datetime.datetime.fromtimestamp(value)) elif isinstance(value, mx.DateTime.DateTimeType): # Naive datetime in default_timezone value = self.default_timezone.localize(value.pydatetime()) elif isinstance(value, datetime.datetime): if value.tzinfo is None: value = self.default_timezone.localize(value) else: raise TypeError('Invalid datetime {0} ({1})'.format(type(value), repr(value))) setattr(obj, self.slot, value) def __delete__(self, obj): if hasattr(obj, self.slot): delattr(obj, self.slot) class Event(object): """ Event abstraction. Contains all the neccessary data to serialize an event. """ DEFAULT_TIMEZONE = 'Europe/Oslo' __slots__ = ['event_type', 'subject', 'objects', 'context', 'attributes', '_timestamp', '_scheduled', ] timestamp = DateTimeDescriptor('_timestamp') scheduled = DateTimeDescriptor('_scheduled') def __init__(self, event_type, subject=None, objects=None, context=None, attributes=None, timestamp=None, scheduled=None): """ :param EventType event: the type of event :param EntityRef subject: reference to the affected entity :param list objects: sequence of other affected objects (EntityRef) :param list context: sequence of affected systems (str) :param list attributes: sequence of affected attributes (str) :param datetime timestamp: when the event originated :param datetime schedule: when the event should be issued """ self.event_type = event_type self.subject = subject self.timestamp = timestamp self.scheduled = scheduled self.objects = set(objects or []) self.context = set(context or []) self.attributes = set(attributes or []) def __repr__(self): return ('<{0.__class__.__name__}' ' event={0.event_type!r}' ' subject={0.subject!r}>').format(self) def mergeable(self, other): """Can this event be merged with other.""" if self.scheduled is not None: return False if self.subject != other.subject: return False if self.event_type == CREATE: return other.event_type not in (DEACTIVATE, REMOVE) if self.event_type == DELETE: return other.event_type in (REMOVE, DEACTIVATE, ADD, ACTIVATE, MODIFY, PASSWORD) if (self.event_type == other.event_type and self.event_type in (ADD, REMOVE, ACTIVATE, DEACTIVATE)): return True if self.context != other.context: return False return True def merge(self, other): """Merge messages.""" def ret_self(): self.objects.update(other.objects) return [self] if not self.mergeable(other): return [self, other] if self.event_type == CREATE: if other.event_type == DELETE: return [] if other.event_type == ADD: self.context.update(other.context) return ret_self() if other.event_type == ACTIVATE: return ret_self() # TODO: if quarantine is an attr, delete it if other.event_type == MODIFY: self.attributes.update(other.attributes) return ret_self() if other.event_type == PASSWORD: self.attributes.add('password') return ret_self() elif self.event_type == DELETE: return ret_self() elif other.event_type == DELETE: return [other] elif (ACTIVATE == self.event_type and DEACTIVATE == other.event_type and self.context == other.context): return [] elif (ADD == self.event_type and REMOVE == other.event_type and self.context == other.context): return [] elif self.event_type == other.event_type: if self.event_type in (ADD, REMOVE, ACTIVATE, DEACTIVATE): self.context.update(other.context) return ret_self() if self.context != other.context: return [self, other] self.attributes.update(other.attributes) return ret_self() return [self, other] def merge_events(events): """Merge events with similarities. As long as subject is the same: * create + add/activate/modify/password = create with attributes merged * create + deactivate/remove is untouched * create + delete should be removed * delete + remove/deactivate/add/activate/modify/password = delete * x + x = x * activate + deactivate = noop (careful with aud) Sort into canonical order: #. create #. delete #. add #. activate #. modify #. password #. deactivate #. remove """ order = (CREATE, DELETE, ADD, ACTIVATE, MODIFY, PASSWORD, DEACTIVATE, REMOVE, JOIN) ps = [[] for x in order] for pl in events: pltype = pl.event_type idx = order.index(pltype) ps[idx].append(pl) result = {} for idx, tp, pl in zip(range(len(order)), order, ps): for p in pl: if p.subject not in result: result[p.subject] = [p] else: result[p.subject].append(p) def merge_list(finished, merged, current, rest): while rest or merged: if rest: new = current.merge(rest[0]) if not new: rest.pop(0) merged.extend(rest) rest = merged if not rest: return finished merged = [] current = rest.pop(0) elif len(new) == 1: if new[0] is not current: merged.extend(rest) rest = merged current = rest.pop(0) merged = [] else: rest.pop(0) else: merged.append(rest.pop(0)) else: # merged is not empty finished.append(current) rest = merged merged = [] current = rest.pop(0) finished.append(current) return finished for sub, lst in result.items(): result[sub] = merge_list([], [], lst[0], lst[1:]) return list(itertools.chain(*result.values()))
unioslo/cerebrum
Cerebrum/modules/event_publisher/event.py
Python
gpl-2.0
11,579
# -*- coding: utf-8 -*- from utils import * commands = [ '^remindme', '^reminder', '^remind$', '^r ' ] parameters = ( ('delay', True), ('message', True), ) description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['command_start'] + 'remindme 2h GiT GuD`' action = 'typing' hidden = True reminders = load_json('data/reminders.json') def to_seconds(time, unit): if unit == 's': return float(time) elif unit == 'm': return float(time) * 60 elif unit == 'h': return float(time) * 60 * 60 elif unit == 'd': return float(time) * 60 * 60 * 24 def run(msg): input = get_input(msg['text']) if not input: doc = get_doc(commands, parameters, description) return send_message(msg['chat']['id'], doc, parse_mode="Markdown") delay = first_word(input) if delay: time = delay[:-1] unit = delay[-1:] if not is_int(time) or is_int(unit): message = 'The delay must be in this format: `(integer)(s|m|h|d)`.\nExample: `2h` for 2 hours.' return send_message(msg['chat']['id'], message, parse_mode="Markdown") try: alarm = now() + to_seconds(time, unit) except: return send_message(msg['chat']['id'], message, parse_mode="Markdown") text = all_but_first_word(input) if not text: send_message(msg['chat']['id'], 'Please include a reminder.') if 'username' in msg['from']: text += '\n@' + msg['from']['username'] reminder = OrderedDict() reminder['alarm'] = alarm reminder['chat_id'] = msg['chat']['id'] reminder['text'] = text reminders[int(now())] = reminder save_json('data/reminders.json', reminders) if unit == 's': delay = delay.replace('s', ' seconds') if unit == 'm': delay = delay.replace('m', ' minutes') if unit == 'h': delay = delay.replace('h', ' hours') if unit == 'd': delay = delay.replace('d', ' days') message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text send_message(msg['chat']['id'], message, parse_mode="Markdown") def cron(): reminders = load_json('data/reminders.json', True) for id, reminder in reminders.items(): if now() > reminder['alarm']: send_message(reminder['chat_id'], reminder['text']) del reminders[id] save_json('data/reminders.json', reminders)
shahabsaf1/Python
plugins/reminders.py
Python
gpl-2.0
2,643
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_05) on Fri Aug 13 10:55:24 CDT 2004 --> <TITLE> Uses of Class javazoom.jl.decoder.OutputChannels </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class javazoom.jl.decoder.OutputChannels"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="OutputChannels.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>javazoom.jl.decoder.OutputChannels</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Packages that use <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#javazoom.jl.decoder"><B>javazoom.jl.decoder</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="javazoom.jl.decoder"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A> in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Fields in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A> declared as <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD> <TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#LEFT">LEFT</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD> <TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#RIGHT">RIGHT</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD> <TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#BOTH">BOTH</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD> <TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#DOWNMIX">DOWNMIX</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Methods in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A> that return <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD> <TD><CODE><B>OutputChannels.</B><B><A HREF="../../../../javazoom/jl/decoder/OutputChannels.html#fromInt(int)">fromInt</A></B>(int&nbsp;code)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates an <code>OutputChannels</code> instance corresponding to the given channel code.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></CODE></FONT></TD> <TD><CODE><B>Decoder.Params.</B><B><A HREF="../../../../javazoom/jl/decoder/Decoder.Params.html#getOutputChannels()">getOutputChannels</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Methods in <A HREF="../../../../javazoom/jl/decoder/package-summary.html">javazoom.jl.decoder</A> with parameters of type <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>Decoder.Params.</B><B><A HREF="../../../../javazoom/jl/decoder/Decoder.Params.html#setOutputChannels(javazoom.jl.decoder.OutputChannels)">setOutputChannels</A></B>(<A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder">OutputChannels</A>&nbsp;out)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../javazoom/jl/decoder/OutputChannels.html" title="class in javazoom.jl.decoder"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="OutputChannels.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
knocte/getittogether
doc/javazoom/jl/decoder/class-use/OutputChannels.html
HTML
gpl-2.0
11,155
/* * Flocking Debugging Unit Generators * http://github.com/colinbdclark/flocking * * Copyright 2011-2014, Colin Clark * Dual licensed under the MIT and GPL Version 2 licenses. */ /*global require*/ /*jshint white: false, newcap: true, regexp: true, browser: true, forin: false, nomen: true, bitwise: false, maxerr: 100, indent: 4, plusplus: false, curly: true, eqeqeq: true, freeze: true, latedef: true, noarg: true, nonew: true, quotmark: double, undef: true, unused: true, strict: true, asi: false, boss: false, evil: false, expr: false, funcscope: false*/ var fluid = fluid || require("infusion"), flock = fluid.registerNamespace("flock"); (function () { "use strict"; // TODO: Unit tests. flock.ugen.print = function (input, output, options) { var that = flock.ugen(input, output, options); that.gen = function (numSamps) { var inputs = that.inputs, out = that.output, m = that.model, label = m.label, chan = inputs.channel, // Basic multichannel support. This should be inproved // by factoring the multichannel input code out of flock.ugen.out. source = chan ? inputs.source.output[chan.output[0]] : inputs.source.output, trig = inputs.trigger.output[0], freq = inputs.freq.output[0], i, j, val; if (trig > 0.0 && m.prevTrig <= 0.0) { fluid.log(fluid.logLevel.IMPORTANT, label + source); } if (m.freq !== freq) { m.sampInterval = Math.round(m.sampleRate / freq); m.freq = freq; m.counter = m.sampInterval; } for (i = 0, j = 0 ; i < numSamps; i++, j += m.strides.source) { if (m.counter >= m.sampInterval) { fluid.log(fluid.logLevel.IMPORTANT, label + source[j]); m.counter = 0; } m.counter++; out[i] = val = source[i]; } m.value = m.unscaledValue = val; }; that.init = function () { var o = that.options; that.model.label = o.label ? o.label + ": " : ""; that.onInputChanged(); }; that.init(); return that; }; flock.ugenDefaults("flock.ugen.print", { rate: "audio", inputs: { source: null, trigger: 0.0, freq: 1.0 }, ugenOptions: { model: { unscaledValue: 0.0, value: 0.0, counter: 0 }, strideInputs: ["source"] } }); }());
mcanthony/Flocking
src/ugens/debugging.js
JavaScript
gpl-2.0
2,806
-- Copyright (c) 2012 Roland Yonaba --[[ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. --]] local insert = table.insert local require = require local pcall = pcall local loadstring = loadstring local print = print local tests = {} local aborted = {} local function addTest (test) test.n = #tests+1 insert(tests,test) end local function runTests(listOfTests,output) local output = output or io.stdout local status,err,fails for i,test in ipairs(listOfTests) do output:write(i..'/ TOPIC : '..test.topic..'\n') output:write('COMMENTS : '..test.comments..'\n') output:write('Sample Code :\n'..test.sample..'\n') output:write('Output\n') status,err = pcall(loadstring(test.sample)) if not status then output:write('Error occured\n') insert(aborted,{test = test, error = err}) end output:write('\nEnd of Test '..i..'\n\n') end fails = #aborted if fails > 0 then output:write(fails..' test'..(fails>1 and 's' or '')..' aborted..\n') for i in ipairs(aborted) do output:write('Test '..aborted[i].test.n..' : '..aborted[i].error..'\n') end else output:write('All tests runned successfully\n') output:close() end end addTest( { topic = 'Class Creation', comments = 'We will cover various ways to create classes using LCS', sample = [[ local LCS = require "LCS" local myClass = LCS.class() local myClass2 = LCS.class {var1 = 0, var2 = nil} print(myClass2.var1) print(myClass2.var2) print(myClass2.var3) print(LCS.is_A(myClass,'class')) print(LCS.is_A(myClass)) ]], } ) addTest( { topic = 'Instantiation (1/2)', comments = 'We will cover differents ways to instantiate objects from a class', sample = [[ local LCS = require 'LCS' local Animal = LCS.class {name = 'Animal'} function Animal:yell() print('I am a '..self.name) end local kitty = Animal() print(kitty.name) kitty.name = 'kitty' kitty:yell() local doggy = Animal:new() print(doggy.name) doggy.name = 'doggy' doggy:yell() ]], } ) addTest( { topic = 'Instantiation (2/2)', comments = 'We will cover how to instantiante objects and init them with parameters', sample = [[ local LCS = require 'LCS' local Animal = LCS.class {name = 'Animal', weight = nil} function Animal:init(name,weight) self.name = name self.weight = weight end function Animal:yell() print('I am a ',self.name,', I weight ',self.weight) end local kitty = Animal('kitty',10) local doggy = Animal:new('doggy',20) kitty:yell() doggy:yell() ]], } ) addTest( { topic = 'Inheritance ', comments = 'We will learn how to use inheritance feature in LCS', sample = [[ local LCS = require 'LCS' local Animal = LCS.class {name = 'Animal'} function Animal:init(name) self.name = name end function Animal:yell() print('I am a ',self.name) end local Cat = Animal:extends() local Dog = Animal:extends() function Cat:speak() print('Meeoow') end function Dog:speak() print('Ouah Ouah!') end local kitty = Cat('kitty') local doggy = Dog('Doggy') kitty:yell() doggy:yell() kitty:speak() doggy:speak() ]], } ) addTest( { topic = 'Super Call ', comments = 'We will learn how to call methods defined within a superclass from a derived class', sample = [[ local LCS = require 'LCS' local Animal = LCS.class {name = 'Animal'} function Animal:init(name) self.name = name end function Animal:yell() print('I am a ',self.name) end local Cat = Animal:extends() function Cat:yell() print('Meeoow') end local kitty = Cat('kitty') kitty:yell() kitty:super('yell') ]], } ) addTest( { topic = 'Final and static classes ', comments = 'We will learn how to create final and static classes.\nThis test will have no output.', sample = [[ local LCS = require 'LCS' local FinalAnimal = LCS.class.final {name = 'Animal'} local StaticAnimal = LCS.class.static {name = 'Animal'} -- This will throw an error -- local FinalDog = FinalAnimal:extends() -- This will throw an error -- staticKitty = StaticAnimal() ]], } ) addTest( { topic = 'Full Api review ', comments = 'We will learn the use of the whole api functions', sample = [[ local LCS = require 'LCS' local Animal = LCS.class {name = 'Animal'} function Animal:init(name) self.name = name end local Cat = Animal:extends() function Cat:yell() print('Meeoow') end local thing = Animal('thing') local kitty = Cat('kitty') print(kitty:getClass() == Cat) print(Cat:getClass() == Animal) print(thing:getClass() == Animal) print(Animal:getClass() == nil) print(kitty:is_A(Cat)) print(thing:is_A(Animal)) print(LCS.is_A(kitty,'object')) print(LCS.is_A(thing)) print(LCS.is_A(Cat,'class')) print(LCS.is_A(Animal)) print((Animal:getSubClasses())[Cat]) ]], } ) runTests(tests)
ZenityRTS/Zenity
libs/lcs/tests.lua
Lua
gpl-2.0
5,915
/* This file is part of the KDE project * Copyright (C) 2009 Pierre Stirnweiss <[email protected]> * Copyright (C) 2011 Boudewijn Rempt <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA.*/ #include "TextPasteCommand.h" #include <KoTextEditor.h> #include <KoTextDocument.h> #include <KoTextPaste.h> #include <KoChangeTracker.h> #include <KoShapeController.h> #include <klocale.h> #include <kdebug.h> #include <kaction.h> #include <QTextDocument> #include <QApplication> #include <QMimeData> #include "ChangeTrackedDeleteCommand.h" #include "DeleteCommand.h" #include "KoDocumentRdfBase.h" #ifdef SHOULD_BUILD_RDF #include <Soprano/Soprano> #else namespace Soprano { class Model { }; } #endif TextPasteCommand::TextPasteCommand(const QMimeData *mimeData, QTextDocument *document, KoShapeController *shapeController, KoCanvasBase *canvas, KUndo2Command *parent, bool pasteAsText) : KUndo2Command (parent), m_mimeData(mimeData), m_document(document), m_rdf(0), m_shapeController(shapeController), m_canvas(canvas), m_pasteAsText(pasteAsText), m_first(true) { m_rdf = qobject_cast<KoDocumentRdfBase*>(shapeController->resourceManager()->resource(KoText::DocumentRdf).value<QObject*>()); if (m_pasteAsText) setText(i18nc("(qtundo-format)", "Paste As Text")); else setText(i18nc("(qtundo-format)", "Paste")); } void TextPasteCommand::undo() { KUndo2Command::undo(); } void TextPasteCommand::redo() { if (m_document.isNull()) return; KoTextDocument textDocument(m_document); KoTextEditor *editor = textDocument.textEditor(); if (!m_first) { KUndo2Command::redo(); } else { editor->beginEditBlock(); //this is needed so Qt does not merge successive paste actions together m_first = false; if (editor->hasSelection()) { //TODO editor->addCommand(new DeleteCommand(DeleteCommand::NextChar, m_document.data(), m_shapeController, this)); } // check for mime type if (m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::Text)) || m_mimeData->hasFormat(KoOdf::mimeType(KoOdf::OpenOfficeClipboard)) ) { KoOdf::DocumentType odfType = KoOdf::Text; if (!m_mimeData->hasFormat(KoOdf::mimeType(odfType))) { odfType = KoOdf::OpenOfficeClipboard; } if (m_pasteAsText) { editor->insertText(m_mimeData->text()); } else { QSharedPointer<Soprano::Model> rdfModel; #ifdef SHOULD_BUILD_RDF if(!m_rdf) { rdfModel = QSharedPointer<Soprano::Model>(Soprano::createModel()); } else { rdfModel = m_rdf->model(); } #endif KoTextPaste paste(editor, m_shapeController, rdfModel, m_canvas, this); paste.paste(odfType, m_mimeData); #ifdef SHOULD_BUILD_RDF if (m_rdf) { m_rdf->updateInlineRdfStatements(editor->document()); } #endif } } else if (!m_pasteAsText && m_mimeData->hasHtml()) { editor->insertHtml(m_mimeData->html()); } else if (m_pasteAsText || m_mimeData->hasText()) { editor->insertText(m_mimeData->text()); } editor->endEditBlock(); //see above beginEditBlock } }
yxl/emscripten-calligra-mobile
libs/kotext/commands/TextPasteCommand.cpp
C++
gpl-2.0
4,258
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.4 # Default target executed when no arguments are given to make. default_target: all #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canoncical targets will work. .SUFFIXES: .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /opt/local/bin/cmake # The command to remove a file. RM = /opt/local/bin/cmake -E remove -f # The program to use to edit the cache. CMAKE_EDIT_COMMAND = /opt/local/bin/ccmake # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /Users/paul/Estelle-ruby/ext/taglib # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /Users/paul/Estelle-ruby/ext/taglib # Include the progress variables for this target. include CMakeFiles/progress.make #============================================================================= # Targets provided globally by CMake. # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) # Special rule for the target edit_cache edit_cache/fast: edit_cache # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -P cmake_install.cmake # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -P cmake_install.cmake # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake # Special rule for the target install/local install/local/fast: install/local # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Only default component available" # Special rule for the target list_install_components list_install_components/fast: list_install_components # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." cd /Users/paul/Estelle-ruby/ext/taglib/taglib/ape && /opt/local/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache # The main all target all: cmake_check_build_system cd /Users/paul/Estelle-ruby/ext/taglib && $(CMAKE_COMMAND) -E cmake_progress_start /Users/paul/Estelle-ruby/ext/taglib/CMakeFiles $(CMAKE_ALL_PROGRESS) cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/all $(CMAKE_COMMAND) -E cmake_progress_start /Users/paul/Estelle-ruby/ext/taglib/CMakeFiles 0 # The main clean target clean: cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/clean # The main clean target clean/fast: clean # Prepare targets for installation. preinstall: all cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/preinstall # Prepare targets for installation. preinstall/fast: cd /Users/paul/Estelle-ruby/ext/taglib && $(MAKE) -f CMakeFiles/Makefile2 taglib/ape/preinstall # clear depends depend: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 # Help Target help:: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... edit_cache" @echo "... install" @echo "... install/local" @echo "... list_install_components" @echo "... rebuild_cache" #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: cd /Users/paul/Estelle-ruby/ext/taglib && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
paulcbetts/Estelle
ext/taglib/taglib/ape/Makefile
Makefile
gpl-2.0
5,036