code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<?php // Heading $_['heading_title'] = 'Statistic'; $_['text_edit'] = 'Edit'; $_['text_enable'] = 'Enable'; $_['text_disable'] = 'Disable'; $_['entry_name'] = 'Box name'; $_['entry_online_view'] = 'Show online'; $_['entry_today_view'] = 'Show today visit'; $_['entry_yesterday_view'] = 'Show yesterday visit'; $_['entry_lastmonth_view'] = 'Show lastmonth visit'; $_['entry_total_view'] = 'Show total visit'; $_['entry_total'] = 'Base total visit'; $_['entry_status'] = 'Status'; $_['button_cancel'] = 'Cancle'; $_['button_save'] = 'Save'; $_['text_success'] = 'You have successfully modified statistic!'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify news!'; ?>
shanksimi/opencart.vn
upload/admin/language/english/module/statistic.php
PHP
gpl-3.0
773
#include "afxwin.h" #if !defined(AFX_PROGRAMSETTINGDLG_H__BED04C03_751D_4A93_A586_91AE8D148155__INCLUDED_) #define AFX_PROGRAMSETTINGDLG_H__BED04C03_751D_4A93_A586_91AE8D148155__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ProgramSettingDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CProgramSettingDlg dialog class CProgramSettingDlg : public CDialog { // Construction public: CProgramSettingDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CProgramSettingDlg) enum { IDD = IDD_DLG_PROGRAM_SET }; CString m_OutputLocation; double m_cellSize_dx; double m_cellSize_dy; double m_cellSize_dz; int m_enlarge; int m_raypx; int m_raypy; BOOL m_ifoutputbox; BOOL m_iflogvolume; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CProgramSettingDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: virtual BOOL PreTranslateMessage(MSG* pMsg); // Generated message map functions //{{AFX_MSG(CProgramSettingDlg) virtual BOOL OnInitDialog(); afx_msg void OnBtnImage(); afx_msg void OnBtnDefault(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: bool flagDisableControls; int m_LimitEle; CButton ctrl_cube_dx; CButton ctrl_logfile; CButton ctrl_VgsTAR; CButton ctrl_btn_default; CButton ctrl_btn_ok; int m_distribution; BOOL check_cube_value; CEdit ctrl_dy; CEdit ctrl_dx; CEdit ctrl_dz; CEdit ctrl_zone_type; CEdit ctrl_output_location; //int lapx; //CEdit ctrl_lapy; //int lapy; //CEdit ctrl_lapx; CEdit ctrl_gpx; CEdit ctrl_gpy; int gpx; int gpy; int gap_option; CStatic ctrl_G_spherical; CComboBox ctrl_leaf_distribution; int m_leaf_distribution; void SetShow(); int gap_average_option; CEdit ctrl_MA; CStatic ctrl_deg; CButton ctrl_browse; CEdit ctrl_dis_file; CString CurrentPath; double m_mean_leaf_inc; CString m_dis_file; int ZeroGapManage; double minimumGap; bool IfSetMaxLAD; double MaxLAD; int m_leaf_dispersion_option; double m_leaf_dispersion; double fix_pza; double default_pza; //Variable added for subdivision of PZA BOOL is_divide_pza; int division_horizontal; int division_vertical; afx_msg void OnBnClickedBtnAdvance(); afx_msg void OnBnClickedBrowse(); afx_msg void OnBnClickedOk(); afx_msg void OnCbnSelchangeComboLdistribution(); afx_msg void OnEnChangeEditCellsizeX(); afx_msg void OnBnClickedCheck5(); void DisableAll(); void DisableBtnOK(); double m_mean_leaf_area; int m_inversion_method; CButton ctrl_inversion_method; CEdit ctrlLeafArea; afx_msg void OnBnClickedRadio1(); void SetctrlLeafArea(); afx_msg void OnBnClickedRadio2(); afx_msg void OnBnClickedRadio3(); BOOL m_ChkLAD; afx_msg void OnBnClickedButton1(); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_PROGRAMSETTINGDLG_H__BED04C03_751D_4A93_A586_91AE8D148155__INCLUDED_)
LudovicHDT/GnuTreeCalculator
ProgramSettingDlg.h
C
gpl-3.0
3,225
using System; using System.Threading.Tasks; using CMS.Base; using CMS.DataEngine; using CMS.EventLog; using CMS.Helpers; using CMS.OnlineMarketing; using CMS.Scheduler; using CMS.UIControls; [Title("om.score.recalculate")] public partial class CMSModules_Scoring_Pages_ScheduleRecalculationDialog : CMSModalPage { #region "Page events" protected void Page_Load(object sender, EventArgs e) { QueryHelper.ValidateHash("hash"); ScoreInfo scoreInfo = ScoreInfoProvider.GetScoreInfo(QueryHelper.GetInteger("scoreID", 0)); if (scoreInfo == null) { ShowError(GetString("general.objectnotfound")); return; } if (!RequestHelper.IsPostBack()) { LoadValuesFromExistingScore(scoreInfo); } string tooltipTextKey = scoreInfo.ScoreBelongsToPersona ? "persona.recalculationwarninglong" : "om.score.recalculationwarninglong"; ShowWarning(GetString("om.score.recalculationwarning"), null, GetString(tooltipTextKey)); Save += (s, ea) => ScheduleRecalculation(scoreInfo); } public void radGroupRecalculate_CheckedChanged(object sender, EventArgs e) { calendarControl.Enabled = radLater.Checked; } protected void ScheduleRecalculation(ScoreInfo scoreInfo) { // Validate input if (radLater.Checked && !(calendarControl.SelectedDateTime > DateTime.Now)) { ShowError(GetString("om.score.recalculationscheduledinvaliddate")); return; } if (!scoreInfo.CheckPermissions(PermissionsEnum.Modify, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(scoreInfo.TypeInfo.ModuleName, "modify"); } if (radLater.Checked && (calendarControl.SelectedDateTime > DateTime.Now)) { StartRecalculationLater(scoreInfo); } else if (radNow.Checked) { StartRecalculationNow(scoreInfo); } ScriptHelper.RegisterWOpenerScript(this); ScriptHelper.RegisterStartupScript(this, typeof(string), "RefreshPage", ScriptHelper.GetScript("wopener.RefreshPage(); CloseDialog();")); } #endregion #region "Private methods" /// <summary> /// Loads controls with values from existing score. /// </summary> /// <param name="score"></param> private void LoadValuesFromExistingScore(ScoreInfo score) { if (score.ScoreScheduledTaskID > 0) { TaskInfo taskInfo = TaskInfoProvider.GetTaskInfo(score.ScoreScheduledTaskID); if ((taskInfo != null) && taskInfo.TaskEnabled) { radLater.Checked = true; calendarControl.Enabled = true; calendarControl.SelectedDateTime = taskInfo.TaskNextRunTime; } } } /// <summary> /// Recalculates score at time that user specified. /// </summary> /// <param name="score">Score to recalculate</param> private void StartRecalculationLater(ScoreInfo score) { // Set info for scheduled task var task = ScoreInfoProvider.EnsureScheduledTask(score, String.Empty, TaskInfoProvider.NO_TIME, false, false); task.TaskNextRunTime = calendarControl.SelectedDateTime; task.TaskDeleteAfterLastRun = true; task.TaskEnabled = true; TaskInfoProvider.SetTaskInfo(task); // Update score score.ScoreScheduledTaskID = task.TaskID; ScoreInfoProvider.SetScoreInfo(score); } /// <summary> /// Immediately recalculates score. /// </summary> /// <param name="score">Score to recalculate</param> private void StartRecalculationNow(ScoreInfo score) { if (score.ScoreStatus == ScoreStatusEnum.Recalculating) { // Score is already being recalculated return; } // Delete already scheduled task, it is not needed if (score.ScoreScheduledTaskID > 0) { TaskInfoProvider.DeleteTaskInfo(score.ScoreScheduledTaskID); score.ScoreScheduledTaskID = 0; } // Set score as recalculating before running the async recalculator, so the change is displayed at the UI immediatelly ScoreInfoProvider.MarkScoreAsRecalculating(score); // Recalculate the score ScoreAsyncRecalculator recalculator = new ScoreAsyncRecalculator(score); Task result = recalculator.RunAsync(); LogTaskException(result); } /// <summary> /// Logs exceptions thrown within task runtime. /// </summary> /// <param name="task">Task which exceptions should be logged</param> private void LogTaskException(Task task) { task.ContinueWith(CMSThread.Wrap( (Task t) => EventLogProvider.LogException("Score", "SCORE_RECALCULATION", t.Exception) ), TaskContinuationOptions.OnlyOnFaulted); } #endregion }
CCChapel/ccchapel.com
CMS/CMSModules/Scoring/Pages/ScheduleRecalculationDialog.aspx.cs
C#
gpl-3.0
5,040
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Sverchok.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Sverchok.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Sverchok" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Sverchok" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
kilon/sverchok
docs/Makefile
Makefile
gpl-3.0
6,770
--- title: 雪鹰领主 第37篇 第16章 峻山城内 date: 2017-05-14 06:00:04 categories: 雪鹰领主 tags: [Duke, Hannb] --- 神界广袤。 大船飞行在云雾间,按照东伯雪鹰询问得知,要抵达峻山城还需要两个多月。 在船上的日子,东伯雪鹰一方面静修推演这世界的虚空道规则,在逐渐改变自己浑源炼体法门,令身体崩解情况也得以减轻。另一方面,就是要应付这位三小姐‘御风清音’了。 “那个叫项庞云的,最后呢,没杀掉你弟弟吧?”大船的一雅间内,御风清音和东伯雪鹰相对而坐,她连紧张询问着。 “在最危急关头,我实力突破,杀了项庞云。”东伯雪鹰微笑道,想起年少时那一幕场景,依旧唏嘘,只是父母弟弟他们如今都已不在了,不过都是活了很久很久。虽然如今他能借助‘虚幻宇宙’重新创造出生命来。 可是,创造出父母弟弟,又有何意呢? “呼。”御风清音松口气:“这就好这就好。我都听的心慌呢。” “三小姐,这飞雪能飞升到神界,在下界,定是了不得的风云人物。”一旁的云管家则笑道。 “也是。”御风清音点头。 御风清音忽然道:“对了,飞雪神君,你今后有什么打算么?” “我早说过,我在神界也没家,四处闯荡。”东伯雪鹰笑道。 “要不,你就留在我们峻山城吧。”御风清音连说道,“这大荒如此危险,还是城内安全。” “我的确有意在城内修行一段时间,这次遇到危机,让我觉得,实力还是不够。”东伯雪鹰点头。 “初入神君,就敢在大荒中乱闯。”一旁的云管家嗤笑。 御风清音则连道:“飞雪神君既然要留在城内修行,这是好事,对了,飞雪神君,你实力到底是何等层次?” “神君中期吧。”东伯雪鹰说道,“只是因为受了重伤,实力一直没能恢复,相信一年半载,伤势完全好,便能恢复到神君中期。” 这些天,他的炼体法门在逐渐改进,伤势在减轻,身体也在变强。 “哦?” 一旁的云管家见状心中微微一惊。 神君中期? 飞升者,真的是从弱小一步步修行起来,甚至都没有浑源祖神血脉带来的助力!同层次,飞升者都比神界原本子民要强一大截的。这位飞雪神君如果实力恢复完好,达到神君中期。这实力怕是离他这位云管家也相差不远了。 毕竟他也只是神君后期,不过兼有‘碧光神眼’的神通!实力比寻常神君后期还厉害些许。 “好。” 御风清音露出喜色,“你有神君中期实力,又是飞升者,我一定能说服我父亲和我大哥,到时候,飞雪神君你在我御风家族兼个‘修行师傅’的闲职吧。修行师傅闲职,也没有什么危险任务,只有我御风家族核心子弟有资格来请你指点一二罢了。有了这一身份,飞雪神君在峻山城就不同了,还定期赐予一些好处,甚至都有资格进入‘藏经殿’选一门修行典籍呢。若是飞雪神君你愿意,立下些功劳,可以换取更多好处。” 东伯雪鹰听的心中一动。 藏经殿? 研究一个世界的规则,怎样才最直接? 自然是观看其他强者的修行法门!其他强者已经总结出了修行路线,只要一观,自己研究世界规则可就轻松不知道多少倍了。 “可有飞升者的典籍?”东伯雪鹰问道。 御风清音听了,得意一笑,眼睛都笑成月牙:“飞升者的修行典籍,极为罕见。可我们峻山御风氏还是有好些收藏的。” “那飞雪就厚颜了。”东伯雪鹰当即感激道,“谢三小姐。” “别高兴太早,不是谁都有资格担任修行师傅的。”云管家则淡然道,“这还得主人以及少主同意。” 御风清音则自信道:“放心吧,父亲和大哥会同意的。” 云管家见状无奈。 东伯雪鹰一笑。 和这位三小姐相处也才一个月,可他还是能感觉到,这位三小姐是真心地善良,因为待自己好,便一心为自己着想。难怪云管家之前威胁自己‘别算计到三小姐’头上。 “不管怎样,我刚来到这世界,受了这位三小姐不少的恩惠,只有今后再找机会报答了。”东伯雪鹰暗暗道,反正自己一段时间内是打算在峻山城待着的!毕竟只要是安全的地方,不管是这世界的哪一处,自己都一样可以研究世界规则。 …… 这大船上的将领、士兵守卫以及仆从等等,一共数百人。 东伯雪鹰在虚界幻境道的造诣,也算增加了自己的‘魅力值’,让别人对自己好感大增。可是,因为不能做的太明显,而强者们意志也不是轻易能撼动的。依旧有数位对自己没什么好感,特别有一位守卫对自己甚至都称得上是‘厌恶’。 这守卫名叫‘铁成柳’。 铁成柳身材高大,只是眼神阴冷,便是在守卫队伍中人缘也一般,他看东伯雪鹰目光极为冰冷厌恶,以东伯雪鹰灵魂方面的敏锐,甚至感觉到一些‘恶意’。 “我一个刚刚来到这世界的,之前从未见过他,他怎么这么厌恶我?”东伯雪鹰暗暗纳闷不解。 不过他也在意。 一个守卫而已,实力只是神将巅峰,离神君还差一线。可这一线便犹如天堑,实力也差很多。 “到了。” “峻山城到了。” 一天,船上响起了一片欢呼声。 站在船头上的三小姐,云管家,还有将领、士兵们,乃至诸多仆人们,都个个露出喜色。毕竟在大荒中前行,他们个个都不敢大意放松。 “峻山城。”东伯雪鹰也遥遥看着,那是一座庞大的城池,不过并不像界心大6的城池那般广阔的可怕,根据东伯雪鹰目测,这峻山城也就数十万里范围。 毕竟这世界的泥土砂石都重的离谱。 要建造如此城池,难度不亚于建造南云国国都! ****** 峻山城的掌控者,便是这御风家族! 在抵达峻山城的当天,在御风家族府邸的一殿厅内。 东伯雪鹰见到了御风家族的大公子!也是御风家族公认的下一任继承人——御风雷! “三妹,这就是你夸赞的飞升者?”一位高大男子坐在那,一双眼眸中隐隐有雷霆流转,威势非凡。 “见过大公子。”东伯雪鹰略微行礼。 御风雷见状轻笑一声:“都说飞升者高傲的很,果然名不虚传,在我面前,还能如此。” “毕竟在下界空间,也都是当过家乡世界第一人的嘛,当然心存傲气。”坐在一旁的御风清音却连道,“都说飞升者在神界修行艰难,可飞雪神君都达到神君中期了呢,这很不容易了。” 御风雷微微点头:“也是难得,既然我妹妹说了,飞雪神君,以后你便在我御风氏府上兼一个修行师傅的职位吧,在城内,我也会给你安排好住处。” “谢大公子。”东伯雪鹰乖乖道。 …… 是的。 见到这位御风雷大公子,东伯雪鹰仅仅说了两句话,一句‘见过大公子’,一句‘谢大公子’,之后就被安排离开了。那位御风雷大公子显然更加热心和妹妹聊这次‘出行’的事了。 一座占地半里的府邸,赐下的宝物足足两个大箱。 “飞雪师傅,东西都送到了,我等就先走了。” “谢诸位了。” 东伯雪鹰目送御风氏的士兵们离去,看着这座府邸,微微露出笑容。 这里,将是自己在这个世界很长一段时间的‘家’了。 …… 来到峻山城的第二天深夜。 东伯雪鹰在静室盘膝而坐静修,夜,一红一银白两月亮高悬夜空,月光洒满院落,显得很是寂静。 “嗯?”东伯雪鹰眉头微皱。 他灵魂感应何等敏锐。 杀机迫来! “有人要杀我?”东伯雪鹰暗暗不解,“我来到峻山城才第二天,就有要杀我的?” ****** (三七中文 www.37zw.net
1xuanyuan1/noval
source/_posts/雪鹰领主 第37篇 第16章 峻山城内.md
Markdown
gpl-3.0
8,060
/* gl_rmain.c - renderer main loop Copyright (C) 2010 Uncle Mike 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. */ #include "common.h" #include "client.h" #include "gl_local.h" #include "mathlib.h" #include "library.h" #include "beamdef.h" #include "particledef.h" #include "entity_types.h" #define IsLiquidContents( cnt ) ( cnt == CONTENTS_WATER || cnt == CONTENTS_SLIME || cnt == CONTENTS_LAVA ) msurface_t *r_debug_surface; const char *r_debug_hitbox; float gldepthmin, gldepthmax; ref_params_t r_lastRefdef; ref_instance_t RI, prevRI; mleaf_t *r_viewleaf, *r_oldviewleaf; mleaf_t *r_viewleaf2, *r_oldviewleaf2; static int R_RankForRenderMode( cl_entity_t *ent ) { switch( ent->curstate.rendermode ) { case kRenderTransTexture: return 1; // draw second case kRenderTransAdd: return 2; // draw third case kRenderGlow: return 3; // must be last! } return 0; } /* =============== R_StaticEntity Static entity is the brush which has no custom origin and not rotated typically is a func_wall, func_breakable, func_ladder etc =============== */ static qboolean R_StaticEntity( cl_entity_t *ent ) { if( !gl_allow_static->integer ) return false; if( ent->curstate.rendermode != kRenderNormal ) return false; if( ent->model->type != mod_brush ) return false; if( ent->curstate.effects & ( EF_NOREFLECT|EF_REFLECTONLY )) return false; if( ent->curstate.frame || ent->model->flags & MODEL_CONVEYOR ) return false; if( ent->curstate.scale ) // waveheight specified return false; if( !VectorIsNull( ent->origin ) || !VectorIsNull( ent->angles )) return false; return true; } /* =============== R_FollowEntity Follow entity is attached to another studiomodel and used last cached bones from parent =============== */ static qboolean R_FollowEntity( cl_entity_t *ent ) { if( ent->model->type != mod_studio ) return false; if( ent->curstate.movetype != MOVETYPE_FOLLOW ) return false; if( ent->curstate.aiment <= 0 ) return false; return true; } /* =============== R_OpaqueEntity Opaque entity can be brush or studio model but sprite =============== */ static qboolean R_OpaqueEntity( cl_entity_t *ent ) { if( ent->curstate.rendermode == kRenderNormal ) return true; if( ent->model->type == mod_sprite ) return false; if( ent->curstate.rendermode == kRenderTransAlpha ) return true; return false; } /* =============== R_SolidEntityCompare Sorting opaque entities by model type =============== */ static int R_SolidEntityCompare( const cl_entity_t **a, const cl_entity_t **b ) { cl_entity_t *ent1, *ent2; ent1 = (cl_entity_t *)*a; ent2 = (cl_entity_t *)*b; if( ent1->model->type > ent2->model->type ) return 1; if( ent1->model->type < ent2->model->type ) return -1; return 0; } /* =============== R_TransEntityCompare Sorting translucent entities by rendermode then by distance =============== */ static int R_TransEntityCompare( const cl_entity_t **a, const cl_entity_t **b ) { cl_entity_t *ent1, *ent2; vec3_t vecLen, org; float len1, len2; ent1 = (cl_entity_t *)*a; ent2 = (cl_entity_t *)*b; // now sort by rendermode if( R_RankForRenderMode( ent1 ) > R_RankForRenderMode( ent2 )) return 1; if( R_RankForRenderMode( ent1 ) < R_RankForRenderMode( ent2 )) return -1; // then by distance if( ent1->model->type == mod_brush ) { VectorAverage( ent1->model->mins, ent1->model->maxs, org ); VectorAdd( ent1->origin, org, org ); VectorSubtract( RI.vieworg, org, vecLen ); } else VectorSubtract( RI.vieworg, ent1->origin, vecLen ); len1 = VectorLength( vecLen ); if( ent2->model->type == mod_brush ) { VectorAverage( ent2->model->mins, ent2->model->maxs, org ); VectorAdd( ent2->origin, org, org ); VectorSubtract( RI.vieworg, org, vecLen ); } else VectorSubtract( RI.vieworg, ent2->origin, vecLen ); len2 = VectorLength( vecLen ); if( len1 > len2 ) return -1; if( len1 < len2 ) return 1; return 0; } /* =============== R_WorldToScreen Convert a given point from world into screen space =============== */ qboolean R_WorldToScreen( const vec3_t point, vec3_t screen ) { matrix4x4 worldToScreen; qboolean behind; float w; if( !point || !screen ) return false; Matrix4x4_Copy( worldToScreen, RI.worldviewProjectionMatrix ); screen[0] = worldToScreen[0][0] * point[0] + worldToScreen[0][1] * point[1] + worldToScreen[0][2] * point[2] + worldToScreen[0][3]; screen[1] = worldToScreen[1][0] * point[0] + worldToScreen[1][1] * point[1] + worldToScreen[1][2] * point[2] + worldToScreen[1][3]; w = worldToScreen[3][0] * point[0] + worldToScreen[3][1] * point[1] + worldToScreen[3][2] * point[2] + worldToScreen[3][3]; screen[2] = 0.0f; // just so we have something valid here if( w < 0.001f ) { behind = true; screen[0] *= 100000; screen[1] *= 100000; } else { float invw = 1.0f / w; behind = false; screen[0] *= invw; screen[1] *= invw; } return behind; } /* =============== R_ScreenToWorld Convert a given point from screen into world space =============== */ void R_ScreenToWorld( const vec3_t screen, vec3_t point ) { matrix4x4 screenToWorld; float w; if( !point || !screen ) return; Matrix4x4_Invert_Full( screenToWorld, RI.worldviewProjectionMatrix ); point[0] = screen[0] * screenToWorld[0][0] + screen[1] * screenToWorld[0][1] + screen[2] * screenToWorld[0][2] + screenToWorld[0][3]; point[1] = screen[0] * screenToWorld[1][0] + screen[1] * screenToWorld[1][1] + screen[2] * screenToWorld[1][2] + screenToWorld[1][3]; point[2] = screen[0] * screenToWorld[2][0] + screen[1] * screenToWorld[2][1] + screen[2] * screenToWorld[2][2] + screenToWorld[2][3]; w = screen[0] * screenToWorld[3][0] + screen[1] * screenToWorld[3][1] + screen[2] * screenToWorld[3][2] + screenToWorld[3][3]; if( w != 0.0f ) VectorScale( point, ( 1.0f / w ), point ); } /* =============== R_ComputeFxBlend =============== */ int R_ComputeFxBlend( cl_entity_t *e ) { int blend = 0, renderAmt; float offset, dist; vec3_t tmp; offset = ((int)e->index ) * 363.0f; // Use ent index to de-sync these fx renderAmt = e->curstate.renderamt; switch( e->curstate.renderfx ) { case kRenderFxPulseSlowWide: blend = renderAmt + 0x40 * sin( RI.refdef.time * 2 + offset ); break; case kRenderFxPulseFastWide: blend = renderAmt + 0x40 * sin( RI.refdef.time * 8 + offset ); break; case kRenderFxPulseSlow: blend = renderAmt + 0x10 * sin( RI.refdef.time * 2 + offset ); break; case kRenderFxPulseFast: blend = renderAmt + 0x10 * sin( RI.refdef.time * 8 + offset ); break; // JAY: HACK for now -- not time based case kRenderFxFadeSlow: if( renderAmt > 0 ) renderAmt -= 1; else renderAmt = 0; blend = renderAmt; break; case kRenderFxFadeFast: if( renderAmt > 3 ) renderAmt -= 4; else renderAmt = 0; blend = renderAmt; break; case kRenderFxSolidSlow: if( renderAmt < 255 ) renderAmt += 1; else renderAmt = 255; blend = renderAmt; break; case kRenderFxSolidFast: if( renderAmt < 252 ) renderAmt += 4; else renderAmt = 255; blend = renderAmt; break; case kRenderFxStrobeSlow: blend = 20 * sin( RI.refdef.time * 4 + offset ); if( blend < 0 ) blend = 0; else blend = renderAmt; break; case kRenderFxStrobeFast: blend = 20 * sin( RI.refdef.time * 16 + offset ); if( blend < 0 ) blend = 0; else blend = renderAmt; break; case kRenderFxStrobeFaster: blend = 20 * sin( RI.refdef.time * 36 + offset ); if( blend < 0 ) blend = 0; else blend = renderAmt; break; case kRenderFxFlickerSlow: blend = 20 * (sin( RI.refdef.time * 2 ) + sin( RI.refdef.time * 17 + offset )); if( blend < 0 ) blend = 0; else blend = renderAmt; break; case kRenderFxFlickerFast: blend = 20 * (sin( RI.refdef.time * 16 ) + sin( RI.refdef.time * 23 + offset )); if( blend < 0 ) blend = 0; else blend = renderAmt; break; case kRenderFxHologram: case kRenderFxDistort: VectorCopy( e->origin, tmp ); VectorSubtract( tmp, RI.refdef.vieworg, tmp ); dist = DotProduct( tmp, RI.refdef.forward ); // Turn off distance fade if( e->curstate.renderfx == kRenderFxDistort ) dist = 1; if( dist <= 0 ) { blend = 0; } else { renderAmt = 180; if( dist <= 100 ) blend = renderAmt; else blend = (int) ((1.0f - ( dist - 100 ) * ( 1.0f / 400.0f )) * renderAmt ); blend += Com_RandomLong( -32, 31 ); } break; case kRenderFxGlowShell: // safe current renderamt because it's shell scale! case kRenderFxDeadPlayer: // safe current renderamt because it's player index! blend = renderAmt; break; case kRenderFxNone: case kRenderFxClampMinScale: default: if( e->curstate.rendermode == kRenderNormal ) blend = 255; else blend = renderAmt; break; } if( e->model->type != mod_brush ) { // NOTE: never pass sprites with rendercolor '0 0 0' it's a stupid Valve Hammer Editor bug if( !e->curstate.rendercolor.r && !e->curstate.rendercolor.g && !e->curstate.rendercolor.b ) e->curstate.rendercolor.r = e->curstate.rendercolor.g = e->curstate.rendercolor.b = 255; } // apply scale to studiomodels and sprites only if( e->model && e->model->type != mod_brush && !e->curstate.scale ) e->curstate.scale = 1.0f; blend = bound( 0, blend, 255 ); return blend; } /* =============== R_ClearScene =============== */ void R_ClearScene( void ) { tr.num_solid_entities = tr.num_trans_entities = 0; tr.num_static_entities = tr.num_mirror_entities = 0; tr.num_child_entities = 0; } /* =============== R_AddEntity =============== */ qboolean R_AddEntity( struct cl_entity_s *clent, int entityType ) { if( !r_drawentities->integer ) return false; // not allow to drawing if( !clent || !clent->model ) return false; // if set to invisible, skip if( clent->curstate.effects & EF_NODRAW ) return false; // done clent->curstate.renderamt = R_ComputeFxBlend( clent ); if( clent->curstate.rendermode != kRenderNormal && clent->curstate.renderamt <= 0.0f ) return true; // invisible clent->curstate.entityType = entityType; if( entityType == ET_FRAGMENTED ) r_stats.c_client_ents++; if( R_FollowEntity( clent )) { // follow entity if( tr.num_child_entities >= MAX_VISIBLE_PACKET ) return false; tr.child_entities[tr.num_child_entities] = clent; tr.num_child_entities++; return true; } if( R_OpaqueEntity( clent )) { if( R_StaticEntity( clent )) { // opaque static if( tr.num_static_entities >= MAX_VISIBLE_PACKET ) return false; tr.static_entities[tr.num_static_entities] = clent; tr.num_static_entities++; } else { // opaque moving if( tr.num_solid_entities >= MAX_VISIBLE_PACKET ) return false; tr.solid_entities[tr.num_solid_entities] = clent; tr.num_solid_entities++; } } else { // translucent if( tr.num_trans_entities >= MAX_VISIBLE_PACKET ) return false; tr.trans_entities[tr.num_trans_entities] = clent; tr.num_trans_entities++; } return true; } /* ============= R_Clear ============= */ static void R_Clear( int bitMask ) { int bits; if( gl_overview->integer ) pglClearColor( 0.0f, 1.0f, 0.0f, 1.0f ); // green background (Valve rules) else pglClearColor( 0.5f, 0.5f, 0.5f, 1.0f ); bits = GL_DEPTH_BUFFER_BIT; if( RI.drawWorld && r_fastsky->integer ) bits |= GL_COLOR_BUFFER_BIT; if( glState.stencilEnabled ) bits |= GL_STENCIL_BUFFER_BIT; bits &= bitMask; pglClear( bits ); // change ordering for overview if( RI.drawOrtho ) { gldepthmin = 1.0f; gldepthmax = 0.0f; } else { gldepthmin = 0.0f; gldepthmax = 1.0f; } pglDepthFunc( GL_LEQUAL ); pglDepthRange( gldepthmin, gldepthmax ); } //============================================================================= /* =============== R_GetFarClip =============== */ static float R_GetFarClip( void ) { if( cl.worldmodel && RI.drawWorld ) return cl.refdef.movevars->zmax * 1.5f; return 2048.0f; } /* =============== R_SetupFrustumOrtho =============== */ static void R_SetupFrustumOrtho( void ) { ref_overview_t *ov = &clgame.overView; float orgOffset; int i; // 0 - left // 1 - right // 2 - down // 3 - up // 4 - farclip // 5 - nearclip // setup the near and far planes. orgOffset = DotProduct( RI.cullorigin, RI.cull_vforward ); VectorNegate( RI.cull_vforward, RI.frustum[4].normal ); RI.frustum[4].dist = -ov->zFar - orgOffset; VectorCopy( RI.cull_vforward, RI.frustum[5].normal ); RI.frustum[5].dist = ov->zNear + orgOffset; // left and right planes... orgOffset = DotProduct( RI.cullorigin, RI.cull_vright ); VectorCopy( RI.cull_vright, RI.frustum[0].normal ); RI.frustum[0].dist = ov->xLeft + orgOffset; VectorNegate( RI.cull_vright, RI.frustum[1].normal ); RI.frustum[1].dist = -ov->xRight - orgOffset; // top and buttom planes... orgOffset = DotProduct( RI.cullorigin, RI.cull_vup ); VectorCopy( RI.cull_vup, RI.frustum[3].normal ); RI.frustum[3].dist = ov->xTop + orgOffset; VectorNegate( RI.cull_vup, RI.frustum[2].normal ); RI.frustum[2].dist = -ov->xBottom - orgOffset; for( i = 0; i < 6; i++ ) { RI.frustum[i].type = PLANE_NONAXIAL; RI.frustum[i].signbits = SignbitsForPlane( RI.frustum[i].normal ); } } /* =============== R_SetupFrustum =============== */ void R_SetupFrustum( void ) { vec3_t farPoint; int i; // 0 - left // 1 - right // 2 - down // 3 - up // 4 - farclip // 5 - nearclip if( RI.drawOrtho ) { R_SetupFrustumOrtho(); return; } // rotate RI.vforward right by FOV_X/2 degrees RotatePointAroundVector( RI.frustum[0].normal, RI.cull_vup, RI.cull_vforward, -( 90 - RI.refdef.fov_x / 2 )); // rotate RI.vforward left by FOV_X/2 degrees RotatePointAroundVector( RI.frustum[1].normal, RI.cull_vup, RI.cull_vforward, 90 - RI.refdef.fov_x / 2 ); // rotate RI.vforward up by FOV_X/2 degrees RotatePointAroundVector( RI.frustum[2].normal, RI.cull_vright, RI.cull_vforward, 90 - RI.refdef.fov_y / 2 ); // rotate RI.vforward down by FOV_X/2 degrees RotatePointAroundVector( RI.frustum[3].normal, RI.cull_vright, RI.cull_vforward, -( 90 - RI.refdef.fov_y / 2 )); // negate forward vector VectorNegate( RI.cull_vforward, RI.frustum[4].normal ); for( i = 0; i < 4; i++ ) { RI.frustum[i].type = PLANE_NONAXIAL; RI.frustum[i].dist = DotProduct( RI.cullorigin, RI.frustum[i].normal ); RI.frustum[i].signbits = SignbitsForPlane( RI.frustum[i].normal ); } VectorMA( RI.cullorigin, R_GetFarClip(), RI.cull_vforward, farPoint ); RI.frustum[i].type = PLANE_NONAXIAL; RI.frustum[i].dist = DotProduct( farPoint, RI.frustum[i].normal ); RI.frustum[i].signbits = SignbitsForPlane( RI.frustum[i].normal ); } /* ============= R_SetupProjectionMatrix ============= */ static void R_SetupProjectionMatrix( const ref_params_t *fd, matrix4x4 m ) { GLdouble xMin, xMax, yMin, yMax, zNear, zFar; if( RI.drawOrtho ) { ref_overview_t *ov = &clgame.overView; Matrix4x4_CreateOrtho( m, ov->xLeft, ov->xRight, ov->xTop, ov->xBottom, ov->zNear, ov->zFar ); RI.clipFlags = 0; return; } RI.farClip = R_GetFarClip(); zNear = 4.0f; zFar = max( 256.0f, RI.farClip ); yMax = zNear * tan( fd->fov_y * M_PI / 360.0 ); yMin = -yMax; xMax = zNear * tan( fd->fov_x * M_PI / 360.0 ); xMin = -xMax; Matrix4x4_CreateProjection( m, xMax, xMin, yMax, yMin, zNear, zFar ); } /* ============= R_SetupModelviewMatrix ============= */ static void R_SetupModelviewMatrix( const ref_params_t *fd, matrix4x4 m ) { #if 0 Matrix4x4_LoadIdentity( m ); Matrix4x4_ConcatRotate( m, -90, 1, 0, 0 ); Matrix4x4_ConcatRotate( m, 90, 0, 0, 1 ); #else Matrix4x4_CreateModelview( m ); #endif Matrix4x4_ConcatRotate( m, -fd->viewangles[2], 1, 0, 0 ); Matrix4x4_ConcatRotate( m, -fd->viewangles[0], 0, 1, 0 ); Matrix4x4_ConcatRotate( m, -fd->viewangles[1], 0, 0, 1 ); Matrix4x4_ConcatTranslate( m, -fd->vieworg[0], -fd->vieworg[1], -fd->vieworg[2] ); } /* ============= R_LoadIdentity ============= */ void R_LoadIdentity( void ) { if( tr.modelviewIdentity ) return; Matrix4x4_LoadIdentity( RI.objectMatrix ); Matrix4x4_Copy( RI.modelviewMatrix, RI.worldviewMatrix ); pglMatrixMode( GL_MODELVIEW ); GL_LoadMatrix( RI.modelviewMatrix ); tr.modelviewIdentity = true; } /* ============= R_RotateForEntity ============= */ void R_RotateForEntity( cl_entity_t *e ) { float scale = 1.0f; if( e == clgame.entities || R_StaticEntity( e )) { R_LoadIdentity(); return; } if( e->model->type != mod_brush && e->curstate.scale > 0.0f ) scale = e->curstate.scale; Matrix4x4_CreateFromEntity( RI.objectMatrix, e->angles, e->origin, scale ); Matrix4x4_ConcatTransforms( RI.modelviewMatrix, RI.worldviewMatrix, RI.objectMatrix ); pglMatrixMode( GL_MODELVIEW ); GL_LoadMatrix( RI.modelviewMatrix ); tr.modelviewIdentity = false; } /* ============= R_TranslateForEntity ============= */ void R_TranslateForEntity( cl_entity_t *e ) { float scale = 1.0f; if( e == clgame.entities || R_StaticEntity( e )) { R_LoadIdentity(); return; } if( e->model->type != mod_brush && e->curstate.scale > 0.0f ) scale = e->curstate.scale; Matrix4x4_CreateFromEntity( RI.objectMatrix, vec3_origin, e->origin, scale ); Matrix4x4_ConcatTransforms( RI.modelviewMatrix, RI.worldviewMatrix, RI.objectMatrix ); pglMatrixMode( GL_MODELVIEW ); GL_LoadMatrix( RI.modelviewMatrix ); tr.modelviewIdentity = false; } /* =============== R_FindViewLeaf =============== */ void R_FindViewLeaf( void ) { float height; mleaf_t *leaf; vec3_t tmp; r_oldviewleaf = r_viewleaf; r_oldviewleaf2 = r_viewleaf2; leaf = Mod_PointInLeaf( RI.pvsorigin, cl.worldmodel->nodes ); r_viewleaf2 = r_viewleaf = leaf; height = RI.waveHeight ? RI.waveHeight : 16; // check above and below so crossing solid water doesn't draw wrong if( leaf->contents == CONTENTS_EMPTY ) { // look down a bit VectorCopy( RI.pvsorigin, tmp ); tmp[2] -= height; leaf = Mod_PointInLeaf( tmp, cl.worldmodel->nodes ); if(( leaf->contents != CONTENTS_SOLID ) && ( leaf != r_viewleaf2 )) r_viewleaf2 = leaf; } else { // look up a bit VectorCopy( RI.pvsorigin, tmp ); tmp[2] += height; leaf = Mod_PointInLeaf( tmp, cl.worldmodel->nodes ); if(( leaf->contents != CONTENTS_SOLID ) && ( leaf != r_viewleaf2 )) r_viewleaf2 = leaf; } } /* =============== R_SetupFrame =============== */ static void R_SetupFrame( void ) { vec3_t viewOrg, viewAng; // already done in client /*if( RP_NORMALPASS() && cl.thirdperson ) { vec3_t cam_ofs, vpn; clgame.dllFuncs.CL_CameraOffset( cam_ofs ); viewAng[PITCH] = cam_ofs[PITCH]; viewAng[YAW] = cam_ofs[YAW]; viewAng[ROLL] = 0; AngleVectors( viewAng, vpn, NULL, NULL ); VectorMA( RI.refdef.vieworg, -cam_ofs[ROLL], vpn, viewOrg ); } else {*/ VectorCopy( RI.refdef.vieworg, viewOrg ); VectorCopy( RI.refdef.viewangles, viewAng ); // build the transformation matrix for the given view angles VectorCopy( viewOrg, RI.vieworg ); AngleVectors( viewAng, RI.vforward, RI.vright, RI.vup ); // setup viewplane dist RI.viewplanedist = DotProduct( RI.vieworg, RI.vforward ); VectorCopy( RI.vieworg, RI.pvsorigin ); if( !r_lockcull->integer ) { VectorCopy( RI.vieworg, RI.cullorigin ); VectorCopy( RI.vforward, RI.cull_vforward ); VectorCopy( RI.vright, RI.cull_vright ); VectorCopy( RI.vup, RI.cull_vup ); } R_AnimateLight(); R_RunViewmodelEvents(); // sort opaque entities by model type to avoid drawing model shadows under alpha-surfaces qsort( tr.solid_entities, tr.num_solid_entities, sizeof( cl_entity_t* ), R_SolidEntityCompare ); if( !gl_nosort->integer ) { // sort translucents entities by rendermode and distance qsort( tr.trans_entities, tr.num_trans_entities, sizeof( cl_entity_t* ), R_TransEntityCompare ); } // current viewleaf if( RI.drawWorld ) { RI.waveHeight = cl.refdef.movevars->waveHeight * 2.0f; // set global waveheight RI.isSkyVisible = false; // unknown at this moment if(!( RI.params & RP_OLDVIEWLEAF )) R_FindViewLeaf(); } } /* ============= R_SetupGL ============= */ static void R_SetupGL( void ) { if( RI.refdef.waterlevel >= 3 ) { float f; f = sin( cl.time * 0.4f * ( M_PI * 2.7f )); RI.refdef.fov_x += f; RI.refdef.fov_y -= f; } R_SetupModelviewMatrix( &RI.refdef, RI.worldviewMatrix ); R_SetupProjectionMatrix( &RI.refdef, RI.projectionMatrix ); // if( RI.params & RP_MIRRORVIEW ) RI.projectionMatrix[0][0] = -RI.projectionMatrix[0][0]; Matrix4x4_Concat( RI.worldviewProjectionMatrix, RI.projectionMatrix, RI.worldviewMatrix ); if( RP_NORMALPASS( )) { int x, x2, y, y2; // set up viewport (main, playersetup) x = floor( RI.viewport[0] * glState.width / glState.width ); x2 = ceil(( RI.viewport[0] + RI.viewport[2] ) * glState.width / glState.width ); y = floor( glState.height - RI.viewport[1] * glState.height / glState.height ); y2 = ceil( glState.height - ( RI.viewport[1] + RI.viewport[3] ) * glState.height / glState.height ); pglViewport( x, y2, x2 - x, y - y2 ); } else { // envpass, mirrorpass pglViewport( RI.viewport[0], RI.viewport[1], RI.viewport[2], RI.viewport[3] ); } pglMatrixMode( GL_PROJECTION ); GL_LoadMatrix( RI.projectionMatrix ); pglMatrixMode( GL_MODELVIEW ); GL_LoadMatrix( RI.worldviewMatrix ); if( RI.params & RP_CLIPPLANE ) { GLdouble clip[4]; mplane_t *p = &RI.clipPlane; clip[0] = p->normal[0]; clip[1] = p->normal[1]; clip[2] = p->normal[2]; clip[3] = -p->dist; pglClipPlane( GL_CLIP_PLANE0, clip ); pglEnable( GL_CLIP_PLANE0 ); } if( RI.params & RP_FLIPFRONTFACE ) GL_FrontFace( !glState.frontFace ); GL_Cull( GL_FRONT ); pglDisable( GL_BLEND ); pglDisable( GL_ALPHA_TEST ); pglColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); } /* ============= R_EndGL ============= */ static void R_EndGL( void ) { if( RI.params & RP_FLIPFRONTFACE ) GL_FrontFace( !glState.frontFace ); if( RI.params & RP_CLIPPLANE ) pglDisable( GL_CLIP_PLANE0 ); } /* ============= R_RecursiveFindWaterTexture using to find source waterleaf with watertexture to grab fog values from it ============= */ static gltexture_t *R_RecursiveFindWaterTexture( const mnode_t *node, const mnode_t *ignore, qboolean down ) { gltexture_t *tex = NULL; // assure the initial node is not null // we could check it here, but we would rather check it // outside the call to get rid of one additional recursion level ASSERT( node != NULL ); // ignore solid nodes if( node->contents == CONTENTS_SOLID ) return NULL; if( node->contents < 0 ) { mleaf_t *pleaf; msurface_t **mark; int i, c; // ignore non-liquid leaves if( node->contents != CONTENTS_WATER && node->contents != CONTENTS_LAVA && node->contents != CONTENTS_SLIME ) return NULL; // find texture pleaf = (mleaf_t *)node; mark = pleaf->firstmarksurface; c = pleaf->nummarksurfaces; for( i = 0; i < c; i++, mark++ ) { if( (*mark)->flags & SURF_DRAWTURB && (*mark)->texinfo && (*mark)->texinfo->texture ) return R_GetTexture( (*mark)->texinfo->texture->gl_texturenum ); } // texture not found return NULL; } // this is a regular node // traverse children if( node->children[0] && ( node->children[0] != ignore )) { tex = R_RecursiveFindWaterTexture( node->children[0], node, true ); if( tex ) return tex; } if( node->children[1] && ( node->children[1] != ignore )) { tex = R_RecursiveFindWaterTexture( node->children[1], node, true ); if( tex ) return tex; } // for down recursion, return immediately if( down ) return NULL; // texture not found, step up if any if( node->parent ) return R_RecursiveFindWaterTexture( node->parent, node, false ); // top-level node, bail out return NULL; } /* ============= R_CheckFog check for underwater fog Using backward recursion to find waterline leaf from underwater leaf (idea: XaeroX) ============= */ static void R_CheckFog( void ) { cl_entity_t *ent; gltexture_t *tex; int i, cnt, count; RI.fogEnabled = false; if( RI.refdef.waterlevel < 2 || !RI.drawWorld || !r_viewleaf ) return; ent = CL_GetWaterEntity( RI.vieworg ); if( ent && ent->model && ent->model->type == mod_brush && ent->curstate.skin < 0 ) cnt = ent->curstate.skin; else cnt = r_viewleaf->contents; if( IsLiquidContents( RI.cached_contents ) && !IsLiquidContents( cnt )) { RI.cached_contents = CONTENTS_EMPTY; return; } if( RI.refdef.waterlevel < 3 ) return; if( !IsLiquidContents( RI.cached_contents ) && IsLiquidContents( cnt )) { tex = NULL; // check for water texture if( ent && ent->model && ent->model->type == mod_brush ) { msurface_t *surf; count = ent->model->nummodelsurfaces; for( i = 0, surf = &ent->model->surfaces[ent->model->firstmodelsurface]; i < count; i++, surf++ ) { if( surf->flags & SURF_DRAWTURB && surf->texinfo && surf->texinfo->texture ) { tex = R_GetTexture( surf->texinfo->texture->gl_texturenum ); RI.cached_contents = ent->curstate.skin; break; } } } else { tex = R_RecursiveFindWaterTexture( r_viewleaf->parent, NULL, false ); if( tex ) RI.cached_contents = r_viewleaf->contents; } if( !tex ) return; // no valid fogs // copy fog params RI.fogColor[0] = tex->fogParams[0] / 255.0f; RI.fogColor[1] = tex->fogParams[1] / 255.0f; RI.fogColor[2] = tex->fogParams[2] / 255.0f; RI.fogDensity = tex->fogParams[3] * 0.000025f; RI.fogStart = RI.fogEnd = 0.0f; RI.fogCustom = false; RI.fogEnabled = true; } else { RI.fogCustom = false; RI.fogEnabled = true; } } /* ============= R_DrawFog ============= */ void R_DrawFog( void ) { if( !RI.fogEnabled || RI.refdef.onlyClientDraw ) return; pglEnable( GL_FOG ); pglFogi( GL_FOG_MODE, GL_EXP ); pglFogf( GL_FOG_DENSITY, RI.fogDensity ); pglFogfv( GL_FOG_COLOR, RI.fogColor ); pglHint( GL_FOG_HINT, GL_NICEST ); } /* ============= R_DrawEntitiesOnList ============= */ void R_DrawEntitiesOnList( void ) { int i; glState.drawTrans = false; // draw the solid submodels fog R_DrawFog (); // first draw solid entities for( i = 0; i < tr.num_solid_entities; i++ ) { if( RI.refdef.onlyClientDraw ) break; RI.currententity = tr.solid_entities[i]; RI.currentmodel = RI.currententity->model; ASSERT( RI.currententity != NULL ); ASSERT( RI.currententity->model != NULL ); switch( RI.currentmodel->type ) { case mod_brush: R_DrawBrushModel( RI.currententity ); break; case mod_studio: R_DrawStudioModel( RI.currententity ); break; case mod_sprite: R_DrawSpriteModel( RI.currententity ); break; default: break; } } if( !RI.refdef.onlyClientDraw ) { CL_DrawBeams( false ); } if( RI.drawWorld ) clgame.dllFuncs.pfnDrawNormalTriangles(); // NOTE: some mods with custom renderer may generate glErrors // so we clear it here while( pglGetError() != GL_NO_ERROR ); // don't fogging translucent surfaces if( !RI.fogCustom ) pglDisable( GL_FOG ); pglDepthMask( GL_FALSE ); glState.drawTrans = true; // then draw translucent entities for( i = 0; i < tr.num_trans_entities; i++ ) { if( RI.refdef.onlyClientDraw ) break; RI.currententity = tr.trans_entities[i]; RI.currentmodel = RI.currententity->model; ASSERT( RI.currententity != NULL ); ASSERT( RI.currententity->model != NULL ); switch( RI.currentmodel->type ) { case mod_brush: R_DrawBrushModel( RI.currententity ); break; case mod_studio: R_DrawStudioModel( RI.currententity ); break; case mod_sprite: R_DrawSpriteModel( RI.currententity ); break; default: break; } } if( RI.drawWorld ) clgame.dllFuncs.pfnDrawTransparentTriangles (); if( !RI.refdef.onlyClientDraw ) { CL_DrawBeams( true ); CL_DrawParticles(); } // NOTE: some mods with custom renderer may generate glErrors // so we clear it here while( pglGetError() != GL_NO_ERROR ); glState.drawTrans = false; pglDepthMask( GL_TRUE ); pglDisable( GL_BLEND ); // Trinity Render issues R_DrawViewModel(); CL_ExtraUpdate(); } /* ================ R_RenderScene RI.refdef must be set before the first call ================ */ void R_RenderScene( const ref_params_t *fd ) { RI.refdef = *fd; if( !cl.worldmodel && RI.drawWorld ) Host_Error( "R_RenderView: NULL worldmodel\n" ); R_PushDlights(); R_SetupFrame(); R_SetupFrustum(); R_SetupGL(); R_Clear( ~0 ); R_MarkLeaves(); R_CheckFog(); R_DrawWorld(); CL_ExtraUpdate (); // don't let sound get messed up if going slow R_DrawEntitiesOnList(); R_DrawWaterSurfaces(); R_EndGL(); } /* =============== R_BeginFrame =============== */ void R_BeginFrame( qboolean clearScene ) { glConfig.softwareGammaUpdate = false; // in case of possible fails if(( gl_clear->integer || gl_overview->integer ) && clearScene && cls.state != ca_cinematic ) { pglClear( GL_COLOR_BUFFER_BIT ); } // update gamma if( vid_gamma->modified ) { if( glConfig.deviceSupportsGamma ) { SCR_RebuildGammaTable(); GL_UpdateGammaRamp(); vid_gamma->modified = false; } else { glConfig.softwareGammaUpdate = true; BuildGammaTable( vid_gamma->value, vid_texgamma->value ); GL_RebuildLightmaps(); glConfig.softwareGammaUpdate = false; } } R_Set2DMode( true ); // draw buffer stuff pglDrawBuffer( GL_BACK ); // texturemode stuff // update texture parameters if( gl_texturemode->modified || gl_texture_anisotropy->modified || gl_texture_lodbias ->modified ) R_SetTextureParameters(); // swapinterval stuff GL_UpdateSwapInterval(); CL_ExtraUpdate (); } /* =============== R_RenderFrame =============== */ void R_RenderFrame( const ref_params_t *fd, qboolean drawWorld ) { if( r_norefresh->integer ) return; tr.realframecount++; if( RI.drawOrtho != gl_overview->integer ) tr.fResetVis = true; // completely override rendering if( clgame.drawFuncs.GL_RenderFrame != NULL ) { if( clgame.drawFuncs.GL_RenderFrame( fd, drawWorld )) { RI.drawWorld = drawWorld; tr.fResetVis = true; return; } } if( drawWorld ) r_lastRefdef = *fd; RI.params = RP_NONE; RI.farClip = 0; RI.clipFlags = 15; RI.drawWorld = drawWorld; RI.thirdPerson = cl.thirdperson; RI.drawOrtho = (RI.drawWorld) ? gl_overview->integer : 0; GL_BackendStartFrame(); if( !r_lockcull->integer ) VectorCopy( fd->vieworg, RI.cullorigin ); VectorCopy( fd->vieworg, RI.pvsorigin ); // setup viewport RI.viewport[0] = fd->viewport[0]; RI.viewport[1] = fd->viewport[1]; RI.viewport[2] = fd->viewport[2]; RI.viewport[3] = fd->viewport[3]; if( gl_finish->integer && drawWorld ) pglFinish(); if( gl_allow_mirrors->integer ) { // render mirrors R_FindMirrors( fd ); R_DrawMirrors (); } R_RenderScene( fd ); GL_BackendEndFrame(); } /* =============== R_EndFrame =============== */ void R_EndFrame( void ) { // flush any remaining 2D bits R_Set2DMode( false ); #ifdef __ANDROID__ Android_DrawControls(); #endif #ifdef XASH_SDL SDL_GL_SwapWindow(host.hWnd); #elif defined __ANDROID__ // For direct android backend Android_SwapBuffers(); #endif } /* =============== R_DrawCubemapView =============== */ void R_DrawCubemapView( const vec3_t origin, const vec3_t angles, int size ) { ref_params_t *fd; if( clgame.drawFuncs.R_DrawCubemapView != NULL ) { if( clgame.drawFuncs.R_DrawCubemapView( origin, angles, size )) return; } fd = &RI.refdef; *fd = r_lastRefdef; fd->time = 0; fd->viewport[0] = 0; fd->viewport[1] = 0; fd->viewport[2] = size; fd->viewport[3] = size; fd->fov_x = 90; fd->fov_y = 90; VectorCopy( origin, fd->vieworg ); VectorCopy( angles, fd->viewangles ); VectorCopy( fd->vieworg, RI.pvsorigin ); // setup viewport RI.viewport[0] = fd->viewport[0]; RI.viewport[1] = fd->viewport[1]; RI.viewport[2] = fd->viewport[2]; RI.viewport[3] = fd->viewport[3]; R_RenderScene( fd ); r_oldviewleaf = r_viewleaf = NULL; // force markleafs next frame } static int GL_RenderGetParm( int parm, int arg ) { gltexture_t *glt; switch( parm ) { case PARM_TEX_WIDTH: glt = R_GetTexture( arg ); return glt->width; case PARM_TEX_HEIGHT: glt = R_GetTexture( arg ); return glt->height; case PARM_TEX_SRC_WIDTH: glt = R_GetTexture( arg ); return glt->srcWidth; case PARM_TEX_SRC_HEIGHT: glt = R_GetTexture( arg ); return glt->srcHeight; case PARM_TEX_GLFORMAT: glt = R_GetTexture( arg ); return glt->format; case PARM_TEX_SKYBOX: ASSERT( arg >= 0 && arg < 6 ); return tr.skyboxTextures[arg]; case PARM_TEX_SKYTEXNUM: return tr.skytexturenum; case PARM_TEX_LIGHTMAP: ASSERT( arg >= 0 && arg < MAX_LIGHTMAPS ); return tr.lightmapTextures[arg]; case PARM_SKY_SPHERE: return world.sky_sphere; case PARM_WORLD_VERSION: if( cls.state != ca_active ) return bmodel_version; return world.version; case PARM_WIDESCREEN: return glState.wideScreen; case PARM_FULLSCREEN: return glState.fullScreen; case PARM_SCREEN_WIDTH: return glState.width; case PARM_SCREEN_HEIGHT: return glState.height; case PARM_MAP_HAS_MIRRORS: return world.has_mirrors; case PARM_CLIENT_INGAME: return CL_IsInGame(); case PARM_MAX_ENTITIES: return clgame.maxEntities; case PARM_TEX_TARGET: glt = R_GetTexture( arg ); return glt->target; case PARM_TEX_TEXNUM: glt = R_GetTexture( arg ); return glt->texnum; case PARM_TEX_FLAGS: glt = R_GetTexture( arg ); return glt->flags; case PARM_FEATURES: return host.features; case PARM_ACTIVE_TMU: return glState.activeTMU; case PARM_TEX_CACHEFRAME: glt = R_GetTexture( arg ); return glt->cacheframe; case PARM_MAP_HAS_DELUXE: return (world.deluxedata != NULL); case PARM_TEX_TYPE: glt = R_GetTexture( arg ); return glt->texType; case PARM_CACHEFRAME: return world.load_sequence; case PARM_MAX_IMAGE_UNITS: return GL_MaxTextureUnits(); case PARM_CLIENT_ACTIVE: return (cls.state == ca_active); case PARM_REBUILD_GAMMA: return glConfig.softwareGammaUpdate; } return 0; } static void R_GetDetailScaleForTexture( int texture, float *xScale, float *yScale ) { gltexture_t *glt = R_GetTexture( texture ); if( xScale ) *xScale = glt->xscale; if( yScale ) *yScale = glt->yscale; } static void R_GetExtraParmsForTexture( int texture, byte *red, byte *green, byte *blue, byte *density ) { gltexture_t *glt = R_GetTexture( texture ); if( red ) *red = glt->fogParams[0]; if( green ) *green = glt->fogParams[1]; if( blue ) *blue = glt->fogParams[2]; if( density ) *density = glt->fogParams[3]; } static void GL_TextureUpdateCache( unsigned int texture ) { gltexture_t *glt = R_GetTexture( texture ); if( !glt || !glt->texnum ) return; glt->cacheframe = world.load_sequence; } /* ================= R_EnvShot ================= */ static void R_EnvShot( const float *vieworg, const char *name, int skyshot, int shotsize ) { static vec3_t viewPoint; if( !name ) { MsgDev( D_ERROR, "R_%sShot: bad name\n", skyshot ? "Sky" : "Env" ); return; } if( cls.scrshot_action != scrshot_inactive ) { if( cls.scrshot_action != scrshot_skyshot && cls.scrshot_action != scrshot_envshot ) MsgDev( D_ERROR, "R_%sShot: subsystem is busy, try later.\n", skyshot ? "Sky" : "Env" ); return; } cls.envshot_vieworg = NULL; // use client view Q_strncpy( cls.shotname, name, sizeof( cls.shotname )); if( vieworg ) { // make sure what viewpoint don't temporare VectorCopy( vieworg, viewPoint ); cls.envshot_vieworg = viewPoint; cls.envshot_disable_vis = true; } // make request for envshot if( skyshot ) cls.scrshot_action = scrshot_skyshot; else cls.scrshot_action = scrshot_envshot; // catch negative values cls.envshot_viewsize = max( 0, shotsize ); } static void R_SetCurrentEntity( cl_entity_t *ent ) { RI.currententity = ent; // set model also if( RI.currententity != NULL ) { RI.currentmodel = RI.currententity->model; } } static void R_SetCurrentModel( model_t *mod ) { RI.currentmodel = mod; } static lightstyle_t *CL_GetLightStyle( int number ) { ASSERT( number >= 0 && number < MAX_LIGHTSTYLES ); return &cl.lightstyles[number]; } static dlight_t *CL_GetDynamicLight( int number ) { ASSERT( number >= 0 && number < MAX_DLIGHTS ); return &cl_dlights[number]; } static dlight_t *CL_GetEntityLight( int number ) { ASSERT( number >= 0 && number < MAX_ELIGHTS ); return &cl_elights[number]; } static void CL_GetBeamChains( BEAM ***active_beams, BEAM ***free_beams, particle_t ***free_trails ) { *active_beams = &cl_active_beams; *free_beams = &cl_free_beams; *free_trails = &cl_free_trails; } static void GL_SetWorldviewProjectionMatrix( const float *glmatrix ) { if( !glmatrix ) return; Matrix4x4_FromArrayFloatGL( RI.worldviewProjectionMatrix, glmatrix ); } static const char *GL_TextureName( unsigned int texnum ) { return R_GetTexture( texnum )->name; } const byte *GL_TextureData( unsigned int texnum ) { rgbdata_t *pic = R_GetTexture( texnum )->original; if( pic != NULL ) return pic->buffer; return NULL; } static int GL_LoadTextureNoFilter( const char *name, const byte *buf, size_t size, int flags ) { return GL_LoadTexture( name, buf, size, flags, NULL ); } static const ref_overview_t *GL_GetOverviewParms( void ) { return &clgame.overView; } static void *R_Mem_Alloc( size_t cb, const char *filename, const int fileline ) { return _Mem_Alloc( cls.mempool, cb, filename, fileline ); } static void R_Mem_Free( void *mem, const char *filename, const int fileline ) { _Mem_Free( mem, filename, fileline ); } /* ========= pfnGetFilesList ========= */ static char **pfnGetFilesList( const char *pattern, int *numFiles, int gamedironly ) { static search_t *t = NULL; if( t ) Mem_Free( t ); // release prev search t = FS_Search( pattern, true, gamedironly ); if( !t ) { if( numFiles ) *numFiles = 0; return NULL; } if( numFiles ) *numFiles = t->numfilenames; return t->filenames; } static render_api_t gRenderAPI = { GL_RenderGetParm, R_GetDetailScaleForTexture, R_GetExtraParmsForTexture, CL_GetLightStyle, CL_GetDynamicLight, CL_GetEntityLight, TextureToTexGamma, CL_GetBeamChains, R_SetCurrentEntity, R_SetCurrentModel, GL_SetWorldviewProjectionMatrix, R_StoreEfrags, GL_FindTexture, GL_TextureName, GL_TextureData, GL_LoadTextureNoFilter, GL_CreateTexture, GL_SetTextureType, GL_TextureUpdateCache, GL_FreeTexture, DrawSingleDecal, R_DecalSetupVerts, R_EntityRemoveDecals, AVI_LoadVideoNoSound, AVI_GetVideoInfo, AVI_GetVideoFrameNumber, AVI_GetVideoFrame, R_UploadStretchRaw, AVI_FreeVideo, AVI_IsActive, GL_Bind, GL_SelectTexture, GL_LoadTexMatrixExt, GL_LoadIdentityTexMatrix, GL_CleanUpTextureUnits, GL_TexGen, GL_TextureTarget, GL_SetTexCoordArrayMode, NULL, NULL, NULL, NULL, CL_DrawParticlesExternal, R_EnvShot, COM_CompareFileTime, Host_Error, pfnSPR_LoadExt, Mod_TesselatePolygon, R_StudioGetTexture, GL_GetOverviewParms, S_FadeMusicVolume, COM_SetRandomSeed, R_Mem_Alloc, R_Mem_Free, pfnGetFilesList, }; /* =============== R_InitRenderAPI Initialize client external rendering =============== */ qboolean R_InitRenderAPI( void ) { // make sure what render functions is cleared Q_memset( &clgame.drawFuncs, 0, sizeof( clgame.drawFuncs )); if( clgame.dllFuncs.pfnGetRenderInterface ) { if( clgame.dllFuncs.pfnGetRenderInterface( CL_RENDER_INTERFACE_VERSION, &gRenderAPI, &clgame.drawFuncs )) { MsgDev( D_AICONSOLE, "CL_LoadProgs: ^2initailized extended RenderAPI ^7ver. %i\n", CL_RENDER_INTERFACE_VERSION ); return true; } // make sure what render functions is cleared Q_memset( &clgame.drawFuncs, 0, sizeof( clgame.drawFuncs )); return false; // just tell user about problems } // render interface is missed return true; }
UCyborg/xash3d
engine/client/gl_rmain.c
C
gpl-3.0
39,951
/* * TAP-Win32 -- A kernel driver to provide virtual tap device functionality * on Windows. Originally derived from the CIPE-Win32 * project by Damion K. Wilson, with extensive modifications by * James Yonan. * * All source code which derives from the CIPE-Win32 project is * Copyright (C) Damion K. Wilson, 2003, and is released under the * GPL version 2 (see below). * * All other source code is Copyright (C) James Yonan, 2003-2004, * and is released under the GPL version 2 (see below). * * 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 the file COPYING included with this * distribution); if not, see <http://www.gnu.org/licenses/>. */ #include "tap.h" #include "qemu-common.h" #include "net.h" #include "sysemu.h" #include "qemu-error.h" #include <stdio.h> #include <windows.h> #include <winioctl.h> //============= // TAP IOCTLs //============= #define TAP_CONTROL_CODE(request,method) \ CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS) #define TAP_IOCTL_GET_MAC TAP_CONTROL_CODE (1, METHOD_BUFFERED) #define TAP_IOCTL_GET_VERSION TAP_CONTROL_CODE (2, METHOD_BUFFERED) #define TAP_IOCTL_GET_MTU TAP_CONTROL_CODE (3, METHOD_BUFFERED) #define TAP_IOCTL_GET_INFO TAP_CONTROL_CODE (4, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_POINT_TO_POINT TAP_CONTROL_CODE (5, METHOD_BUFFERED) #define TAP_IOCTL_SET_MEDIA_STATUS TAP_CONTROL_CODE (6, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_DHCP_MASQ TAP_CONTROL_CODE (7, METHOD_BUFFERED) #define TAP_IOCTL_GET_LOG_LINE TAP_CONTROL_CODE (8, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_DHCP_SET_OPT TAP_CONTROL_CODE (9, METHOD_BUFFERED) //================= // Registry keys //================= #define ADAPTER_KEY "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}" #define NETWORK_CONNECTIONS_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}" //====================== // Filesystem prefixes //====================== #define USERMODEDEVICEDIR "\\\\.\\Global\\" #define TAPSUFFIX ".tap" //====================== // Compile time configuration //====================== //#define DEBUG_TAP_WIN32 #define TUN_ASYNCHRONOUS_WRITES 1 #define TUN_BUFFER_SIZE 1560 #define TUN_MAX_BUFFER_COUNT 32 /* * The data member "buffer" must be the first element in the tun_buffer * structure. See the function, tap_win32_free_buffer. */ typedef struct tun_buffer_s { unsigned char buffer [TUN_BUFFER_SIZE]; unsigned long read_size; struct tun_buffer_s* next; } tun_buffer_t; typedef struct tap_win32_overlapped { HANDLE handle; HANDLE read_event; HANDLE write_event; HANDLE output_queue_semaphore; HANDLE free_list_semaphore; HANDLE tap_semaphore; CRITICAL_SECTION output_queue_cs; CRITICAL_SECTION free_list_cs; OVERLAPPED read_overlapped; OVERLAPPED write_overlapped; tun_buffer_t buffers[TUN_MAX_BUFFER_COUNT]; tun_buffer_t* free_list; tun_buffer_t* output_queue_front; tun_buffer_t* output_queue_back; } tap_win32_overlapped_t; static tap_win32_overlapped_t tap_overlapped; static tun_buffer_t* get_buffer_from_free_list(tap_win32_overlapped_t* const overlapped) { tun_buffer_t* buffer = NULL; WaitForSingleObject(overlapped->free_list_semaphore, INFINITE); EnterCriticalSection(&overlapped->free_list_cs); buffer = overlapped->free_list; // assert(buffer != NULL); overlapped->free_list = buffer->next; LeaveCriticalSection(&overlapped->free_list_cs); buffer->next = NULL; return buffer; } static void put_buffer_on_free_list(tap_win32_overlapped_t* const overlapped, tun_buffer_t* const buffer) { EnterCriticalSection(&overlapped->free_list_cs); buffer->next = overlapped->free_list; overlapped->free_list = buffer; LeaveCriticalSection(&overlapped->free_list_cs); ReleaseSemaphore(overlapped->free_list_semaphore, 1, NULL); } static tun_buffer_t* get_buffer_from_output_queue(tap_win32_overlapped_t* const overlapped, const int block) { tun_buffer_t* buffer = NULL; DWORD result, timeout = block ? INFINITE : 0L; // Non-blocking call result = WaitForSingleObject(overlapped->output_queue_semaphore, timeout); switch (result) { // The semaphore object was signaled. case WAIT_OBJECT_0: EnterCriticalSection(&overlapped->output_queue_cs); buffer = overlapped->output_queue_front; overlapped->output_queue_front = buffer->next; if(overlapped->output_queue_front == NULL) { overlapped->output_queue_back = NULL; } LeaveCriticalSection(&overlapped->output_queue_cs); break; // Semaphore was nonsignaled, so a time-out occurred. case WAIT_TIMEOUT: // Cannot open another window. break; } return buffer; } static tun_buffer_t* get_buffer_from_output_queue_immediate (tap_win32_overlapped_t* const overlapped) { return get_buffer_from_output_queue(overlapped, 0); } static void put_buffer_on_output_queue(tap_win32_overlapped_t* const overlapped, tun_buffer_t* const buffer) { EnterCriticalSection(&overlapped->output_queue_cs); if(overlapped->output_queue_front == NULL && overlapped->output_queue_back == NULL) { overlapped->output_queue_front = overlapped->output_queue_back = buffer; } else { buffer->next = NULL; overlapped->output_queue_back->next = buffer; overlapped->output_queue_back = buffer; } LeaveCriticalSection(&overlapped->output_queue_cs); ReleaseSemaphore(overlapped->output_queue_semaphore, 1, NULL); } static int is_tap_win32_dev(const char *guid) { HKEY netcard_key; LONG status; DWORD len; int i = 0; status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, ADAPTER_KEY, 0, KEY_READ, &netcard_key); if (status != ERROR_SUCCESS) { return FALSE; } for (;;) { char enum_name[256]; char unit_string[256]; HKEY unit_key; char component_id_string[] = "ComponentId"; char component_id[256]; char net_cfg_instance_id_string[] = "NetCfgInstanceId"; char net_cfg_instance_id[256]; DWORD data_type; len = sizeof (enum_name); status = RegEnumKeyEx( netcard_key, i, enum_name, &len, NULL, NULL, NULL, NULL); if (status == ERROR_NO_MORE_ITEMS) break; else if (status != ERROR_SUCCESS) { return FALSE; } snprintf (unit_string, sizeof(unit_string), "%s\\%s", ADAPTER_KEY, enum_name); status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, unit_string, 0, KEY_READ, &unit_key); if (status != ERROR_SUCCESS) { return FALSE; } else { len = sizeof (component_id); status = RegQueryValueEx( unit_key, component_id_string, NULL, &data_type, (LPBYTE)component_id, &len); if (!(status != ERROR_SUCCESS || data_type != REG_SZ)) { len = sizeof (net_cfg_instance_id); status = RegQueryValueEx( unit_key, net_cfg_instance_id_string, NULL, &data_type, (LPBYTE)net_cfg_instance_id, &len); if (status == ERROR_SUCCESS && data_type == REG_SZ) { if (/* !strcmp (component_id, TAP_COMPONENT_ID) &&*/ !strcmp (net_cfg_instance_id, guid)) { RegCloseKey (unit_key); RegCloseKey (netcard_key); return TRUE; } } } RegCloseKey (unit_key); } ++i; } RegCloseKey (netcard_key); return FALSE; } static int get_device_guid( char *name, int name_size, char *actual_name, int actual_name_size) { LONG status; HKEY control_net_key; DWORD len; int i = 0; int stop = 0; status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_READ, &control_net_key); if (status != ERROR_SUCCESS) { return -1; } while (!stop) { char enum_name[256]; char connection_string[256]; HKEY connection_key; char name_data[256]; DWORD name_type; const char name_string[] = "Name"; len = sizeof (enum_name); status = RegEnumKeyEx( control_net_key, i, enum_name, &len, NULL, NULL, NULL, NULL); if (status == ERROR_NO_MORE_ITEMS) break; else if (status != ERROR_SUCCESS) { return -1; } snprintf(connection_string, sizeof(connection_string), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, enum_name); status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, connection_string, 0, KEY_READ, &connection_key); if (status == ERROR_SUCCESS) { len = sizeof (name_data); status = RegQueryValueEx( connection_key, name_string, NULL, &name_type, (LPBYTE)name_data, &len); if (status != ERROR_SUCCESS || name_type != REG_SZ) { return -1; } else { if (is_tap_win32_dev(enum_name)) { snprintf(name, name_size, "%s", enum_name); if (actual_name) { if (strcmp(actual_name, "") != 0) { if (strcmp(name_data, actual_name) != 0) { RegCloseKey (connection_key); ++i; continue; } } else { snprintf(actual_name, actual_name_size, "%s", name_data); } } stop = 1; } } RegCloseKey (connection_key); } ++i; } RegCloseKey (control_net_key); if (stop == 0) return -1; return 0; } static int tap_win32_set_status(HANDLE handle, int status) { unsigned long len = 0; return DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof (status), &status, sizeof (status), &len, NULL); } static void tap_win32_overlapped_init(tap_win32_overlapped_t* const overlapped, const HANDLE handle) { overlapped->handle = handle; overlapped->read_event = CreateEvent(NULL, FALSE, FALSE, NULL); overlapped->write_event = CreateEvent(NULL, FALSE, FALSE, NULL); overlapped->read_overlapped.Offset = 0; overlapped->read_overlapped.OffsetHigh = 0; overlapped->read_overlapped.hEvent = overlapped->read_event; overlapped->write_overlapped.Offset = 0; overlapped->write_overlapped.OffsetHigh = 0; overlapped->write_overlapped.hEvent = overlapped->write_event; InitializeCriticalSection(&overlapped->output_queue_cs); InitializeCriticalSection(&overlapped->free_list_cs); overlapped->output_queue_semaphore = CreateSemaphore( NULL, // default security attributes 0, // initial count TUN_MAX_BUFFER_COUNT, // maximum count NULL); // unnamed semaphore if(!overlapped->output_queue_semaphore) { fprintf(stderr, "error creating output queue semaphore!\n"); } overlapped->free_list_semaphore = CreateSemaphore( NULL, // default security attributes TUN_MAX_BUFFER_COUNT, // initial count TUN_MAX_BUFFER_COUNT, // maximum count NULL); // unnamed semaphore if(!overlapped->free_list_semaphore) { fprintf(stderr, "error creating free list semaphore!\n"); } overlapped->free_list = overlapped->output_queue_front = overlapped->output_queue_back = NULL; { unsigned index; for(index = 0; index < TUN_MAX_BUFFER_COUNT; index++) { tun_buffer_t* element = &overlapped->buffers[index]; element->next = overlapped->free_list; overlapped->free_list = element; } } /* To count buffers, initially no-signal. */ overlapped->tap_semaphore = CreateSemaphore(NULL, 0, TUN_MAX_BUFFER_COUNT, NULL); if(!overlapped->tap_semaphore) fprintf(stderr, "error creating tap_semaphore.\n"); } static int tap_win32_write(tap_win32_overlapped_t *overlapped, const void *buffer, unsigned long size) { unsigned long write_size; BOOL result; DWORD error; result = GetOverlappedResult( overlapped->handle, &overlapped->write_overlapped, &write_size, FALSE); if (!result && GetLastError() == ERROR_IO_INCOMPLETE) WaitForSingleObject(overlapped->write_event, INFINITE); result = WriteFile(overlapped->handle, buffer, size, &write_size, &overlapped->write_overlapped); if (!result) { switch (error = GetLastError()) { case ERROR_IO_PENDING: #ifndef TUN_ASYNCHRONOUS_WRITES WaitForSingleObject(overlapped->write_event, INFINITE); #endif break; default: return -1; } } return write_size; } static DWORD WINAPI tap_win32_thread_entry(LPVOID param) { tap_win32_overlapped_t *overlapped = (tap_win32_overlapped_t*)param; unsigned long read_size; BOOL result; DWORD dwError; tun_buffer_t* buffer = get_buffer_from_free_list(overlapped); for (;;) { result = ReadFile(overlapped->handle, buffer->buffer, sizeof(buffer->buffer), &read_size, &overlapped->read_overlapped); if (!result) { dwError = GetLastError(); if (dwError == ERROR_IO_PENDING) { WaitForSingleObject(overlapped->read_event, INFINITE); result = GetOverlappedResult( overlapped->handle, &overlapped->read_overlapped, &read_size, FALSE); if (!result) { #ifdef DEBUG_TAP_WIN32 LPVOID lpBuffer; dwError = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpBuffer, 0, NULL ); fprintf(stderr, "Tap-Win32: Error GetOverlappedResult %d - %s\n", dwError, lpBuffer); LocalFree( lpBuffer ); #endif } } else { #ifdef DEBUG_TAP_WIN32 LPVOID lpBuffer; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpBuffer, 0, NULL ); fprintf(stderr, "Tap-Win32: Error ReadFile %d - %s\n", dwError, lpBuffer); LocalFree( lpBuffer ); #endif } } if(read_size > 0) { buffer->read_size = read_size; put_buffer_on_output_queue(overlapped, buffer); ReleaseSemaphore(overlapped->tap_semaphore, 1, NULL); buffer = get_buffer_from_free_list(overlapped); } } return 0; } static int tap_win32_read(tap_win32_overlapped_t *overlapped, uint8_t **pbuf, int max_size) { int size = 0; tun_buffer_t* buffer = get_buffer_from_output_queue_immediate(overlapped); if(buffer != NULL) { *pbuf = buffer->buffer; size = (int)buffer->read_size; if(size > max_size) { size = max_size; } } return size; } static void tap_win32_free_buffer(tap_win32_overlapped_t *overlapped, uint8_t *pbuf) { tun_buffer_t* buffer = (tun_buffer_t*)pbuf; put_buffer_on_free_list(overlapped, buffer); } static int tap_win32_open(tap_win32_overlapped_t **phandle, const char *prefered_name) { char device_path[256]; char device_guid[0x100]; int rc; HANDLE handle; BOOL bret; char name_buffer[0x100] = {0, }; struct { unsigned long major; unsigned long minor; unsigned long debug; } version; DWORD version_len; DWORD idThread; if (prefered_name != NULL) snprintf(name_buffer, sizeof(name_buffer), "%s", prefered_name); rc = get_device_guid(device_guid, sizeof(device_guid), name_buffer, sizeof(name_buffer)); if (rc) return -1; snprintf (device_path, sizeof(device_path), "%s%s%s", USERMODEDEVICEDIR, device_guid, TAPSUFFIX); handle = CreateFile ( device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0 ); if (handle == INVALID_HANDLE_VALUE) { return -1; } bret = DeviceIoControl(handle, TAP_IOCTL_GET_VERSION, &version, sizeof (version), &version, sizeof (version), &version_len, NULL); if (bret == FALSE) { CloseHandle(handle); return -1; } if (!tap_win32_set_status(handle, TRUE)) { return -1; } tap_win32_overlapped_init(&tap_overlapped, handle); *phandle = &tap_overlapped; CreateThread(NULL, 0, tap_win32_thread_entry, (LPVOID)&tap_overlapped, 0, &idThread); return 0; } /********************************************/ typedef struct TAPState { NetClientState nc; tap_win32_overlapped_t *handle; } TAPState; static void tap_cleanup(NetClientState *nc) { TAPState *s = DO_UPCAST(TAPState, nc, nc); qemu_del_wait_object(s->handle->tap_semaphore, NULL, NULL); /* FIXME: need to kill thread and close file handle: tap_win32_close(s); */ } static ssize_t tap_receive(NetClientState *nc, const uint8_t *buf, size_t size) { TAPState *s = DO_UPCAST(TAPState, nc, nc); return tap_win32_write(s->handle, buf, size); } static void tap_win32_send(void *opaque) { TAPState *s = opaque; uint8_t *buf; int max_size = 4096; int size; size = tap_win32_read(s->handle, &buf, max_size); if (size > 0) { qemu_send_packet(&s->nc, buf, size); tap_win32_free_buffer(s->handle, buf); } } static NetClientInfo net_tap_win32_info = { .type = NET_CLIENT_OPTIONS_KIND_TAP, .size = sizeof(TAPState), .receive = tap_receive, .cleanup = tap_cleanup, }; static int tap_win32_init(NetClientState *peer, const char *model, const char *name, const char *ifname) { NetClientState *nc; TAPState *s; tap_win32_overlapped_t *handle; if (tap_win32_open(&handle, ifname) < 0) { printf("tap: Could not open '%s'\n", ifname); return -1; } nc = qemu_new_net_client(&net_tap_win32_info, peer, model, name); s = DO_UPCAST(TAPState, nc, nc); snprintf(s->nc.info_str, sizeof(s->nc.info_str), "tap: ifname=%s", ifname); s->handle = handle; qemu_add_wait_object(s->handle->tap_semaphore, tap_win32_send, s); return 0; } int net_init_tap(const NetClientOptions *opts, const char *name, NetClientState *peer) { const NetdevTapOptions *tap; assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP); tap = opts->tap; if (!tap->has_ifname) { error_report("tap: no interface name"); return -1; } if (tap_win32_init(peer, "tap", name, tap->ifname) == -1) { return -1; } return 0; } int tap_has_ufo(NetClientState *nc) { return 0; } int tap_has_vnet_hdr(NetClientState *nc) { return 0; } int tap_probe_vnet_hdr_len(int fd, int len) { return 0; } void tap_fd_set_vnet_hdr_len(int fd, int len) { } void tap_using_vnet_hdr(NetClientState *nc, int using_vnet_hdr) { } void tap_set_offload(NetClientState *nc, int csum, int tso4, int tso6, int ecn, int ufo) { } struct vhost_net *tap_get_vhost_net(NetClientState *nc) { return NULL; }
SSLAB-HSA/HSAemu
qemu/net/tap-win32.c
C
gpl-3.0
21,663
$(document).ready(function() { $('.fancybox').fancybox(); $(".fancybox-effects-a").fancybox({ helpers: { title : { type : 'outside' }, overlay : { speedOut : 0 } } }); $(".fancybox-effects-b").fancybox({ openEffect : 'none', closeEffect : 'none', helpers : { title : { type : 'over' } } }); $(".fancybox-effects-c").fancybox({ wrapCSS : 'fancybox-custom', closeClick : true, openEffect : 'none', helpers : { title : { type : 'inside' }, overlay : { css : { 'background' : 'rgba(238,238,238,0.85)' } } } }); $(".fancybox-effects-d").fancybox({ padding: 0, openEffect : 'elastic', openSpeed : 150, closeEffect : 'elastic', closeSpeed : 150, closeClick : true, helpers : { overlay : null } }); $('.fancybox-buttons').fancybox({ openEffect : 'none', closeEffect : 'none', prevEffect : 'none', nextEffect : 'none', closeBtn : false, helpers : { title : { type : 'inside' }, buttons : {} }, afterLoad : function() { this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : ''); } }); $('.fancybox-thumbs').fancybox({ prevEffect : 'none', nextEffect : 'none', closeBtn : false, arrows : false, nextClick : true, helpers : { thumbs : { width : 50, height : 50 } } }); $('.fancybox-media') .attr('rel', 'media-gallery') .fancybox({ openEffect : 'none', closeEffect : 'none', prevEffect : 'none', nextEffect : 'none', arrows : false, helpers : { media : {}, buttons : {} } }); $("#fancybox-manual-a").click(function() { $.fancybox.open('1_b.jpg'); }); $("#fancybox-manual-b").click(function() { $.fancybox.open({ href : 'iframe.html', type : 'iframe', padding : 5 }); }); $("#fancybox-manual-c").click(function() { $.fancybox.open([ { href : '1_b.jpg', title : 'My title' }, { href : '2_b.jpg', title : '2nd title' }, { href : '3_b.jpg' } ], { helpers : { thumbs : { width: 75, height: 50 } } }); }); });
ElizavetaKuzmenko/dsm_genres
data/custom.js
JavaScript
gpl-3.0
2,174
/* Copyright 2012-2013, Polyvi Inc. (http://www.xface3.com) This program is distributed under the terms of the GNU General Public License. This file is part of xFace. xFace 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. xFace 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 xFace. If not, see <http://www.gnu.org/licenses/>. */ /** * @module zip */ /** * 该类定义一些常量,用于标识压缩和解压失败的错误信息(Android, iOS, WP8)<br/> * 相关参考: {{#crossLink "Zip"}}{{/crossLink}} * @class ZipError * @static * @platform Android, iOS, WP8 * @since 3.0.0 */ var ZipError = function() { }; /** * 待压缩的文件或文件夹不存在(Android, iOS, WP8) * @property FILE_NOT_EXIST * @type Number * @static * @final * @platform Android, iOS, WP8 * @since 3.0.0 */ ZipError.FILE_NOT_EXIST = 1; /** * 压缩文件出错.(Android, iOS, WP8) * @property COMPRESS_FILE_ERROR * @type Number * @static * @final * @platform Android, iOS, WP8 * @since 3.0.0 */ ZipError.COMPRESS_FILE_ERROR = 2; /** * 解压文件出错.(Android, iOS, WP8) * @property UNZIP_FILE_ERROR * @type Number * @static * @final * @platform Android, iOS, WP8 * @since 3.0.0 */ ZipError.UNZIP_FILE_ERROR = 3; /** * 文件类型错误,不支持的文件类型(Android, iOS, WP8) * @property FILE_TYPE_ERROR * @type Number * @static * @final * @platform Android, iOS, WP8 * @since 3.0.0 */ ZipError.FILE_TYPE_ERROR = 4; /** * 位置错误(Android, iOS, WP8) * @property UNKNOWN_ERR * @type Number * @static * @final * @platform Android, iOS, WP8 * @since 3.0.0 */ ZipError.UNKNOWN_ERR = 5; module.exports = ZipError;
polyvi/xface-extension-zip
www/ZipError.js
JavaScript
gpl-3.0
2,136
#!/bin/bash nodejs server.js > ../log_server & disown nodejs http.js > ../log_http & disown nodejs notif.js > ../log_notif & disown
vladvelici/trainspotter
startall.sh
Shell
gpl-3.0
133
Teaching Examples ================= A collection of programming scenarios to learn from. Synopsis ------- As I've been coding through the years I've noticed the same repeating questions from new and old coders. There are specific questions and a lack of understanding of key concepts that span programming languages, education, or experience levels. I'm writing these examples as a way to express these concepts and answer some of the questions. Perhaps other's can learn from them. I hope so. I'm approaching this from a concept basis. I hold that most concepts overlap languages, and with that in mind, I will be writing the examples in multiple languages. I'll naturally start from the ones I love working in, but eventually I hope to circle back around and fill the gaps with other practical languages. I'd be glad to see other developers filling in the gaps with their preferred langauges. Contributions are very welcome! Concepts so far --------------- [Routing](https://github.com/m3talsmith/teaching-examples/tree/master/routing)
m3talsmith/teaching-examples
README.md
Markdown
gpl-3.0
1,044
<?php namespace App\Admin\Controllers; use App\GrupoEvento; use App\Categoria; use App\TorneioTemplate; use App\Http\Controllers\Controller; use Encore\Admin\Controllers\HasResourceActions; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Layout\Content; use Encore\Admin\Show; class GrupoEventoController extends Controller { use HasResourceActions; /** * Index interface. * * @param Content $content * @return Content */ public function index(Content $content) { return $content ->header('Listar Grupos de Evento') ->description('description') ->body($this->grid()); } /** * Show interface. * * @param mixed $id * @param Content $content * @return Content */ public function show($id, Content $content) { return $content ->header('Mostrar Grupo de Evento') ->description('description') ->body($this->detail($id)); } /** * Edit interface. * * @param mixed $id * @param Content $content * @return Content */ public function edit($id, Content $content) { return $content ->header('Editar Grupo de Evento') ->description('description') ->body($this->form()->edit($id)); } /** * Create interface. * * @param Content $content * @return Content */ public function create(Content $content) { return $content ->header('Criar Grupo de Evento') ->description('description') ->body($this->form()); } /** * Make a grid builder. * * @return Grid */ protected function grid() { $grid = new Grid(new GrupoEvento); $grid->id('#'); $grid->name('Nome do Grupo de Evento'); return $grid; } /** * Make a show builder. * * @param mixed $id * @return Show */ protected function detail($id) { $show = new Show(GrupoEvento::findOrFail($id)); return $show; } /** * Make a form builder. * * @return Form */ protected function form() { $form = new Form(new GrupoEvento); $form->tab('Informações Básicas', function ($form) { $form->text('name', 'Nome do Grupo de Evento'); })->tab('Categorias', function ($form) { $form->hasMany('categorias', function ($form) { $form->select('categoria_id', 'Categoria')->options(Categoria::all()->pluck('name', 'id')); }); })->tab('Template de Torneio', function ($form) { $form->hasMany('torneios', function ($form) { $form->select('torneio_template_id', 'Template de Torneio')->options(TorneioTemplate::all()->pluck('name', 'id')); }); }); return $form; } }
XadrezSuico/XadrezSuico
app/Admin/Controllers/GrupoEventoController.php
PHP
gpl-3.0
2,955
#ifndef CYGONCE_HAL_VAR_INTR_H #define CYGONCE_HAL_VAR_INTR_H //========================================================================== // // imp_intr.h // // RM7000 Interrupt and clock support // //========================================================================== //####ECOSGPLCOPYRIGHTBEGIN#### // ------------------------------------------- // This file is part of eCos, the Embedded Configurable Operating System. // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc. // // eCos 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. // // eCos 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 eCos; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. // // As a special exception, if other files instantiate templates or use macros // or inline functions from this file, or you compile this file and link it // with other works to produce a work based on this file, this file does not // by itself cause the resulting work to be covered by the GNU General Public // License. However the source code for this file must still be made available // in accordance with section (3) of the GNU General Public License. // // This exception does not invalidate any other reasons why a work based on // this file might be covered by the GNU General Public License. // // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc. // at http://sources.redhat.com/ecos/ecos-license/ // ------------------------------------------- //####ECOSGPLCOPYRIGHTEND#### //========================================================================== //#####DESCRIPTIONBEGIN#### // // Author(s): jskov // Contributors: jskov // Date: 2000-05-09 // Purpose: RM7000 Interrupt support // Description: The macros defined here provide the HAL APIs for handling // interrupts and the clock for variants of the RM7000 MIPS // architecture. // // Usage: // #include <cyg/hal/var_intr.h> // ... // // //####DESCRIPTIONEND#### // //========================================================================== #include <pkgconf/hal.h> #include <cyg/hal/plf_intr.h> //-------------------------------------------------------------------------- // Interrupt controller information #ifndef CYGHWR_HAL_INTERRUPT_CONTROLLER_ACCESS_DEFINED #define HAL_INTERRUPT_MASK( _vector_ ) \ CYG_MACRO_START \ if( (_vector_) <= CYGNUM_HAL_INTERRUPT_COMPARE ) \ { \ asm volatile ( \ "mfc0 $3,$12\n" \ "la $2,0x00000400\n" \ "sllv $2,$2,%0\n" \ "nor $2,$2,$0\n" \ "and $3,$3,$2\n" \ "mtc0 $3,$12\n" \ "nop; nop; nop\n" \ : \ : "r"(_vector_) \ : "$2", "$3" \ ); \ } \ else \ { \ /* int 6:9 are masked in the Interrupt Control register */ \ asm volatile ( \ "cfc0 $3,$20\n" \ "la $2,0x00000004\n" \ "sllv $2,$2,%0\n" \ "nor $2,$2,$0\n" \ "and $3,$3,$2\n" \ "ctc0 $3,$20\n" \ "nop; nop; nop\n" \ : \ : "r"((_vector_) ) \ : "$2", "$3" \ ); \ } \ CYG_MACRO_END #define HAL_INTERRUPT_UNMASK( _vector_ ) \ CYG_MACRO_START \ if( (_vector_) <= CYGNUM_HAL_INTERRUPT_COMPARE ) \ { \ asm volatile ( \ "mfc0 $3,$12\n" \ "la $2,0x00000400\n" \ "sllv $2,$2,%0\n" \ "or $3,$3,$2\n" \ "mtc0 $3,$12\n" \ "nop; nop; nop\n" \ : \ : "r"(_vector_) \ : "$2", "$3" \ ); \ } \ else \ { \ /* int 6:9 are masked in the Interrupt Control register */ \ asm volatile ( \ "cfc0 $3,$20\n" \ "la $2,0x00000004\n" \ "sllv $2,$2,%0\n" \ "or $3,$3,$2\n" \ "ctc0 $3,$20\n" \ "nop; nop; nop\n" \ : \ : "r"((_vector_) ) \ : "$2", "$3" \ ); \ } \ CYG_MACRO_END #define HAL_INTERRUPT_ACKNOWLEDGE( _vector_ ) \ CYG_MACRO_START \ /* All 10 interrupts have pending bits in the cause register */ \ cyg_uint32 _srvector_ = _vector_; \ asm volatile ( \ "mfc0 $3,$13\n" \ "la $2,0x00000400\n" \ "sllv $2,$2,%0\n" \ "nor $2,$2,$0\n" \ "and $3,$3,$2\n" \ "mtc0 $3,$13\n" \ "nop; nop; nop\n" \ : \ : "r"(_srvector_) \ : "$2", "$3" \ ); \ CYG_MACRO_END #define HAL_INTERRUPT_CONFIGURE( _vector_, _level_, _up_ ) #define HAL_INTERRUPT_SET_LEVEL( _vector_, _level_ ) #define CYGHWR_HAL_INTERRUPT_CONTROLLER_ACCESS_DEFINED #endif //-------------------------------------------------------------------------- // Interrupt vectors. // Vectors and handling of these are defined in platform HALs since the // CPU itself does not have a builtin interrupt controller. //-------------------------------------------------------------------------- // Clock control // This is handled by the default code //-------------------------------------------------------------------------- #endif // ifndef CYGONCE_HAL_VAR_INTR_H // End of var_intr.h
luebbers/reconos
core/ecos/ecos-patched/ecos/packages/hal/mips/rm7000/var/current/include/var_intr.h
C
gpl-3.0
9,673
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - ROBINSON, Louise Sarah</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>ROBINSON, Louise Sarah<sup><small></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> ROBINSON, Louise Sarah <a href="#sref1a">1a</a> </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I17833</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">female</td> </tr> <tr> <td class="ColumnAttribute">Age at Death</td> <td class="ColumnValue">81 years, 9 months, 12 days</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/5/2/d15f608f05c4f71937f88f0e325.html" title="Birth"> Birth <span class="grampsid"> [E17967]</span> </a> </td> <td class="ColumnDate">1909</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> <a href="../../../evt/4/e/d15f608f0614eb244ff780af7e4.html" title="Death"> Death <span class="grampsid"> [E17968]</span> </a> </td> <td class="ColumnDate">1990-10-13</td> <td class="ColumnPlace"> <a href="../../../plc/2/3/d15f608f06554848fe2b5d9b632.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">&nbsp</td> <td class="ColumnAttribute">&nbsp</td> <td class="ColumnValue"><a href="../../../fam/a/d/d15f608f0357f7ca0a964b7bfda.html" title="Family of TREVAN, Victor Grenville and ROBINSON, Louise Sarah">Family of TREVAN, Victor Grenville and ROBINSON, Louise Sarah<span class="grampsid"> [F5734]</span></a></td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Unknown</td> <td class="ColumnAttribute">Partner</td> <td class="ColumnValue"> <a href="../../../ppl/0/0/d15f608efff1614baa2f615e400.html">TREVAN, Victor Grenville<span class="grampsid"> [I17832]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Attributes</td> <td class="ColumnValue"> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">C8AFAFCD581DA14A8F04F590F3E80AC5157E</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </td> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">404A2EC6111ABE4CB71BD358A3CB5ED75389</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <ol> <li class="thisperson"> ROBINSON, Louise Sarah <ol class="spouselist"> <li class="spouse"> <a href="../../../ppl/0/0/d15f608efff1614baa2f615e400.html">TREVAN, Victor Grenville<span class="grampsid"> [I17832]</span></a> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/f/8/d15f5fb5b144bec865d1503ad8f.html" title="Email from Ted Anderson 08/03/2007" name ="sref1"> Email from Ted Anderson 08/03/2007 <span class="grampsid"> [S0362]</span> </a> <ol> <li id="sref1a"> <ul> <li> Confidence: Low </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:25<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/ppl/4/2/d15f608f05377c48913a77cfa24.html
HTML
gpl-3.0
7,364
package com.michaelhoffmantech.recipemanager.recipedataservice.domain; // Generated Feb 13, 2017 4:02:01 PM by Hibernate Tools 5.2.0.CR1 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Recipeingredient generated by hbm2java */ @Entity @Table(name = "recipe_ingredient") public class RecipeIngredient implements java.io.Serializable { private static final long serialVersionUID = -6219355201572086875L; private Integer recipeIngredientId; private Recipe recipe; private String createdBy; private Date createdTimestamp; private String ingredientAmount; private String ingredientMeasurement; private String ingredientType; private Integer sequenceNumber; public RecipeIngredient() { } public RecipeIngredient(Integer recipeIngredientId, Recipe recipe, String createdBy, Date createdTimestamp, String ingredientType, Integer sequenceNumber) { this.recipeIngredientId = recipeIngredientId; this.recipe = recipe; this.createdBy = createdBy; this.createdTimestamp = createdTimestamp; this.ingredientType = ingredientType; this.sequenceNumber = sequenceNumber; } public RecipeIngredient(Integer recipeIngredientId, Recipe recipe, String createdBy, Date createdTimestamp, String ingredientAmount, String ingredientMeasurement, String ingredientType, Integer sequenceNumber) { this.recipeIngredientId = recipeIngredientId; this.recipe = recipe; this.createdBy = createdBy; this.createdTimestamp = createdTimestamp; this.ingredientAmount = ingredientAmount; this.ingredientMeasurement = ingredientMeasurement; this.ingredientType = ingredientType; this.sequenceNumber = sequenceNumber; } @Id @SequenceGenerator(name = "recipe_ingredient_recipe_ingredient_id_seq", sequenceName = "recipe_ingredient_recipe_ingredient_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "recipe_ingredient_recipe_ingredient_id_seq") @Column(name = "recipe_ingredient_id", unique = true, nullable = false) public Integer getRecipeIngredientId() { return this.recipeIngredientId; } public void setRecipeIngredientId(Integer recipeIngredientId) { this.recipeIngredientId = recipeIngredientId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "recipe_id", nullable = false) public Recipe getRecipe() { return this.recipe; } public void setRecipe(Recipe recipe) { this.recipe = recipe; } @Column(name = "created_by", nullable = false, length = 100) public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_timestamp", nullable = false, length = 29) public Date getCreatedTimestamp() { return this.createdTimestamp; } public void setCreatedTimestamp(Date createdTimestamp) { this.createdTimestamp = createdTimestamp; } @Column(name = "ingredient_amount") public String getIngredientAmount() { return this.ingredientAmount; } public void setIngredientAmount(String ingredientAmount) { this.ingredientAmount = ingredientAmount; } @Column(name = "ingredient_measurement") public String getIngredientMeasurement() { return this.ingredientMeasurement; } public void setIngredientMeasurement(String ingredientMeasurement) { this.ingredientMeasurement = ingredientMeasurement; } @Column(name = "ingredient_type", nullable = false) public String getIngredientType() { return this.ingredientType; } public void setIngredientType(String ingredientType) { this.ingredientType = ingredientType; } @Column(name = "sequence_number", nullable = false) public Integer getSequenceNumber() { return this.sequenceNumber; } public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } }
mikevoxcap/recipe-data-service
src/main/java/com/michaelhoffmantech/recipemanager/recipedataservice/domain/RecipeIngredient.java
Java
gpl-3.0
4,637
import re class HeadingsParser(): """ The HeadingParser parses the document for headings. NOT YET: converts headings to raw latex headings in the correct way, so that they can be referrenced to later see https://www.sharelatex.com/learn/Sections_and_chapters for info about the levels""" def __init__(self): super().__init__() self.title = None self.subtitle = None self.heading = [] # regexes self.title_start_marker_regex = re.compile(r'[=]{3,}') self.title_end_marker_regex = re.compile(r'[=]{3,}') self.title_content_regex = re.compile( r''' ^ # beginning of line [ ] # one whitespace [A-Za-z0-9äöüÄÖÜ]+ # alphanumerical string, no whitespace (?P<title>[A-Za-z0-9äöüÄÖÜ ]+) # alphanumerical string, whitespace ok [A-Za-z0-9äöüÄÖÜ]+ # alphanumerical string, no whitespace [ ] # one whitespace $ # end of line ''', re.VERBOSE|re.UNICODE ) self.subtitle_start_marker_regex = re.compile(r'[-]{3,}') self.subtitle_end_marker_regex = re.compile(r'[-]{3,}') self.subtitle_content_regex = re.compile( r''' ^ # beginning of line [ ] # one whitespace [A-Za-z0-9äöüÄÖÜ]+ # alphanumerical string, no whitespace (?P<subtitle>[A-Za-z0-9äöüÄÖÜ ]+) # alphanumerical string, whitespace ok [A-Za-z0-9äöüÄÖÜ]+ # alphanumerical string, no whitespace [ ] # one whitespace $ # end of line ''', re.VERBOSE|re.UNICODE ) # Headings cannot begin with whitespace self.h_content_regex = re.compile( r''' ^ # beginning of line [A-Za-z0-9äöüÄÖÜß(] # alphanum [A-Za-z0-9äöüÄÖÜß,() -]* # alphanum or space [A-Za-z0-9äöüÄÖÜß)] # alphanum $ # end of line ''', re.VERBOSE|re.UNICODE ) # chapter self.h1_underlining_regex = re.compile(r'[=]{3,}') # section self.h2_underlining_regex = re.compile(r'[-]{3,}') # subsection self.h3_underlining_regex = re.compile(r'[~]{3,}') # subsubsection self.h4_underlining_regex = re.compile(r'[\^]{3,}') # paragraph self.h5_underlining_regex = re.compile(r'[*]{3,}') # subparagraph self.h6_underlining_regex = re.compile(r'[.]{3,}') def parse(self, rst_file_content): self.title = self.find_title(rst_file_content) self.subtitle_content_regex = self.find_subtitle(rst_file_content) return self.find_heading_labels(rst_file_content) def find_title(self, rst_file_content): print('looking for title ...') title = None for lineno, line in enumerate(rst_file_content): previous_line = "" if lineno > 0: previous_line = rst_file_content[lineno - 1] next_line = "" if lineno < len(rst_file_content) - 1: next_line = rst_file_content[lineno + 1] # title if ( self.title_start_marker_regex.match(previous_line) and self.title_end_marker_regex.match(next_line) and ( len(self.title_start_marker_regex.match(previous_line).group()) == len(self.title_end_marker_regex.match(next_line).group()) ) and self.title_content_regex.match(line) and not title ): title = self.title_content_regex.match(line).group('title') print('title is:|', title, '|', sep='') break if not title: print('Could not find title in document.') return title def find_subtitle(self, rst_file_content): print('looking for subtitle ...') subtitle = None for lineno, line in enumerate(rst_file_content): previous_line = "" if lineno > 0: previous_line = rst_file_content[lineno - 1] next_line = "" if lineno < len(rst_file_content) - 1: next_line = rst_file_content[lineno + 1] if ( self.subtitle_start_marker_regex.match(previous_line) and self.subtitle_end_marker_regex.match(next_line) and ( len(self.subtitle_start_marker_regex.match(previous_line).group()) == len(self.subtitle_end_marker_regex.match(next_line).group()) ) and self.subtitle_content_regex.match(line) and not subtitle ): subtitle = self.subtitle_content_regex.match(line).group('subtitle') print('subtitle is:|', subtitle, '|', sep='') break if not subtitle: print('Could not find subtitle in document.') return subtitle def find_heading_labels(self, rst_file_content): print('looking for headings ...') headings_dict = {} # heading_labels = [] for lineno, line in enumerate(rst_file_content): # print('current line:', lineno) # print('current line:', line) # if line.startswith("Schlussfolgerungen"): # print('current line:', line) previous_line = "" if lineno > 0: previous_line = rst_file_content[lineno - 1] next_line = "" if lineno < len(rst_file_content) - 1: next_line = rst_file_content[lineno + 1] # headings level 1 # print('looking for h1 ...') if ( (previous_line.isspace() or previous_line == '') and self.h_content_regex.match(line) and self.h1_underlining_regex.match(next_line) and len(self.h_content_regex.match(line).group()) == len(self.h1_underlining_regex.match(next_line).group()) ): print('found a h1:', line) print('replacing chapter heading') headings_dict[line] = self.heading_to_label(line, 'chapter') # heading_labels.append(self.heading_to_label(line, 'chapter')) rst_file_content[lineno] = ':raw-latex:`\chapter{' + line + '}`' rst_file_content[lineno + 1] = ':raw-latex:`\label{' + self.heading_to_label(line, 'chapter') + '}`' # headings level 2 # print('looking for h2 ...') if ( (previous_line.isspace() or previous_line == '') and self.h_content_regex.match(line) and self.h2_underlining_regex.match(next_line) and len(self.h_content_regex.match(line).group()) == len(self.h2_underlining_regex.match(next_line).group()) ): print('found a h2:', line) headings_dict[line] = self.heading_to_label(line, 'section') # heading_labels.append(self.heading_to_label(line, 'section')) rst_file_content[lineno] = ':raw-latex:`\section{' + line + '}`' rst_file_content[lineno + 1] = ':raw-latex:`\label{' + self.heading_to_label(line, 'section') + '}`' # headings level 3 # print('looking for h3 ...') if ( (previous_line.isspace() or previous_line == '') and self.h_content_regex.match(line) and self.h3_underlining_regex.match(next_line) and len(self.h_content_regex.match(line).group()) == len(self.h3_underlining_regex.match(next_line).group()) ): print('found a h3:', line) # heading_labels.append(self.heading_to_label(line, 'subsection')) headings_dict[line] = self.heading_to_label(line, 'subsection') rst_file_content[lineno] = ':raw-latex:`\subsection{' + line + '}`' rst_file_content[lineno + 1] = ':raw-latex:`\label{' + self.heading_to_label(line, 'subsection') + '}`' # headings level 4 # print('looking for h4 ...') if ( (previous_line.isspace() or previous_line == '') and self.h_content_regex.match(line) and self.h4_underlining_regex.match(next_line) and len(self.h_content_regex.match(line).group()) == len(self.h4_underlining_regex.match(next_line).group()) ): print('found a h4:', line) # heading_labels.append(self.heading_to_label(line, 'subsubsection')) headings_dict[line] = self.heading_to_label(line, 'subsubsection') rst_file_content[lineno] = ':raw-latex:`\subsubsection{' + line + '}`' rst_file_content[lineno + 1] = ':raw-latex:`\label{' + self.heading_to_label(line, 'subsubsection') + '}`' # headings level 5 # print('looking for h5 ...') if ( (previous_line.isspace() or previous_line == '') and self.h_content_regex.match(line) and self.h5_underlining_regex.match(next_line) and len(self.h_content_regex.match(line).group()) == len(self.h5_underlining_regex.match(next_line).group()) ): print('found a h5:', line) # heading_labels.append(self.heading_to_label(line, 'paragraph')) headings_dict[line] = self.heading_to_label(line, 'paragraph') rst_file_content[lineno] = ':raw-latex:`\paragraph{' + line + '}`' rst_file_content[lineno + 1] = ':raw-latex:`\label{' + self.heading_to_label(line, 'paragraph') + '}`' # headings level 6 # print('looking for h6 ...') if ( (previous_line.isspace() or previous_line == '') and self.h_content_regex.match(line) and self.h6_underlining_regex.match(next_line) and len(self.h_content_regex.match(line).group()) == len(self.h6_underlining_regex.match(next_line).group()) ): print('found a h6:', line) # heading_labels.append(self.heading_to_label(line, 'subparagraph')) headings_dict[line] = self.heading_to_label(line, 'subparagraph') rst_file_content[lineno] = ':raw-latex:`\subparagraph{' + line + '}`' rst_file_content[lineno + 1] = ':raw-latex:`\label{' + self.heading_to_label(line, 'subparagraph') + '}`' return headings_dict def heading_to_label(self, heading_text, level): heading_text = heading_text.lower() replaced_chars = { ' ': '-', '(': '', ')': '' } for key,value in replaced_chars.items(): heading_text = heading_text.replace(key, value) return '{0}:{1}'.format(level, heading_text) # self.chapter_delimiter_regex = re.compile(r'={3,}') # ============= # self.section_delimiter_regex = re.compile(r'-{3,}') # ------------- # self.subsection_delimiter_regex = re.compile(r'~{3,}') # ~~~~~~~~~~~~~ # self.subsubsection_delimiter_regex = re.compile(r'\^{3,}') # ^^^^^^^^^^^^^ # self.heading_text_regex = re.compile( # r''' # ^ # \s* # (?P<title_text> # [a-zA-Z0-9] # [a-zA-Z0-9_ -]* # [a-zA-Z0-9] # ) # \s* # $''', # re.VERBOSE) # self.heading_keys = [] # def parse_headings(self, rst_file_content): # for lineno, line in enumerate(rst_file_content): # # # search for title # if self.title_delimiter_regex.search(line) is not None: # if (lineno >= 2): # if ( # self.title_delimiter_regex.search(rst_file_content[lineno - 2]) is not None and # self.heading_text_regex.search(rst_file_content[lineno - 1]) is not None # ): # title_text = self.heading_text_regex.findall(rst_file_content[lineno - 1])[0].strip() # self.heading_keys.append(re.sub('\s+', '-', title_text.lower())) # print('[DEBUG:HEADINGS]', self.heading_keys) # print('[DEBUG:HEADINGS] !!! found a title in the document:', title_text, sep='') # # # TODO: elif subtitle
ZelphirKaltstahl/rst-internal-links-to-raw-latex
RSTInternalLinks/HeadingsParser.py
Python
gpl-3.0
13,092
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### ## ## ## Copyright 2010-2012, Neil Wallace <neil@openmolar.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/>. ## ## ## ############################################################################### ''' Provides schema and insert queries for the practitioner table information about the practitioners (dentists hygienists etc..) ''' from lib_openmolar.common.db_orm import InsertableRecord TABLENAME = "practitioners" class DemoGenerator(object): def __init__(self, database=None): self.length = 4 self.record = InsertableRecord(database, TABLENAME) self.record.remove(self.record.indexOf("time_stamp")) def demo_queries(self): ''' return a list of queries to populate a demo database ''' ## practitioner 1 self.record.setValue('user_id', 1) self.record.setValue('type',"dentist") self.record.setValue('status', "active") self.record.setValue('modified_by', "demo_installer") yield self.record.insert_query self.record.clearValues() ## practitioner 2 self.record.setValue('user_id', 2) self.record.setValue('type',"dentist") self.record.setValue('status', "active") self.record.setValue('modified_by', "demo_installer") yield self.record.insert_query self.record.clearValues() ## practitioner 3 self.record.setValue('user_id', 3) self.record.setValue('type',"dentist") self.record.setValue('speciality', 'Orthodontics') self.record.setValue('status', "active") self.record.setValue('modified_by', "demo_installer") yield self.record.insert_query self.record.clearValues() ## practitioner 4 self.record.setValue('user_id', 4) self.record.setValue('type',"hygienist") self.record.setValue('status', "active") self.record.setValue('modified_by', "demo_installer") yield self.record.insert_query if __name__ == "__main__": from lib_openmolar.admin.connect import DemoAdminConnection sc = DemoAdminConnection() sc.connect() builder = DemoGenerator(sc) print builder.demo_queries()
rowinggolfer/openmolar2
src/lib_openmolar/admin/db_orm/admin_practitioners.py
Python
gpl-3.0
3,483
/** Copyright 2012-2014 Kevin Hausmann * * This file is part of PodCatcher Deluxe. * * PodCatcher Deluxe 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. * * PodCatcher Deluxe 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 PodCatcher Deluxe. If not, see <http://www.gnu.org/licenses/>. */ package net.alliknow.podcatcher.model.tags; /** * Defines some constants used in JSON-files. */ @SuppressWarnings("javadoc") public class JSON { public static final String FEATURED = "featured"; public static final String SUGGESTION = "suggestions"; public static final String TITLE = "title"; public static final String URL = "url"; public static final String DESCRIPTION = "description"; public static final String LANGUAGE = "language"; public static final String TYPE = "type"; public static final String CATEGORY = "category"; public static final String EXPLICIT = "explicit"; }
salema/PodCatcher-Deluxe-Android
src/net/alliknow/podcatcher/model/tags/JSON.java
Java
gpl-3.0
1,375
#!/usr/bin/env python # -*- mode: python; coding: utf-8; -*- # --------------------------------------------------------------------------- # # Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer # Copyright (C) 2003 Mt. Hood Playing Card Co. # Copyright (C) 2005-2009 Skomoroh # # 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/>. # # --------------------------------------------------------------------------- import os import traceback from pysollib.mygettext import _ from pysollib.settings import TITLE from pysollib.settings import VERSION from pysollib.settings import TOOLKIT, USE_TILE from pysollib.settings import DEBUG from pysollib.mfxutil import print_err if TOOLKIT == 'tk': if USE_TILE: from pysollib.tile import ttk def init_tile(app, top): # load available themes d = os.path.join(app.dataloader.dir, 'themes') if os.path.isdir(d): top.tk.eval('global auto_path; lappend auto_path {%s}' % d) for t in os.listdir(d): if os.path.exists(os.path.join(d, t, 'pkgIndex.tcl')): try: top.tk.eval('package require ttk::theme::'+t) # print 'load theme:', t except Exception: traceback.print_exc() pass def set_theme(app, top, theme): # set theme style = ttk.Style(top) try: style.theme_use(theme) except Exception: print_err(_('invalid theme name: ') + theme) style.theme_use(app.opt.default_tile_theme) def get_font_name(font): # create font name # i.e. "helvetica 12" -> ("helvetica", 12, "roman", "normal") if (TOOLKIT == 'kivy'): return "helvetica 12" from six.moves.tkinter_font import Font font_name = None try: f = Font(font=font) except Exception: print_err(_('invalid font name: ') + font) if DEBUG: traceback.print_exc() else: fa = f.actual() font_name = (fa['family'], fa['size'], fa['slant'], fa['weight']) return font_name def base_init_root_window(root, app): # root.wm_group(root) root.wm_title(TITLE + ' ' + VERSION) root.wm_iconname(TITLE + ' ' + VERSION) # set minsize sw, sh = (root.winfo_screenwidth(), root.winfo_screenheight()) if sw < 640 or sh < 480: root.wm_minsize(400, 300) else: root.wm_minsize(520, 360) if TOOLKIT == 'gtk': pass if TOOLKIT == 'kivy': pass elif USE_TILE: theme = app.opt.tile_theme init_tile(app, root) set_theme(app, root, theme) else: pass class BaseTkSettings: canvas_padding = (0, 0) horizontal_toolbar_padding = (0, 0) vertical_toolbar_padding = (0, 1) toolbar_button_padding = (2, 2) toolbar_label_padding = (4, 4) if USE_TILE: toolbar_relief = 'flat' toolbar_borderwidth = 0 else: toolbar_relief = 'raised' toolbar_button_relief = 'flat' toolbar_separator_relief = 'sunken' toolbar_borderwidth = 1 toolbar_button_borderwidth = 1
jimsize/PySolFC
pysollib/winsystems/common.py
Python
gpl-3.0
3,751
#! /usr/bin/env python import sys g = {} n = {} for line in sys.stdin: (n1, n2, p, q, t, tg, x) = line.strip().split(' ') t = int(t) x = float(x) key = ' '.join((n1,n2,p,q)) if not key in n: n[key] = 0 g[key] = 0 n[key] += t g[key] += x*t for key in n: print key, n[key], g[key]/n[key]
vbeffara/Simulations
tools/massage-box.py
Python
gpl-3.0
341
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from django.contrib.auth import REDIRECT_FIELD_NAME from django.shortcuts import redirect from django.contrib.auth.views import logout as original_logout from loginas import settings as la_settings from loginas.utils import restore_original_login def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, extra_context=None): """ This can replace your default logout view. In you settings, do: from django.core.urlresolvers import reverse_lazy LOGOUT_URL = reverse_lazy('logout') """ original_session = request.session.get(la_settings.USER_SESSION_FLAG) if original_session: restore_original_login(request) return redirect(la_settings.LOGOUT_REDIRECT) else: return original_logout(request, next_page, template_name, redirect_field_name, extra_context)
CroceRossaItaliana/jorvik
autenticazione/viste.py
Python
gpl-3.0
986
<HTML > <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252" /> <TITLE>PLUGINSPAGE Attribute | pluginspage</TITLE> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/ie4.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/ie5.css" /> <style> BODY { font-family:verdana,arial,helvetica; margin:0; } </style> <SCRIPT LANGUAGE="javascript" SRC="../common/common.js"></SCRIPT> <SCRIPT LANGUAGE="javascript" SRC="../common/browdata.js"></SCRIPT> <SCRIPT LANGUAGE="javascript" SRC="../common/appliesto2.js"></SCRIPT> <SCRIPT LANGUAGE="javascript" SRC="../common/toolbar.js"></SCRIPT> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/ie4.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/inetsdk.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/advSDKATIE4.css" /> <LINK REL="stylesheet" TYPE="text/css" HREF="../common/default.css" /> <SCRIPT> var gbDBG = true; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> var gsHTCPath = "../common/"; var gsGraphicsPath = "../common/"; var gsCodePath = "../common/"; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> var gsContextMenuPath = gsHTCPath + "contextmenu.htc"; var gsCodeDecoPath = gsHTCPath + "codedeco.htc"; var gsStoreName="workshop"; var gsGraphicsPath = "../common/"; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> function InitPage() { if (!assert( (typeof(oBD) == 'object' && oBD != null), "browdata object unavailable!") ) { return; } if ("MSIE" == oBD.browser && oBD.majorVer >= 5 && (oBD.platform.toLowerCase()!="x" && oBD.platform!="Mac" && oBD.platform!="PPC" )) { if (typeof(fnATInit) == 'function') fnATInit(); if (typeof(PostGBInit) == 'function') PostGBInit(); if (typeof(PostInit) == 'function') PostInit(); if (typeof(initTabbedMembers) == 'function') initTabbedMembers(); if (typeof(hideExamples) == 'function') hideExamples(); } if (oBD.getsNavBar && oBD.platform!="PPC" ) { if (typeof(SetShowMes) == 'function') SetShowMes(); } } function assert(bCond, sMsg) { if (bCond) { return true; } else { if (gbDBG) { alert(sMsg); } return false; } } window.onload = InitPage; </SCRIPT> <SCRIPT LANGUAGE="JavaScript1.2"> function PreInit() { } </SCRIPT> <SCRIPT LANGUAGE="JavaScript"> </script> </HEAD> <BODY TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0" BGCOLOR="#FFFFFF" TEXT="#000000"> <TABLE STYLE="table-layout:fixed" class='clsContainer' CELLPADDING='15' CELLSPACING='0' float='left' WIDTH='100%' BORDER='0'> <TR> <TD VALIGN='top'> <DIV CLASS="clsDocBody"><TABLE WIDTH="97%" CELLPADDING="0" CELLSPACING="0"><TR><TD><H1>PLUGINSPAGE Attribute | pluginspage Property </H1></TD><TD ALIGN="right"><A HREF="../default.html" TITLE="This index is only for content formerly found in the Web Workshop." TARGET="_top">Internet Development Index</A></TD></TR></TABLE> <HR SIZE="1"></HR><P>Retrieves the URL of the plug-in used to view an embedded document.</P><P CLASS="clsRef">Syntax</P><BLOCKQUOTE><TABLE CLASS="clsStd"><TR><TH><B>HTML</B></TH><TD>&lt;EMBED&nbsp;<B>PLUGINSPAGE</B> = <SPAN CLASS="clsRange">sURL</SPAN>... &gt; </TD></TR><TR><TH><B>Scripting</B></TH><TD>[ <SPAN CLASS="clsRange">sURL</SPAN><B> =</B> ] <I>EMBED</I>.<B>pluginspage</B></TD></TR></TABLE></BLOCKQUOTE><P CLASS="clsRef">Possible Values</P><BLOCKQUOTE><TABLE CLASS="clsStd"><TR><TD><SPAN CLASS="clsRange">sURL</SPAN></TD><TD><b>String</b> that receives the URL of the plug-in(s).</TD></TR></TABLE><P>The property is read-only. The property has no default value.</P></BLOCKQUOTE><P CLASS="clsRef">Standards Information</P><BLOCKQUOTE><P> There is no public standard that applies to this property. </P></BLOCKQUOTE><P CLASS="clsRef">Applies To</P><BLOCKQUOTE><TABLE ID="oATTable" CLASS="TMAT3D"><TR><TD VALIGN="top" STYLE="border: 1 outset; display: none;"></TD><TD ID="oATData" CLASS="controls"><A PLATINFO="win16=3.02;win32=3.02;unix=4.0;mac=3.02;ce=5.5" HREF="../objects/embed.html"> EMBED</A></TD></TR><TR><TD COLSPAN="2" CLASS="controls"></TD></TR></TABLE></BLOCKQUOTE></DIV> </TD> </TR> </TABLE> </BODY> </HTML>
gucong3000/handbook
dhtml/DHTML/DHTMLref/properties/pluginspage.html
HTML
gpl-3.0
4,029
#include "AHADIC++/Decays/Cluster_Decay_Handler.H" #include "AHADIC++/Decays/Cluster_Part.H" #include "AHADIC++/Tools/Hadronisation_Parameters.H" using namespace AHADIC; using namespace ATOOLS; using namespace std; Cluster_Decay_Handler::Cluster_Decay_Handler(Cluster_List * clulist,bool ana) : p_softclusters(hadpars->GetSoftClusterHandler()), p_clus(new Cluster_Part(ana)), p_clulist(clulist), p_analysis(ana?new Cluster_Decay_Analysis():NULL) { } Cluster_Decay_Handler::~Cluster_Decay_Handler() { if (p_clus) { delete p_clus; p_clus=NULL; } if (p_analysis) { delete p_analysis; p_analysis=NULL; } } int Cluster_Decay_Handler::DecayClusters(Blob * blob) { Cluster * cluster; Cluster_Iterator cit(p_clulist->begin()); //msg_Out()<<":::::: "<<METHOD<<" with "<<p_clulist->size()<<" clusters.\n"; while (!p_clulist->empty()) { cluster = p_clulist->front(); if (!cluster->Active()) return -1; if (p_clus->TestDecay(cluster)) { //msg_Out()<<":::::: "<<METHOD<<": decay ok for\n"<<(*cluster); Cluster_List * clist(cluster->GetClusters()); if (!p_softclusters->TreatClusterList(clist,blob)) { msg_Error()<<"Error in "<<METHOD<<" : \n" <<" Did not find a kinematically allowed " <<"solution for the cluster list.\n" <<" Will trigger retrying the event.\n"; return -1; } while (!clist->empty()) { p_clulist->push_back(clist->front()); clist->pop_front(); } //msg_Out()<<":::::: "<<p_clulist->size()<<" clusters now.\n"; } else { //msg_Out()<<":::::: "<<METHOD<<":\n" // <<" Enter soft cluster treatment for undecayed cluster.\n" // <<(*cluster); Cluster_List clist; clist.push_back(cluster); if (!p_softclusters->TreatClusterList(&clist,blob)) { msg_Error()<<"Error in "<<METHOD<<".\n"; return -1; } } delete (p_clulist->front()->GetTrip()); delete (p_clulist->front()->GetAnti()); delete (p_clulist->front()); p_clulist->pop_front(); } if (p_analysis) p_analysis->AnalyseThis(blob); return 1; }
cms-externals/sherpa
AHADIC++/Decays/Cluster_Decay_Handler.C
C++
gpl-3.0
2,101
# 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/>. # list_files.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import traceback import tempfile import weka.core.jvm as jvm from weka.flow.control import Flow from weka.flow.source import ListFiles from weka.flow.sink import Console def main(): """ Just runs some example code. """ # setup the flow flow = Flow(name="list files") # flow.print_help() listfiles = ListFiles() listfiles.config["dir"] = str(tempfile.gettempdir()) listfiles.config["list_files"] = True listfiles.config["list_dirs"] = False listfiles.config["recursive"] = False listfiles.config["regexp"] = ".*r.*" # listfiles.print_help() flow.actors.append(listfiles) console = Console() console.config["prefix"] = "Match: " # console.print_help() flow.actors.append(console) # run the flow msg = flow.setup() if msg is None: print("\n" + flow.tree + "\n") msg = flow.execute() if msg is not None: print("Error executing flow:\n" + msg) else: print("Error setting up flow:\n" + msg) flow.wrapup() flow.cleanup() if __name__ == "__main__": try: jvm.start() main() except Exception, e: print(traceback.format_exc()) finally: jvm.stop()
fracpete/python-weka-wrapper-examples
src/wekaexamples/flow/list_file.py
Python
gpl-3.0
1,948
class CreateStatuses < ActiveRecord::Migration def change create_table :statuses do |t| t.string :title t.boolean :default t.boolean :closed t.timestamps end end end
jmacdonald/triage
db/migrate/20120927181309_create_statuses.rb
Ruby
gpl-3.0
203
# urbs [![Build Status](https://travis-ci.org/Gellardo/urbs.jl.svg?branch=master)](https://travis-ci.org/Gellardo/urbs.jl) urbs.jl is a [linear programming](https://en.wikipedia.org/wiki/Linear_programming) optimisation model for distributed energy systems. Its name stems from it's origin as a port of [URBS](https://github.com/tum-ens/urbs). ## Installation Urbs can be installed through the Julia package manager: ```julia julia> Pkg.clone("https://github.com/Gellardo/urbs.jl.git", "urbs") ``` Before any optimization can be done, one also has to install a solver for the [JuMP](https://github.com/JuliaOpt/JuMP.jl) package, for example: ```julia julia> Pkg.add("GLPKMathProgInterface") ``` In order to read data from Excelfiles, urbs uses ExcelReaders.jl which in turn needs pythons `xlrd` package. ## Copyright Copyright (C) 2016 Gellardo 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/>
Gellardo/urbs.jl
README.md
Markdown
gpl-3.0
1,467
// // RemoteNodeConnection.cs: // // Authors: // Eric Butler <eric@extremeboredom.net> // // (C) 2006 FileFind.net (http://filefind.net) // using Meshwork.Backend.Core.Protocol; namespace Meshwork.Backend.Core { public class RemoteNodeConnection : INodeConnection { private Network parentNetwork; private Node thisNodeLocal; private Node thisNodeRemote; internal RemoteNodeConnection(Network theNetwork) { parentNetwork = theNetwork; } internal RemoteNodeConnection(Network theNetwork, ConnectionInfo info) { parentNetwork = theNetwork; thisNodeLocal = parentNetwork.Nodes[info.SourceNodeID]; thisNodeRemote = parentNetwork.Nodes[info.DestNodeID]; } public ConnectionState ConnectionState { get { return ConnectionState.Remote; } set { } } public Node NodeLocal { get { return thisNodeLocal; } set { thisNodeLocal = value; } } public Node NodeRemote { get { return thisNodeRemote; } set { thisNodeRemote = value; } } } }
codebutler/meshwork
src/Meshwork.Backend/Core/RemoteNodeConnection.cs
C#
gpl-3.0
1,037
# coding: utf-8 """ Copyright 2015 SmartBear Software 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. Ref: https://github.com/swagger-api/swagger-codegen """ from pprint import pformat from six import iteritems class SeriesActors(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self): """ SeriesActors - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'data': 'list[SeriesActorsData]' } self.attribute_map = { 'data': 'data' } self._data = None @property def data(self): """ Gets the data of this SeriesActors. :return: The data of this SeriesActors. :rtype: list[SeriesActorsData] """ return self._data @data.setter def data(self, data): """ Sets the data of this SeriesActors. :param data: The data of this SeriesActors. :type: list[SeriesActorsData] """ self._data = data def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
FireBladeNooT/Medusa_1_6
lib/tvdbapiv2/models/series_actors.py
Python
gpl-3.0
3,002
--- layout: default --- {% for post in site.posts %} <div class="card mb-4"> <img class="card-img-top" src="{{ site.baseurl }}/assets/img/750x300.png" alt="Card image cap"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-justify">{{ post.content | truncatewords: 140, '...' }}</p> <a href="{{ post.url | prepend: site.baseurl }}" class="btn btn-primary">Read More &rarr;</a> </div> <div class="card-footer text-muted"> Posted on January 1, 2017 by <a href="#">{{ site.author.name}}</a> </div> </div> {% endfor %}
asperduti/jekyllstart
index.html
HTML
gpl-3.0
675
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ package org.graylog.events.notifications.types; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import org.graylog.events.contentpack.entities.EventNotificationConfigEntity; import org.graylog.events.contentpack.entities.HttpEventNotificationConfigEntity; import org.graylog.events.event.EventDto; import org.graylog.events.notifications.EventNotificationConfig; import org.graylog.events.notifications.EventNotificationExecutionJob; import org.graylog.scheduler.JobTriggerData; import org.graylog2.contentpacks.EntityDescriptorIds; import org.graylog2.contentpacks.model.entities.references.ValueReference; import org.graylog2.plugin.rest.ValidationResult; @AutoValue @JsonTypeName(HTTPEventNotificationConfig.TYPE_NAME) @JsonDeserialize(builder = HTTPEventNotificationConfig.Builder.class) public abstract class HTTPEventNotificationConfig implements EventNotificationConfig { public static final String TYPE_NAME = "http-notification-v1"; private static final String FIELD_URL = "url"; @JsonProperty(FIELD_URL) public abstract String url(); @JsonIgnore public JobTriggerData toJobTriggerData(EventDto dto) { return EventNotificationExecutionJob.Data.builder().eventDto(dto).build(); } public static Builder builder() { return Builder.create(); } @JsonIgnore public ValidationResult validate() { final ValidationResult validation = new ValidationResult(); if (url().isEmpty()) { validation.addError(FIELD_URL, "HTTP Notification url cannot be empty."); } return validation; } @AutoValue.Builder public static abstract class Builder implements EventNotificationConfig.Builder<Builder> { @JsonCreator public static Builder create() { return new AutoValue_HTTPEventNotificationConfig.Builder() .type(TYPE_NAME); } @JsonProperty(FIELD_URL) public abstract Builder url(String url); public abstract HTTPEventNotificationConfig build(); } @Override public EventNotificationConfigEntity toContentPackEntity(EntityDescriptorIds entityDescriptorIds) { return HttpEventNotificationConfigEntity.builder() .url(ValueReference.of(url())) .build(); } }
Graylog2/graylog2-server
graylog2-server/src/main/java/org/graylog/events/notifications/types/HTTPEventNotificationConfig.java
Java
gpl-3.0
3,210
package org.pale.chatcitizen; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.npc.NPC; import org.alicebot.ab.AIMLProcessor; import org.alicebot.ab.Chat; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.pale.chatcitizen.plugininterfaces.NPCDestinations; import org.pale.chatcitizen.plugininterfaces.Sentinel; import org.pale.chatcitizen.Command.CallInfo; import org.pale.chatcitizen.Command.Cmd; import org.pale.chatcitizen.Command.Registry; public class Plugin extends JavaPlugin { public static void log(String msg) { getInstance().getLogger().info(msg); } public static void warn(String msg) { getInstance().getLogger().warning(msg); } /** * Make the plugin a weird singleton. */ static Plugin instance = null; /** * All the bot wrappers - the Traits share the bots. */ private Map<String,ChatterWrapper> bots = new HashMap<String,ChatterWrapper>(); public NPCDestinations ndPlugin; public Sentinel sentinelPlugin; private Registry commandRegistry=new Registry(); /** * Use this to get plugin instances - don't play silly buggers creating new * ones all over the place! */ public static Plugin getInstance() { if (instance == null) throw new RuntimeException( "Attempt to get plugin when it's not enabled"); return instance; } @Override public void onDisable() { instance = null; getLogger().info("ChatCitizen has been disabled"); } public Plugin(){ super(); if(instance!=null) throw new RuntimeException("oi! only one instance!"); } @Override public void onEnable() { instance = this; //check if Citizens is present and enabled. if(getServer().getPluginManager().getPlugin("Citizens") == null || getServer().getPluginManager().getPlugin("Citizens").isEnabled() == false) { getLogger().severe("Citizens 2.0 not found or not enabled"); getServer().getPluginManager().disablePlugin(this); return; } // check other optional plugins ndPlugin = new NPCDestinations(); sentinelPlugin = new Sentinel(); // initialise AIML extensions AIMLProcessor.extension = new ChatBotAIMLExtension(); // this is the listener for pretty much ALL events EXCEPT NPC events, not just chat. new ChatEventListener(this); //Register. net.citizensnpcs.api.CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(ChatTrait.class)); saveDefaultConfig(); loadBots(); commandRegistry.register(this); // register commands getLogger().info("ChatCitizen has been enabled"); } public void loadBots(){ FileConfiguration c = this.getConfig(); ConfigurationSection bots = c.getConfigurationSection("bots"); if(bots==null){ throw new RuntimeException("No bots section in config"); } for(String name : bots.getKeys(false)){ String confpath = bots.getString(name); log("Loading bot "+name+" from path "+confpath); this.bots.put(name,new ChatterWrapper(name,confpath)); } log("Bots all loaded."); } public static void sendCmdMessage(CommandSender s,String msg){ s.sendMessage(ChatColor.AQUA+"[ChatCitizen] "+ChatColor.YELLOW+msg); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String cn = command.getName(); if(cn.equals("chatcitizen")){ commandRegistry.handleCommand(sender, args); return true; } return false; } public ChatterWrapper getBot(String s){ if(bots.containsKey(s)){ return bots.get(s); } else return null; } List<NPC> chatters = new ArrayList<NPC>(); public void addChatter(NPC npc) { chatters.add(npc); } public void removeChatter(NPC npc){ chatters.remove(npc); } public static boolean isNear(Location a,Location b,double dist){ return (a.distance(b)<5 && Math.abs(a.getY()-b.getY())<2); } public void handleMessage(Player player, String msg){ Location playerloc = player.getLocation(); for(NPC npc: chatters){ Location npcl = npc.getEntity().getLocation(); if(isNear(playerloc,npcl,2)){ // chatters assume <2m and you're talking to them. if(npc.hasTrait(ChatTrait.class)){ ChatTrait ct = npc.getTrait(ChatTrait.class); ct.setPropertiesForSender(player); ct.respondTo(player,msg); } } } } public static ChatTrait getChatCitizenFor(CommandSender sender) { NPC npc = CitizensAPI.getDefaultNPCSelector().getSelected(sender); if (npc == null) { return null; } if (npc.hasTrait(ChatTrait.class)) { return npc.getTrait(ChatTrait.class); } return null; } /** * Commands */ @Cmd(desc="get info on a bot",argc=0,usage="<npcname>",cz=true) public void info(CallInfo c){ String [] a; ChatTrait ct = c.getCitizen(); a = new String[] { "Bot name = "+ct.getBotName(), "Sub-bot name = "+ct.subbotName, "Random speech distance [saydist] = "+ct.sayDist, "Random speech interval [sayint] = "+ct.sayInterval, "Random speech chance [sayprob] = "+(int)(ct.sayProbability*100), "Greet distance [greetdist] = "+ct.greetDist, "Greet interval [greetint] = "+ct.greetInterval, "Greet chance = [greetprob] "+(int)(ct.greetProbability*100), "Audible distance [auddist] = "+ct.audibleDistance }; StringBuilder b = new StringBuilder(); for(String s: a){ b.append(s);b.append("\n"); } c.msg(b.toString()); } @Cmd(desc="reload all bots",argc=0,permission="chatcitizen.reloadall") public void reloadall(CallInfo c){ for(ChatterWrapper b : bots.values()){ b.reload(); } c.msg("Reload OK"); } @Cmd(desc="reload a given bot",argc=1,permission="chatcitizen.reload",usage="[botname]") public void reload(CallInfo c){ String n = c.getArgs()[0]; if(!bots.containsKey(n)){ c.msg("Bot not known. List bots with \"ccz bots\"."); } else { ChatterWrapper b = bots.get(n); b.reload(); } c.msg("Reload OK"); } @Cmd(name="bots",desc="list all bots and which NPCs use them",argc=0) public void listBots(CallInfo c){ for(String s : bots.keySet()){ ChatterWrapper b = bots.get(s); StringBuilder sb = new StringBuilder(); sb.append(ChatColor.AQUA+s+": "+ChatColor.GREEN); for(Chat chat: b.getChats()){ sb.append(chat.npc.getFullName()+" "); } c.msg(sb.toString()); } } @Cmd(name="t",desc="chat test",permission="chatcitizen.test",usage="[string]",cz=true) public void testBot(CallInfo c){ ChatTrait ct = c.getCitizen(); String msg = ""; for(String s:c.getArgs()) msg += s + " "; String m = ct.getResponseTest(msg); getLogger().info("RESPONSE :"+m); } private static String[] paramNames={"saydist","sayint","sayprob","greetdist","greetint","greetprob","auddist"}; // same ordering as paramNames - these are the actual field names! private static String[] paramFields={"sayDist","sayInterval","sayProbability","greetDist","greetInterval", "greetProbability","audibleDistance" }; @Cmd(desc="set a property in a bot",argc=-1,usage="<property> <value>", cz=true, permission="chatcitizen.set") public void set(CallInfo c) { if(c.getArgs().length < 2){ StringBuilder b = new StringBuilder(); b.append("Parameters are: "); for(String s: paramNames){ b.append(s);b.append(" "); } c.msg(b.toString()); } else { ChatTrait ct = c.getCitizen(); String[] args=c.getArgs(); for(int i=0;i<paramNames.length;i++){ if(args[0].equals(paramNames[i])){ try { Field f = ChatTrait.class.getDeclaredField(paramFields[i]); double val = Double.parseDouble(args[1]); if(paramNames[i].contains("prob")){ val *= 0.01; // convert "prob"abilities from percentages. } f.setDouble(ct,val); } catch (NumberFormatException e) { c.msg("that is not a number"); } catch (NoSuchFieldException | SecurityException e) { c.msg("no such field - this shouldn't happen:"+paramFields[i]); } catch (IllegalArgumentException e) { c.msg("probably a type mismatch - this shouldn't happen:"+paramFields[i]); } catch (IllegalAccessException e) { c.msg("illegal access to field - this shouldn't happen:"+paramFields[i]); } return; // found and handled, so exit. } } c.msg("No parameter of that name found"); return; } } @Cmd(desc="set a chatbot for an NPC",argc=1,usage="<botname>",cz=true,permission="chatcitizen.set") public void setbot(CallInfo c){ String name = c.getArgs()[0]; ChatTrait ct = c.getCitizen(); ChatterWrapper b = Plugin.getInstance().getBot(name); if(b==null){ c.msg("\""+name+"\" is not installed on this server."); } else { ct.setBot(b); c.msg(ct.getNPC().getFullName()+" is now using bot \""+name+"\"."); } } @Cmd(desc="set a \"sub-bot\" for an NPC",argc=1,usage="<subbot>",cz=true,permission="chatcitizen.set") public void subbot(CallInfo c){ String name = c.getArgs()[0]; ChatTrait ct = c.getCitizen(); ct.subbotName = name; c.msg(ct.getNPC().getFullName()+" is now using sub-bot \""+name+"\"."); } @Cmd(desc="show help for a command or list commands",argc=-1,usage="[<command name>]") public void help(CallInfo c){ if(c.getArgs().length==0){ commandRegistry.listCommands(c); } else { commandRegistry.showHelp(c,c.getArgs()[0]); } } }
jimfinnis/ChatCitizen
ChatCitizen/src/org/pale/chatcitizen/Plugin.java
Java
gpl-3.0
9,666
/* * Copyright (C) 2008, 2009, 2010 The Collaborative Software Foundation. * * This file is part of FeedHandlers (FH). * * FH 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. * * FH 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 FH. If not, see <http://www.gnu.org/licenses/>. */ /* * System includes */ #include <stdio.h> #include <pthread.h> #include <string.h> #include <errno.h> /* * FH Common includes */ #include "fh_log.h" /* * OPRA includes */ #include "fh_opra_topic.h" /* * OPRA Topic format API */ FH_STATUS fh_opra_topic_fmt(fh_opra_topic_fmt_t *tfmt, fh_opra_opt_key_t *k, char *topic, uint32_t length) { register uint32_t i = 0; register uint32_t j = 0; for (i = 0; i < tfmt->tfmt_num_stanzas && j < length; i++) { register char *ptr = tfmt->tfmt_stanza_fmts[i]; if (ptr == NULL) { FH_LOG(MGMT, ERR, ("Topic format is missing stanza[%d]", i)); return FH_ERROR; } FH_LOG(MGMT, DIAG, ("Topic format stanza[%d] = '%s'", i, ptr)); while (*ptr != '\0' && j < length) { if (*ptr != '$') { topic[j++] = *ptr++; } else { ptr++; if (*ptr == '\0') { FH_LOG(MGMT, ERR, ("Invalid topic format: stanza[%d] = '%s'", i, tfmt->tfmt_stanza_fmts[i])); } switch (*ptr++) { case FH_OPRA_TOPIC_FMT_SYMBOL: { register char *uptr = k->k_symbol; register int count = 0; while (*uptr != '\0' && count++ < FH_OPRA_TOPIC_MAX_SYMBOL && j < length) { topic[j++] = *uptr++; } } break; case FH_OPRA_TOPIC_FMT_YEAR: { sprintf(&topic[j], "%.2u", k->k_year); j += 2; } break; case FH_OPRA_TOPIC_FMT_MONTH: { sprintf(&topic[j], "%.2u", k->k_month); j += 2; } break; case FH_OPRA_TOPIC_FMT_DAY: { sprintf(&topic[j], "%.2u", k->k_day); j += 2; } break; case FH_OPRA_TOPIC_FMT_PUTCALL: { topic[j++] = k->k_putcall; } break; case FH_OPRA_TOPIC_FMT_DECIMAL: { sprintf(&topic[j], "%.5u", k->k_decimal); j += 5; } break; case FH_OPRA_TOPIC_FMT_FRACTION: { sprintf(&topic[j], "%.3u", k->k_fraction * 1000); j += 3; } break; case FH_OPRA_TOPIC_FMT_EXCH: { topic[j++] = k->k_exchid; } break; default: FH_LOG(MGMT, ERR, ("Invalid topic format variable: $%c - stanza[%d] = '%s'", *ptr, i, tfmt->tfmt_stanza_fmts[i])); FH_ASSERT(1); } } } if (j < length && (i+1) != tfmt->tfmt_num_stanzas) { topic[j++] = tfmt->tfmt_stanza_delim; } } if (j == length) { topic[j-1] = '\0'; FH_LOG(MGMT, ERR, ("Topic too long (len:%d): topic: %s", topic)); return FH_ERROR; } topic[j] = '\0'; FH_LOG(MGMT, DIAG, ("Topic formatted successfully: topic: %s (len:%d)", topic, j)); return FH_OK; }
csinitiative/fhce
feeds/opra/fast/common/fh_opra_topic.c
C
gpl-3.0
4,298
#!/bin/bash set -- "example/graphviz-binary-search-tree-graph" DOT=dot CONVERT=convert # XXX: Downside of -GNE is that is overrides any in-graph attribute $DOT -Tpng -Nstyle=filled -Nfillcolor=white -Gbgcolor=transparent $1.dot.gv > all.png $DOT -Tpng -Nstyle=filled -Nfillcolor=white -Estyle=invis -Gbgcolor=transparent $1.dot.gv > no_edges.png $CONVERT all.png \( no_edges.png -background black -shadow 50x3+0+5 \) +swap -background none -layers merge +repage $1.png #rm -f all.png no_edges.png echo $1.png realpath all.png realpath $1.png
dotmpe/node-sitefile
tools/diagram-shadows.sh
Shell
gpl-3.0
548
@echo off set OPT=-XprintProcessorInfo -XprintRounds set CP=c:\projects\deors.demos\annotations\deors.demos.annotations.velocity\target\deors.demos.annotations.velocity-1.0-SNAPSHOT.jar set PROC=%CP%;c:\projects\deors.demos\annotations\com.luckyend.generators.metamodel.processors\target\com.luckyend.generators.metamodel.processors-1.0-SNAPSHOT.jar set PROC=%PROC%;%HOME%\.m2\repository\org\apache\velocity\velocity\1.6.4\velocity-1.6.4.jar set PROC=%PROC%;%HOME%\.m2\repository\commons-collections\commons-collections\3.2.1\commons-collections-3.2.1.jar set PROC=%PROC%;%HOME%\.m2\repository\commons-lang\commons-lang\2.4\commons-lang-2.4.jar set PROC=%PROC%;%HOME%\.m2\repository\org\apache\velocity\velocity-tools\2.0\velocity-tools-2.0.jar set SRC=src\main\java\deors\demos\annotations\velocity\client\Article.java set GEN_SRC=target\generated-sources\annotations set GEN_CLS=target\classes mkdir %GEN_SRC% mkdir %GEN_CLS% javac %OPT% -classpath %CP% -processorpath %PROC% %SRC% -s %GEN_SRC% -d %GEN_CLS%
arielcarrera/bean-metamodel-generator
bean-metamodel-generator-client/build-with-javac.bat
Batchfile
gpl-3.0
1,010
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Family of STEELE, Irving Veitch and DUNNE, Moira Helen</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li class = "CurrentSection"><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="RelationshipDetail"> <h2>Family of STEELE, Irving Veitch and DUNNE, Moira Helen<sup><small></small></sup></h2> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Husband</td> <td class="ColumnValue"> <a href="../../../ppl/d/f/d15f605d4dc78b0ccdd4bad39fd.html">STEELE, Irving Veitch<span class="grampsid"> [I12355]</span></a> </td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Wife</td> <td class="ColumnValue"> <a href="../../../ppl/a/5/d15f605d52583c33958c26865a.html">DUNNE, Moira Helen<span class="grampsid"> [I12356]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/6/3/d15f60d70d75c5e89ffec88da36.html" title="Marriage"> Marriage <span class="grampsid"> [E25881]</span> </a> </td> <td class="ColumnDate">1938-11-14</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> <a href="../../../evt/9/7/d15f60d70df3f069e0e698acd79.html" title="Family (Primary)"> Family (Primary) <span class="grampsid"> [E25882]</span> </a> </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> <a href="#sref1a">1a</a> </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Attributes</td> <td class="ColumnValue"> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">B9DA0C03F19616409498ECB8EB0CCE8094D3</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </td> </tr> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">B9DA0C03F19616409498ECB8EB0CCE8094D3</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/0/1/d15f5fb94b999ac1cae9d49a10.html" title="Frank Lee: GEDCOM File : JamesJORDAN.ged" name ="sref1"> Frank Lee: GEDCOM File : JamesJORDAN.ged <span class="grampsid"> [S0308]</span> </a> <ol> <li id="sref1a"> <ul> <li> Confidence: Low </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:55<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/fam/8/d/d15f605d503466a0c5e3feb39d8.html
HTML
gpl-3.0
6,419
/**************************************************************************** ** ** Copyright (C) 2013, 2014 Andreas Mussgiller ** ** based on libpifacedigital by Thomas Preston ** http://github.com/piface/libpifacedigital ** ** 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 <cstdio> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #ifndef NODEVICE #include <mcp23s17.h> #endif #include "PiFaceOrg.h" uint8_t PiFaceOrg::usecount_ = 0; int PiFaceOrg::mcp23s17_fd_ = 0; PiFaceOrg::PiFaceOrg(uint8_t hw_addr) :VPiFace(hw_addr) { } PiFaceOrg::~PiFaceOrg() { if (usecount_>0) { usecount_--; #ifndef NODEVICE if (usecount_==0) { const uint8_t intenb = mcp23s17_read_reg(GPINTENB, hw_addr_, mcp23s17_fd_); if (intenb) { mcp23s17_write_reg(0, GPINTENB, hw_addr_, mcp23s17_fd_); // now do some other interrupt stuff... // TODO } close(mcp23s17_fd_); mcp23s17_fd_ = 0; } #endif } } bool PiFaceOrg::init() { if (usecount_==0) { #ifndef NODEVICE if ((mcp23s17_fd_ = mcp23s17_open(0, 0)) < 0) { return false; } #endif } usecount_++; #ifndef NODEVICE const uint8_t ioconfig = BANK_OFF | INT_MIRROR_OFF | \ SEQOP_OFF | \ DISSLW_OFF | \ HAEN_ON | \ ODR_OFF | \ INTPOL_LOW; mcp23s17_write_reg(ioconfig, IOCON, hw_addr_, mcp23s17_fd_); // I/O direction mcp23s17_write_reg(0x00, IODIRA, hw_addr_, mcp23s17_fd_); mcp23s17_write_reg(0xff, IODIRB, hw_addr_, mcp23s17_fd_); // GPIOB pull ups mcp23s17_write_reg(0xff, GPPUB, hw_addr_, mcp23s17_fd_); // enable interrupts mcp23s17_write_reg(0xff, GPINTENB, hw_addr_, mcp23s17_fd_); #endif return true; } uint8_t PiFaceOrg::readRegister(uint8_t reg) { #ifndef NODEVICE return mcp23s17_read_reg(reg, hw_addr_, mcp23s17_fd_); #else return 0; #endif } void PiFaceOrg::writeRegister(uint8_t data, uint8_t reg) { #ifndef NODEVICE mcp23s17_write_reg(data, reg, hw_addr_, mcp23s17_fd_); #endif } uint8_t PiFaceOrg::readBit(uint8_t bit, uint8_t reg) { #ifndef NODEVICE return mcp23s17_read_bit(bit, reg, hw_addr_, mcp23s17_fd_); #else return 0; #endif } void PiFaceOrg::writeBit(uint8_t data, uint8_t bit, uint8_t reg) { #ifndef NODEVICE mcp23s17_write_bit(data, bit, reg, hw_addr_, mcp23s17_fd_); #endif }
Negusbuk/NeguPi
src/PiFaceOrg.cc
C++
gpl-3.0
3,049
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'print', 'et', { toolbar: 'Printimine' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/print/lang/et.js
JavaScript
gpl-3.0
234
/* * Copyright (C) 2012 Alexandr Vodiannikov aka "Aleksoid1978" (Aleksoid1978@mail.ru) * * This file is part of WinnerMediaPlayer. * * WinnerMediaPlayer 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. * * WinnerMediaPlayer 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 class CPreView : public CWnd { public: CPreView(); virtual ~CPreView(); DECLARE_DYNAMIC(CPreView) virtual BOOL SetWindowText(LPCWSTR lpString); void GetVideoRect(LPRECT lpRect); HWND GetVideoHWND(); COLORREF RGBFill(int r1, int g1, int b1, int r2, int g2, int b2, int i, int k); protected: CString tooltipstr; CWnd m_view; int wb; int hc; CRect v_rect; virtual BOOL PreCreateWindow(CREATESTRUCT& cs); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() };
WinnerSoftLab/WinnerMediaPlayer
src/apps/mplayerc/PlayerPreView.h
C
gpl-3.0
1,389
#! /bin/false # vim: set autoindent shiftwidth=4 tabstop=4: # $Id: SAMI_WS2.pm,v 1.1 2011/10/12 23:51:49 pertusus Exp $ # Conversion routines for WIN-SAMI-2. # Copyright (C) 2002-2009 Guido Flohr <guido@imperia.net>, all # rights reserved. # This file is generated, do not edit! # This program 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, 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 # Library General Public License for more details. # You should have received a copy of the GNU Library 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. package Locale::RecodeData::SAMI_WS2; use strict; require Locale::RecodeData; use base qw(Locale::RecodeData); my @to_ucs4 = ( 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, 0x20ac, 0xfffd, 0x010c, 0x0192, 0x010d, 0x01b7, 0x0292, 0x01ee, 0x01ef, 0x0110, 0x0160, 0x2039, 0x0152, 0xfffd, 0xfffd, 0xfffd, 0xfffd, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x0111, 0x01e6, 0x0161, 0x203a, 0x0153, 0xfffd, 0xfffd, 0x0178, 0x00a0, 0x01e7, 0x01e4, 0x00a3, 0x00a4, 0x01e5, 0x00a6, 0x00a7, 0x00a8, 0x00a9, 0x021e, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x021f, 0x00b0, 0x00b1, 0x01e8, 0x01e9, 0x00b4, 0x00b5, 0x00b6, 0x00b7, 0x014a, 0x014b, 0x0166, 0x00bb, 0x0167, 0x00bd, 0x017d, 0x017e, 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, ); my @to_utf8 = ( "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f", "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f", "\x20", "\x21", "\x22", "\x23", "\x24", "\x25", "\x26", "\x27", "\x28", "\x29", "\x2a", "\x2b", "\x2c", "\x2d", "\x2e", "\x2f", "\x30", "\x31", "\x32", "\x33", "\x34", "\x35", "\x36", "\x37", "\x38", "\x39", "\x3a", "\x3b", "\x3c", "\x3d", "\x3e", "\x3f", "\x40", "\x41", "\x42", "\x43", "\x44", "\x45", "\x46", "\x47", "\x48", "\x49", "\x4a", "\x4b", "\x4c", "\x4d", "\x4e", "\x4f", "\x50", "\x51", "\x52", "\x53", "\x54", "\x55", "\x56", "\x57", "\x58", "\x59", "\x5a", "\x5b", "\x5c", "\x5d", "\x5e", "\x5f", "\x60", "\x61", "\x62", "\x63", "\x64", "\x65", "\x66", "\x67", "\x68", "\x69", "\x6a", "\x6b", "\x6c", "\x6d", "\x6e", "\x6f", "\x70", "\x71", "\x72", "\x73", "\x74", "\x75", "\x76", "\x77", "\x78", "\x79", "\x7a", "\x7b", "\x7c", "\x7d", "\x7e", "\x7f", "\xe2\x82\xac", "\xef\xbf\xbd", "\xc4\x8c", "\xc6\x92", "\xc4\x8d", "\xc6\xb7", "\xca\x92", "\xc7\xae", "\xc7\xaf", "\xc4\x90", "\xc5\xa0", "\xe2\x80\xb9", "\xc5\x92", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\xa2", "\xe2\x80\x93", "\xe2\x80\x94", "\xc4\x91", "\xc7\xa6", "\xc5\xa1", "\xe2\x80\xba", "\xc5\x93", "\xef\xbf\xbd", "\xef\xbf\xbd", "\xc5\xb8", "\xc2\xa0", "\xc7\xa7", "\xc7\xa4", "\xc2\xa3", "\xc2\xa4", "\xc7\xa5", "\xc2\xa6", "\xc2\xa7", "\xc2\xa8", "\xc2\xa9", "\xc8\x9e", "\xc2\xab", "\xc2\xac", "\xc2\xad", "\xc2\xae", "\xc8\x9f", "\xc2\xb0", "\xc2\xb1", "\xc7\xa8", "\xc7\xa9", "\xc2\xb4", "\xc2\xb5", "\xc2\xb6", "\xc2\xb7", "\xc5\x8a", "\xc5\x8b", "\xc5\xa6", "\xc2\xbb", "\xc5\xa7", "\xc2\xbd", "\xc5\xbd", "\xc5\xbe", "\xc3\x80", "\xc3\x81", "\xc3\x82", "\xc3\x83", "\xc3\x84", "\xc3\x85", "\xc3\x86", "\xc3\x87", "\xc3\x88", "\xc3\x89", "\xc3\x8a", "\xc3\x8b", "\xc3\x8c", "\xc3\x8d", "\xc3\x8e", "\xc3\x8f", "\xc3\x90", "\xc3\x91", "\xc3\x92", "\xc3\x93", "\xc3\x94", "\xc3\x95", "\xc3\x96", "\xc3\x97", "\xc3\x98", "\xc3\x99", "\xc3\x9a", "\xc3\x9b", "\xc3\x9c", "\xc3\x9d", "\xc3\x9e", "\xc3\x9f", "\xc3\xa0", "\xc3\xa1", "\xc3\xa2", "\xc3\xa3", "\xc3\xa4", "\xc3\xa5", "\xc3\xa6", "\xc3\xa7", "\xc3\xa8", "\xc3\xa9", "\xc3\xaa", "\xc3\xab", "\xc3\xac", "\xc3\xad", "\xc3\xae", "\xc3\xaf", "\xc3\xb0", "\xc3\xb1", "\xc3\xb2", "\xc3\xb3", "\xc3\xb4", "\xc3\xb5", "\xc3\xb6", "\xc3\xb7", "\xc3\xb8", "\xc3\xb9", "\xc3\xba", "\xc3\xbb", "\xc3\xbc", "\xc3\xbd", "\xc3\xbe", "\xc3\xbf", ); my %from_ucs4 = ( 0x00000000 => "\x00", 0x00000001 => "\x01", 0x00000002 => "\x02", 0x00000003 => "\x03", 0x00000004 => "\x04", 0x00000005 => "\x05", 0x00000006 => "\x06", 0x00000007 => "\x07", 0x00000008 => "\x08", 0x00000009 => "\x09", 0x0000000a => "\x0a", 0x0000000b => "\x0b", 0x0000000c => "\x0c", 0x0000000d => "\x0d", 0x0000000e => "\x0e", 0x0000000f => "\x0f", 0x00000010 => "\x10", 0x00000011 => "\x11", 0x00000012 => "\x12", 0x00000013 => "\x13", 0x00000014 => "\x14", 0x00000015 => "\x15", 0x00000016 => "\x16", 0x00000017 => "\x17", 0x00000018 => "\x18", 0x00000019 => "\x19", 0x0000001a => "\x1a", 0x0000001b => "\x1b", 0x0000001c => "\x1c", 0x0000001d => "\x1d", 0x0000001e => "\x1e", 0x0000001f => "\x1f", 0x00000020 => "\x20", 0x00000021 => "\x21", 0x00000022 => "\x22", 0x00000023 => "\x23", 0x00000024 => "\x24", 0x00000025 => "\x25", 0x00000026 => "\x26", 0x00000027 => "\x27", 0x00000028 => "\x28", 0x00000029 => "\x29", 0x0000002a => "\x2a", 0x0000002b => "\x2b", 0x0000002c => "\x2c", 0x0000002d => "\x2d", 0x0000002e => "\x2e", 0x0000002f => "\x2f", 0x00000030 => "\x30", 0x00000031 => "\x31", 0x00000032 => "\x32", 0x00000033 => "\x33", 0x00000034 => "\x34", 0x00000035 => "\x35", 0x00000036 => "\x36", 0x00000037 => "\x37", 0x00000038 => "\x38", 0x00000039 => "\x39", 0x0000003a => "\x3a", 0x0000003b => "\x3b", 0x0000003c => "\x3c", 0x0000003d => "\x3d", 0x0000003e => "\x3e", 0x0000003f => "\x3f", 0x00000040 => "\x40", 0x00000041 => "\x41", 0x00000042 => "\x42", 0x00000043 => "\x43", 0x00000044 => "\x44", 0x00000045 => "\x45", 0x00000046 => "\x46", 0x00000047 => "\x47", 0x00000048 => "\x48", 0x00000049 => "\x49", 0x0000004a => "\x4a", 0x0000004b => "\x4b", 0x0000004c => "\x4c", 0x0000004d => "\x4d", 0x0000004e => "\x4e", 0x0000004f => "\x4f", 0x00000050 => "\x50", 0x00000051 => "\x51", 0x00000052 => "\x52", 0x00000053 => "\x53", 0x00000054 => "\x54", 0x00000055 => "\x55", 0x00000056 => "\x56", 0x00000057 => "\x57", 0x00000058 => "\x58", 0x00000059 => "\x59", 0x0000005a => "\x5a", 0x0000005b => "\x5b", 0x0000005c => "\x5c", 0x0000005d => "\x5d", 0x0000005e => "\x5e", 0x0000005f => "\x5f", 0x00000060 => "\x60", 0x00000061 => "\x61", 0x00000062 => "\x62", 0x00000063 => "\x63", 0x00000064 => "\x64", 0x00000065 => "\x65", 0x00000066 => "\x66", 0x00000067 => "\x67", 0x00000068 => "\x68", 0x00000069 => "\x69", 0x0000006a => "\x6a", 0x0000006b => "\x6b", 0x0000006c => "\x6c", 0x0000006d => "\x6d", 0x0000006e => "\x6e", 0x0000006f => "\x6f", 0x00000070 => "\x70", 0x00000071 => "\x71", 0x00000072 => "\x72", 0x00000073 => "\x73", 0x00000074 => "\x74", 0x00000075 => "\x75", 0x00000076 => "\x76", 0x00000077 => "\x77", 0x00000078 => "\x78", 0x00000079 => "\x79", 0x0000007a => "\x7a", 0x0000007b => "\x7b", 0x0000007c => "\x7c", 0x0000007d => "\x7d", 0x0000007e => "\x7e", 0x0000007f => "\x7f", 0x000000a0 => "\xa0", 0x000000a3 => "\xa3", 0x000000a4 => "\xa4", 0x000000a6 => "\xa6", 0x000000a7 => "\xa7", 0x000000a8 => "\xa8", 0x000000a9 => "\xa9", 0x000000ab => "\xab", 0x000000ac => "\xac", 0x000000ad => "\xad", 0x000000ae => "\xae", 0x000000b0 => "\xb0", 0x000000b1 => "\xb1", 0x000000b4 => "\xb4", 0x000000b5 => "\xb5", 0x000000b6 => "\xb6", 0x000000b7 => "\xb7", 0x000000bb => "\xbb", 0x000000bd => "\xbd", 0x000000c0 => "\xc0", 0x000000c1 => "\xc1", 0x000000c2 => "\xc2", 0x000000c3 => "\xc3", 0x000000c4 => "\xc4", 0x000000c5 => "\xc5", 0x000000c6 => "\xc6", 0x000000c7 => "\xc7", 0x000000c8 => "\xc8", 0x000000c9 => "\xc9", 0x000000ca => "\xca", 0x000000cb => "\xcb", 0x000000cc => "\xcc", 0x000000cd => "\xcd", 0x000000ce => "\xce", 0x000000cf => "\xcf", 0x000000d0 => "\xd0", 0x000000d1 => "\xd1", 0x000000d2 => "\xd2", 0x000000d3 => "\xd3", 0x000000d4 => "\xd4", 0x000000d5 => "\xd5", 0x000000d6 => "\xd6", 0x000000d7 => "\xd7", 0x000000d8 => "\xd8", 0x000000d9 => "\xd9", 0x000000da => "\xda", 0x000000db => "\xdb", 0x000000dc => "\xdc", 0x000000dd => "\xdd", 0x000000de => "\xde", 0x000000df => "\xdf", 0x000000e0 => "\xe0", 0x000000e1 => "\xe1", 0x000000e2 => "\xe2", 0x000000e3 => "\xe3", 0x000000e4 => "\xe4", 0x000000e5 => "\xe5", 0x000000e6 => "\xe6", 0x000000e7 => "\xe7", 0x000000e8 => "\xe8", 0x000000e9 => "\xe9", 0x000000ea => "\xea", 0x000000eb => "\xeb", 0x000000ec => "\xec", 0x000000ed => "\xed", 0x000000ee => "\xee", 0x000000ef => "\xef", 0x000000f0 => "\xf0", 0x000000f1 => "\xf1", 0x000000f2 => "\xf2", 0x000000f3 => "\xf3", 0x000000f4 => "\xf4", 0x000000f5 => "\xf5", 0x000000f6 => "\xf6", 0x000000f7 => "\xf7", 0x000000f8 => "\xf8", 0x000000f9 => "\xf9", 0x000000fa => "\xfa", 0x000000fb => "\xfb", 0x000000fc => "\xfc", 0x000000fd => "\xfd", 0x000000fe => "\xfe", 0x000000ff => "\xff", 0x0000010c => "\x82", 0x0000010d => "\x84", 0x00000110 => "\x89", 0x00000111 => "\x98", 0x0000014a => "\xb8", 0x0000014b => "\xb9", 0x00000152 => "\x8c", 0x00000153 => "\x9c", 0x00000160 => "\x8a", 0x00000161 => "\x9a", 0x00000166 => "\xba", 0x00000167 => "\xbc", 0x00000178 => "\x9f", 0x0000017d => "\xbe", 0x0000017e => "\xbf", 0x00000192 => "\x83", 0x000001b7 => "\x85", 0x000001e4 => "\xa2", 0x000001e5 => "\xa5", 0x000001e6 => "\x99", 0x000001e7 => "\xa1", 0x000001e8 => "\xb2", 0x000001e9 => "\xb3", 0x000001ee => "\x87", 0x000001ef => "\x88", 0x0000021e => "\xaa", 0x0000021f => "\xaf", 0x00000292 => "\x86", 0x00002013 => "\x96", 0x00002014 => "\x97", 0x00002018 => "\x91", 0x00002019 => "\x92", 0x0000201c => "\x93", 0x0000201d => "\x94", 0x00002022 => "\x95", 0x00002039 => "\x8b", 0x0000203a => "\x9b", 0x000020ac => "\x80", ); sub _recode { if ($_[0]->{_from} eq 'INTERNAL') { $_[1] = join '', map $from_ucs4{$_} || (defined $from_ucs4{$_} ? $from_ucs4{$_} : "\x3f"), @{$_[1]}; } elsif ($_[0]->{_to} eq 'UTF-8',) { $_[1] = join '', map $to_utf8[$_], unpack 'C*', $_[1]; } else { $_[1] = [ map $to_ucs4[$_], unpack 'C*', $_[1] ]; } return 1; } 1; __END__ =head1 NAME Locale::RecodeData::SAMI_WS2 - Conversion routines for SAMI_WS2 =head1 SYNOPSIS This module is internal to libintl. Do not use directly! =head1 DESCRIPTION This module is generated and contains the conversion tables and routines for WIN-SAMI-2. =head1 COMMENTS The following comments have been extracted from the original charmap: source: E<lt>URL:http://www2.isl.uit.no/trond/ws2t.htmlE<gt> and E<lt>URL:http://www.unicode.org/unicode/alloc/Pipeline.htmlE<gt> author: Petter Reinholdtsen E<lt>pere@td.org.uit.noE<gt> date: 1999-01-20 based on info from Trond Trosterud E<lt>Trond.Trosterud@hum.uit.noE<gt>. This charmap is based on MS CP1252, not ISO 8859/1. alias WS2 alias WINDOWS-SAMI2 Please note that aliases listed above are not necessarily valid! =head1 CHARACTER TABLE The following table is sorted in the same order as the original charmap. All character codes are in hexadecimal. Please read 'ISO-10646' as 'ISO-10646-UCS4'. Local | ISO-10646 | Description -------+-----------+------------------------------------------------- 00 | 00000000 | NULL (NUL) 01 | 00000001 | START OF HEADING (SOH) 02 | 00000002 | START OF TEXT (STX) 03 | 00000003 | END OF TEXT (ETX) 04 | 00000004 | END OF TRANSMISSION (EOT) 05 | 00000005 | ENQUIRY (ENQ) 06 | 00000006 | ACKNOWLEDGE (ACK) 07 | 00000007 | BELL (BEL) 08 | 00000008 | BACKSPACE (BS) 09 | 00000009 | CHARACTER TABULATION (HT) 0A | 0000000A | LINE FEED (LF) 0B | 0000000B | LINE TABULATION (VT) 0C | 0000000C | FORM FEED (FF) 0D | 0000000D | CARRIAGE RETURN (CR) 0E | 0000000E | SHIFT OUT (SO) 0F | 0000000F | SHIFT IN (SI) 10 | 00000010 | DATALINK ESCAPE (DLE) 11 | 00000011 | DEVICE CONTROL ONE (DC1) 12 | 00000012 | DEVICE CONTROL TWO (DC2) 13 | 00000013 | DEVICE CONTROL THREE (DC3) 14 | 00000014 | DEVICE CONTROL FOUR (DC4) 15 | 00000015 | NEGATIVE ACKNOWLEDGE (NAK) 16 | 00000016 | SYNCHRONOUS IDLE (SYN) 17 | 00000017 | END OF TRANSMISSION BLOCK (ETB) 18 | 00000018 | CANCEL (CAN) 19 | 00000019 | END OF MEDIUM (EM) 1A | 0000001A | SUBSTITUTE (SUB) 1B | 0000001B | ESCAPE (ESC) 1C | 0000001C | FILE SEPARATOR (IS4) 1D | 0000001D | GROUP SEPARATOR (IS3) 1E | 0000001E | RECORD SEPARATOR (IS2) 1F | 0000001F | UNIT SEPARATOR (IS1) 20 | 00000020 | SPACE 21 | 00000021 | EXCLAMATION MARK 22 | 00000022 | QUOTATION MARK 23 | 00000023 | NUMBER SIGN 24 | 00000024 | DOLLAR SIGN 25 | 00000025 | PERCENT SIGN 26 | 00000026 | AMPERSAND 27 | 00000027 | APOSTROPHE 28 | 00000028 | LEFT PARENTHESIS 29 | 00000029 | RIGHT PARENTHESIS 2A | 0000002A | ASTERISK 2B | 0000002B | PLUS SIGN 2C | 0000002C | COMMA 2D | 0000002D | HYPHEN-MINUS 2E | 0000002E | FULL STOP 2F | 0000002F | SOLIDUS 30 | 00000030 | DIGIT ZERO 31 | 00000031 | DIGIT ONE 32 | 00000032 | DIGIT TWO 33 | 00000033 | DIGIT THREE 34 | 00000034 | DIGIT FOUR 35 | 00000035 | DIGIT FIVE 36 | 00000036 | DIGIT SIX 37 | 00000037 | DIGIT SEVEN 38 | 00000038 | DIGIT EIGHT 39 | 00000039 | DIGIT NINE 3A | 0000003A | COLON 3B | 0000003B | SEMICOLON 3C | 0000003C | LESS-THAN SIGN 3D | 0000003D | EQUALS SIGN 3E | 0000003E | GREATER-THAN SIGN 3F | 0000003F | QUESTION MARK 40 | 00000040 | COMMERCIAL AT 41 | 00000041 | LATIN CAPITAL LETTER A 42 | 00000042 | LATIN CAPITAL LETTER B 43 | 00000043 | LATIN CAPITAL LETTER C 44 | 00000044 | LATIN CAPITAL LETTER D 45 | 00000045 | LATIN CAPITAL LETTER E 46 | 00000046 | LATIN CAPITAL LETTER F 47 | 00000047 | LATIN CAPITAL LETTER G 48 | 00000048 | LATIN CAPITAL LETTER H 49 | 00000049 | LATIN CAPITAL LETTER I 4A | 0000004A | LATIN CAPITAL LETTER J 4B | 0000004B | LATIN CAPITAL LETTER K 4C | 0000004C | LATIN CAPITAL LETTER L 4D | 0000004D | LATIN CAPITAL LETTER M 4E | 0000004E | LATIN CAPITAL LETTER N 4F | 0000004F | LATIN CAPITAL LETTER O 50 | 00000050 | LATIN CAPITAL LETTER P 51 | 00000051 | LATIN CAPITAL LETTER Q 52 | 00000052 | LATIN CAPITAL LETTER R 53 | 00000053 | LATIN CAPITAL LETTER S 54 | 00000054 | LATIN CAPITAL LETTER T 55 | 00000055 | LATIN CAPITAL LETTER U 56 | 00000056 | LATIN CAPITAL LETTER V 57 | 00000057 | LATIN CAPITAL LETTER W 58 | 00000058 | LATIN CAPITAL LETTER X 59 | 00000059 | LATIN CAPITAL LETTER Y 5A | 0000005A | LATIN CAPITAL LETTER Z 5B | 0000005B | LEFT SQUARE BRACKET 5C | 0000005C | REVERSE SOLIDUS 5D | 0000005D | RIGHT SQUARE BRACKET 5E | 0000005E | CIRCUMFLEX ACCENT 5F | 0000005F | LOW LINE 60 | 00000060 | GRAVE ACCENT 61 | 00000061 | LATIN SMALL LETTER A 62 | 00000062 | LATIN SMALL LETTER B 63 | 00000063 | LATIN SMALL LETTER C 64 | 00000064 | LATIN SMALL LETTER D 65 | 00000065 | LATIN SMALL LETTER E 66 | 00000066 | LATIN SMALL LETTER F 67 | 00000067 | LATIN SMALL LETTER G 68 | 00000068 | LATIN SMALL LETTER H 69 | 00000069 | LATIN SMALL LETTER I 6A | 0000006A | LATIN SMALL LETTER J 6B | 0000006B | LATIN SMALL LETTER K 6C | 0000006C | LATIN SMALL LETTER L 6D | 0000006D | LATIN SMALL LETTER M 6E | 0000006E | LATIN SMALL LETTER N 6F | 0000006F | LATIN SMALL LETTER O 70 | 00000070 | LATIN SMALL LETTER P 71 | 00000071 | LATIN SMALL LETTER Q 72 | 00000072 | LATIN SMALL LETTER R 73 | 00000073 | LATIN SMALL LETTER S 74 | 00000074 | LATIN SMALL LETTER T 75 | 00000075 | LATIN SMALL LETTER U 76 | 00000076 | LATIN SMALL LETTER V 77 | 00000077 | LATIN SMALL LETTER W 78 | 00000078 | LATIN SMALL LETTER X 79 | 00000079 | LATIN SMALL LETTER Y 7A | 0000007A | LATIN SMALL LETTER Z 7B | 0000007B | LEFT CURLY BRACKET 7C | 0000007C | VERTICAL LINE 7D | 0000007D | RIGHT CURLY BRACKET 7E | 0000007E | TILDE 7F | 0000007F | DELETE (DEL) 80 | 000020AC | EURO SIGN 82 | 0000010C | LATIN CAPITAL LETTER C WITH CARON 83 | 00000192 | LATIN SMALL LETTER F WITH HOOK 84 | 0000010D | LATIN SMALL LETTER C WITH CARON 85 | 000001B7 | LATIN CAPITAL LETTER EZH 86 | 00000292 | LATIN SMALL LETTER EZH 87 | 000001EE | LATIN CAPITAL LETTER EZH WITH CARON 88 | 000001EF | LATIN SMALL LETTER EZH WITH CARON 89 | 00000110 | LATIN CAPITAL LETTER D WITH STROKE 8A | 00000160 | LATIN CAPITAL LETTER S WITH CARON 8B | 00002039 | SINGLE LEFT-POINTING ANGLE QUOTATION MARK 8C | 00000152 | LATIN CAPITAL LIGATURE OE 91 | 00002018 | LEFT SINGLE QUOTATION MARK 92 | 00002019 | RIGHT SINGLE QUOTATION MARK 93 | 0000201C | LEFT DOUBLE QUOTATION MARK 94 | 0000201D | RIGHT DOUBLE QUOTATION MARK 95 | 00002022 | BULLET 96 | 00002013 | EN DASH 97 | 00002014 | EM DASH 98 | 00000111 | LATIN SMALL LETTER D WITH STROKE 99 | 000001E6 | LATIN CAPITAL LETTER G WITH CARON 9A | 00000161 | LATIN SMALL LETTER S WITH CARON 9B | 0000203A | SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 9C | 00000153 | LATIN SMALL LIGATURE OE 9F | 00000178 | LATIN CAPITAL LETTER Y WITH DIAERESIS A0 | 000000A0 | NO-BREAK SPACE A1 | 000001E7 | LATIN SMALL LETTER G WITH CARON A2 | 000001E4 | LATIN CAPITAL LETTER G WITH STROKE A3 | 000000A3 | POUND SIGN A4 | 000000A4 | CURRENCY SIGN A5 | 000001E5 | LATIN SMALL LETTER G WITH STROKE A6 | 000000A6 | BROKEN BAR A7 | 000000A7 | SECTION SIGN A8 | 000000A8 | DIAERESIS A9 | 000000A9 | COPYRIGHT SIGN AA | 0000021E | LATIN CAPITAL LETTER H WITH CARON AB | 000000AB | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK AC | 000000AC | NOT SIGN AD | 000000AD | SOFT HYPHEN AE | 000000AE | REGISTERED SIGN AF | 0000021F | LATIN SMALL LETTER H WITH CARON B0 | 000000B0 | DEGREE SIGN B1 | 000000B1 | PLUS-MINUS SIGN B2 | 000001E8 | LATIN CAPITAL LETTER K WITH CARON B3 | 000001E9 | LATIN SMALL LETTER K WITH CARON B4 | 000000B4 | ACUTE ACCENT B5 | 000000B5 | MICRO SIGN B6 | 000000B6 | PILCROW SIGN B7 | 000000B7 | MIDDLE DOT B8 | 0000014A | LATIN CAPITAL LETTER ENG (Sami) B9 | 0000014B | LATIN SMALL LETTER ENG (Sami) BA | 00000166 | LATIN CAPITAL LETTER T WITH STROKE BB | 000000BB | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK BC | 00000167 | LATIN SMALL LETTER T WITH STROKE BD | 000000BD | VULGAR FRACTION ONE HALF BE | 0000017D | LATIN CAPITAL LETTER Z WITH CARON BF | 0000017E | LATIN SMALL LETTER Z WITH CARON C0 | 000000C0 | LATIN CAPITAL LETTER A WITH GRAVE C1 | 000000C1 | LATIN CAPITAL LETTER A WITH ACUTE C2 | 000000C2 | LATIN CAPITAL LETTER A WITH CIRCUMFLEX C3 | 000000C3 | LATIN CAPITAL LETTER A WITH TILDE C4 | 000000C4 | LATIN CAPITAL LETTER A WITH DIAERESIS C5 | 000000C5 | LATIN CAPITAL LETTER A WITH RING ABOVE C6 | 000000C6 | LATIN CAPITAL LETTER AE C7 | 000000C7 | LATIN CAPITAL LETTER C WITH CEDILLA C8 | 000000C8 | LATIN CAPITAL LETTER E WITH GRAVE C9 | 000000C9 | LATIN CAPITAL LETTER E WITH ACUTE CA | 000000CA | LATIN CAPITAL LETTER E WITH CIRCUMFLEX CB | 000000CB | LATIN CAPITAL LETTER E WITH DIAERESIS CC | 000000CC | LATIN CAPITAL LETTER I WITH GRAVE CD | 000000CD | LATIN CAPITAL LETTER I WITH ACUTE CE | 000000CE | LATIN CAPITAL LETTER I WITH CIRCUMFLEX CF | 000000CF | LATIN CAPITAL LETTER I WITH DIAERESIS D0 | 000000D0 | LATIN CAPITAL LETTER ETH (Icelandic) D1 | 000000D1 | LATIN CAPITAL LETTER N WITH TILDE D2 | 000000D2 | LATIN CAPITAL LETTER O WITH GRAVE D3 | 000000D3 | LATIN CAPITAL LETTER O WITH ACUTE D4 | 000000D4 | LATIN CAPITAL LETTER O WITH CIRCUMFLEX D5 | 000000D5 | LATIN CAPITAL LETTER O WITH TILDE D6 | 000000D6 | LATIN CAPITAL LETTER O WITH DIAERESIS D7 | 000000D7 | MULTIPLICATION SIGN D8 | 000000D8 | LATIN CAPITAL LETTER O WITH STROKE D9 | 000000D9 | LATIN CAPITAL LETTER U WITH GRAVE DA | 000000DA | LATIN CAPITAL LETTER U WITH ACUTE DB | 000000DB | LATIN CAPITAL LETTER U WITH CIRCUMFLEX DC | 000000DC | LATIN CAPITAL LETTER U WITH DIAERESIS DD | 000000DD | LATIN CAPITAL LETTER Y WITH ACUTE DE | 000000DE | LATIN CAPITAL LETTER THORN (Icelandic) DF | 000000DF | LATIN SMALL LETTER SHARP S (German) E0 | 000000E0 | LATIN SMALL LETTER A WITH GRAVE E1 | 000000E1 | LATIN SMALL LETTER A WITH ACUTE E2 | 000000E2 | LATIN SMALL LETTER A WITH CIRCUMFLEX E3 | 000000E3 | LATIN SMALL LETTER A WITH TILDE E4 | 000000E4 | LATIN SMALL LETTER A WITH DIAERESIS E5 | 000000E5 | LATIN SMALL LETTER A WITH RING ABOVE E6 | 000000E6 | LATIN SMALL LETTER AE E7 | 000000E7 | LATIN SMALL LETTER C WITH CEDILLA E8 | 000000E8 | LATIN SMALL LETTER E WITH GRAVE E9 | 000000E9 | LATIN SMALL LETTER E WITH ACUTE EA | 000000EA | LATIN SMALL LETTER E WITH CIRCUMFLEX EB | 000000EB | LATIN SMALL LETTER E WITH DIAERESIS EC | 000000EC | LATIN SMALL LETTER I WITH GRAVE ED | 000000ED | LATIN SMALL LETTER I WITH ACUTE EE | 000000EE | LATIN SMALL LETTER I WITH CIRCUMFLEX EF | 000000EF | LATIN SMALL LETTER I WITH DIAERESIS F0 | 000000F0 | LATIN SMALL LETTER ETH (Icelandic) F1 | 000000F1 | LATIN SMALL LETTER N WITH TILDE F2 | 000000F2 | LATIN SMALL LETTER O WITH GRAVE F3 | 000000F3 | LATIN SMALL LETTER O WITH ACUTE F4 | 000000F4 | LATIN SMALL LETTER O WITH CIRCUMFLEX F5 | 000000F5 | LATIN SMALL LETTER O WITH TILDE F6 | 000000F6 | LATIN SMALL LETTER O WITH DIAERESIS F7 | 000000F7 | DIVISION SIGN F8 | 000000F8 | LATIN SMALL LETTER O WITH STROKE F9 | 000000F9 | LATIN SMALL LETTER U WITH GRAVE FA | 000000FA | LATIN SMALL LETTER U WITH ACUTE FB | 000000FB | LATIN SMALL LETTER U WITH CIRCUMFLEX FC | 000000FC | LATIN SMALL LETTER U WITH DIAERESIS FD | 000000FD | LATIN SMALL LETTER Y WITH ACUTE FE | 000000FE | LATIN SMALL LETTER THORN (Icelandic) FF | 000000FF | LATIN SMALL LETTER Y WITH DIAERESIS =head1 AUTHOR Copyright (C) 2002-2009, Guido Flohr E<lt>guido@imperia.netE<gt>, all rights reserved. See the source code for details. This software is contributed to the Perl community by Imperia (L<http://www.imperia.net/>). =head1 SEE ALSO Locale::RecodeData(3), Locale::Recode(3), perl(1) =cut Local Variables: mode: perl perl-indent-level: 4 perl-continued-statement-offset: 4 perl-continued-brace-offset: 0 perl-brace-offset: -4 perl-brace-imaginary-offset: 0 perl-label-offset: -4 cperl-indent-level: 4 cperl-continued-statement-offset: 2 tab-width: 4 End: =cut
cgwalters/texinfo-git-mirror
tp/maintain/lib/libintl-perl/lib/Locale/RecodeData/SAMI_WS2.pm
Perl
gpl-3.0
27,791
#define SYSTEM_APP_EB 1 //embedded #define SYSTEM_APP_BB 0 //baseband only extern bdata unsigned char system_config_flag; extern bit system_app_fg;
flake123p/ProjectH
8051/B01_2Projects/boot.h
C
gpl-3.0
163
/* Copyright IBM Corp. 2010, 2016 This file is part of Anomaly Detection Engine for Linux Logs (ADE). ADE 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. ADE 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 ADE. If not, see <http://www.gnu.org/licenses/>. */ package org.openmainframe.ade.impl.dataStore; import org.openmainframe.ade.Ade; import org.openmainframe.ade.dbUtils.ConnectionWrapper; import org.openmainframe.ade.dbUtils.DriverType; import org.openmainframe.ade.exceptions.AdeException; import org.openmainframe.ade.impl.dbUtils.TableGeneralUtils; public class TableManager { /** * List of all table names in dependency order, * i.e, if B depends on A then A will appear first * */ private static final SQL[] ALL_TABLES = { SQL.MESSAGE_IDS, SQL.COMPONENT_IDS, SQL.RULES, SQL.GROUPS, SQL.SOURCES, SQL.PERIODS, SQL.PERIOD_SUMMARIES, SQL.ADE_VERSIONS, SQL.MODELS, SQL.TEXT_CLUSTERS, SQL.MESSAGE_SUMMARIES, SQL.INTERVALS, SQL.ANALYSIS_RESULTS }; /** * Invokes methods to create tables, indexes, and set version of database definition * @param * @throws AdeException */ public final void createAll() throws AdeException { createTables(ALL_TABLES); createIndices(); initTables(); } /** * Creates database tables * @param tables * @throws AdeException */ public static void createTables(SQL... tables) throws AdeException { for (SQL table : tables) { final String sql = String.format("create table %s (%s)", table.toString(), table.create()); ConnectionWrapper.executeDmlDefaultCon(sql); } } /** * Builds list of database tables in reverse order (order tables need to be dropped in) * @return */ public final SQL[] getAllTablesInReverseDependencyOrder() { final SQL[] res = new SQL[ALL_TABLES.length]; for (int i = 0; i < ALL_TABLES.length; ++i) { res[i] = ALL_TABLES[ALL_TABLES.length - i - 1]; } return res; } /** * Deletes all tables one at a time in reverse order of creation * @throws AdeException */ public final void deleteAll() throws AdeException { deleteTables(getAllTablesInReverseDependencyOrder()); } /** * Deletes a table * @param tables - name of table * @throws AdeException */ public final void deleteTables(SQL[] tables) throws AdeException { if (tables == null) { return; } for (SQL table : tables) { TableGeneralUtils.deleteTable(table.toString()); } } /** * Drops all tables one at a time in reverse order of creation * @throws AdeException */ public final void dropAll() throws AdeException { dropTables(getAllTablesInReverseDependencyOrder()); } /** * Drops a table * @param tables - name of table * @throws AdeException */ public final void dropTables(SQL[] tables) throws AdeException { if (tables == null) { return; } for (int i = 0; i < tables.length; i++) { TableGeneralUtils.dropTable(tables[i].toString()); } } public final void printAll() throws AdeException { printTables(ALL_TABLES); } /** * Creates indicies * @throws AdeException */ private void createIndices() throws AdeException { ConnectionWrapper.executeDmlDefaultCon("create index message_summaries_by_period_summary_internal_id on " + SQL.MESSAGE_SUMMARIES + " (PERIOD_SUMMARY_INTERNAL_ID)"); ConnectionWrapper.executeDmlDefaultCon("create index ANALYSIS_GROUP_INDEX on "+SQL.SOURCES+" (ANALYSIS_GROUP)"); } /** * Initializes the Ade Version table with version and current time * @throws AdeException */ final void initTables() throws AdeException { // set the version to be the current one final String driver = Ade.getAde().getConfigProperties().database().getDatabaseDriver(); String query = "insert into " + SQL.ADE_VERSIONS + " (ADE_VERSION, PATCHED_TIME) values ('" + Ade.getAde().getDbVersion() + "', current timestamp)"; if ((DriverType.parseDriverType(driver) == DriverType.MY_SQL) || (DriverType.parseDriverType(driver) == DriverType.MARIADB)) { query = query.replace("current timestamp", "current_timestamp"); } ConnectionWrapper.executeDmlDefaultCon(query); } public final void printTables(SQL[] tables) throws AdeException { if (tables == null) { return; } for (int i = 0; i < tables.length; i++) { TableGeneralUtils.printTable(tables[i].toString()); } } }
openmainframeproject/ade
ade-core/src/main/java/org/openmainframe/ade/impl/dataStore/TableManager.java
Java
gpl-3.0
5,434
#!/usr/bin/python3 import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes") def get_registries(): registries = [] directories = os.listdir(PREFIXES_PATH) directories.append(os.path.expanduser("~/.wine")) for prefix in directories: for path in os.listdir(os.path.join(PREFIXES_PATH, prefix)): if path.endswith(".reg"): registries.append(os.path.join(PREFIXES_PATH, prefix, path)) return registries def check_registry(registry_path): with open(registry_path, 'r') as registry_file: original_content = registry_file.read() try: registry = WineRegistry(registry_path) except: sys.stderr.write("Error parsing {}\n".format(registry_path)) raise content = registry.render() if content != original_content: wrong_path = os.path.join(os.path.dirname(__file__), 'error.reg') with open(wrong_path, 'w') as wrong_reg: wrong_reg.write(content) print("Content of parsed registry doesn't match: {}".format(registry_path)) subprocess.call(["meld", registry_path, wrong_path]) sys.exit(2) registries = get_registries() for registry in registries: check_registry(registry) print("All {} registry files validated!".format(len(registries)))
RobLoach/lutris
tests/check_prefixes.py
Python
gpl-3.0
1,465
/** * Macchiato : Mobile and Web application offloading Copyright (C) 2013 Nicolas * Petitprez * * 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 FutureJS require('../../../src/main/javascript/websocket-node-adapter.js'); require('../../main/javascript/futuresjs/future.js'); require('../../main/javascript/futuresjs/sequence.js'); require('../../main/javascript/futuresjs/chainify.js'); require('../../main/javascript/futuresjs/join.js'); // macchiato EB libraries require('../../main/javascript/macchiato-commons.js'); require('../../main/javascript/macchiato-eb.js'); // test require('./qunit-server.js'); require('../javascript/eventbus.js'); run();
petitpre/Macchiato-eventbus
src/test/server/testLauncher.js
JavaScript
gpl-3.0
1,272
--created & coded by Lyris --Ragna Clarissa of Stellar Vine function c101010217.initial_effect(c) --refill Once per turn, during either player's turn, when a banished "Stellar Vine" monster is returned to the Graveyard: you can banish 1 "Stellar Vine" monster from your Deck. If this card would be sent to the Graveyard from the field or as an Xyz Material, banish it instead. local ae3=Effect.CreateEffect(c) ae3:SetCategory(CATEGORY_REMOVE) ae3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) ae3:SetCode(EVENT_TO_GRAVE) ae3:SetRange(LOCATION_MZONE) ae3:SetCountLimit(1) ae3:SetCondition(c101010217.condition) ae3:SetTarget(c101010217.target) ae3:SetOperation(c101010217.operation) c:RegisterEffect(ae3) if not c101010217.global_check then c101010217.global_check=true local ge2=Effect.CreateEffect(c) ge2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge2:SetCode(EVENT_ADJUST) ge2:SetCountLimit(1) ge2:SetProperty(EFFECT_FLAG_NO_TURN_RESET) ge2:SetOperation(c101010217.chk) Duel.RegisterEffect(ge2,0) end end c101010217.spatial=true --Spatial Formula filter(s) c101010217.material=function(mc) return mc:IsAttribute(ATTRIBUTE_WATER) and mc:IsSetCard(0x785e) end function c101010217.chk(e,tp,eg,ep,ev,re,r,rp) Duel.CreateToken(tp,500) Duel.CreateToken(1-tp,500) end --when a banished "Stellar Vine" monster is returned to the Graveyard function c101010217.condition(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(Card.IsSetCard,1,nil,0x785e) end --you can banish 1 "Stellar Vine" monster from your Deck. function c101010217.filter2(c) return c:IsSetCard(0x785e) and c:IsAbleToRemove() end function c101010217.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c101010217.filter2,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK) end function c101010217.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c101010217.filter2,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.Remove(g,POS_FACEUP,REASON_EFFECT) end end
RisingPhoenixYGOPRO/YGOPro-Custom-Cards
script/c101010217.lua
Lua
gpl-3.0
2,103
<!doctype html> <html> <head> <meta charset="utf-8" /> <link href="css/foundation.min.css" rel="stylesheet" type="text/css" /> <title>Homepage</title> </head> <body> <div id="container"> <div id="header" class="row"> <div id="logo" class="medium-2 columns"> <img src="imgs/cat2.jpg" /> </div> <ul class="medium-2 columns"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> </div> <div id="main"> <div class="row"> <div class="columns medium-12"> <h1>Title</h1> </div> </div> <div class="row"> <div class="columns medium-6"> <p>Sunt arbitrantur deserunt irure voluptate ad tamen laboris consectetur hic occaecat ipsum labore ingeniis labore aut id magna praetermissum quo tamen voluptatibus consequat velit mentitum, a fore lorem eu quibusdam o voluptate hic aute mentitum sed velit ea nostrud ut magna. Possumus te elit admodum, incurreret noster quis expetendis veniam, multos quo laborum ad multos, aute occaecat ne enim quorum. De malis legam anim ullamco ex de summis minim fugiat incurreret. Culpa deserunt hic exercitation ita proident quid nisi cernantur quorum qui minim fabulas sed commodo ita eram voluptate deserunt. Deserunt sed sint. Enim occaecat o coniunctione, quae probant o fabulas aut iis se despicationes a consequat multos doctrina officia, lorem voluptatibus excepteur magna possumus, admodum noster anim de velit, commodo quae veniam tempor enim, ad incididunt si consequat. Voluptate multos quamquam qui proident noster eram litteris quid an velit admodum te iudicem, et cillum summis qui incididunt, arbitror magna non mentitum praetermissum est iis ullamco graviterque, si id distinguantur e lorem occaecat distinguantur.</p> </div> <div class="columns medium-4"> <img src="imgs/cat.jpg" /> </div> </div> <div class="row"> <div class="columns medium-12"> <p>Ad est eram possumus. Multos et ab cillum laboris, si quem nostrud. Se quae varias e possumus id minim quamquam in probant ab fugiat sed de dolore aliquip, quo fore veniam varias possumus. Fugiat ad cupidatat aut elit possumus ullamco quo minim occaecat nam voluptate a se legam nescius deserunt. Ea et cillum fabulas, voluptate tractavissent et mentitum. Malis ingeniis se nulla esse, possumus quem magna mandaremus irure. Multos offendit hic noster summis, de summis ad summis, laboris labore quamquam fabulas sed quis instituendarum nescius tamen possumus.</p> </div> </div> </div> </div> </body> </html>
brianmacmillan/BMCC-MMP350
spring 2016 class/week5/desktop/blank.html
HTML
gpl-3.0
3,657
var searchData= [ ['mainthreadid',['MainThreadID',['../classMezzanine_1_1Threading_1_1FrameScheduler.html#a9e78999f8224259b438874034a7f68c1',1,'Mezzanine::Threading::FrameScheduler']]], ['marg',['mArg',['../structMezzanine_1_1Threading_1_1__thread__start__info.html#a222f0b4b2db625b87a83a5d5e5ac6058',1,'Mezzanine::Threading::_thread_start_info']]], ['maxint',['MaxInt',['../namespaceMezzanine.html#ad7ab1b85229be184e16d96c505143f9b',1,'Mezzanine']]], ['mezz_5fdagframescheduler_5fmajor_5fversion',['MEZZ_DAGFRAMESCHEDULER_MAJOR_VERSION',['../dagframescheduler_8h.html#a1c7dd991646a7cd3c560290de4a0c023',1,'dagframescheduler.h']]], ['mezz_5fdagframescheduler_5fminor_5fversion',['MEZZ_DAGFRAMESCHEDULER_MINOR_VERSION',['../dagframescheduler_8h.html#ad10fe0ebc78e77428ec9a489a0235e60',1,'dagframescheduler.h']]], ['mezz_5fdagframescheduler_5frevision_5fversion',['MEZZ_DAGFRAMESCHEDULER_REVISION_VERSION',['../dagframescheduler_8h.html#a999f430c652e796f2eca639234bcd7dc',1,'dagframescheduler.h']]], ['mezz_5fdebug',['MEZZ_DEBUG',['../crossplatformexport_8h.html#a71ff5bc7f0f85f601fab126a57a41998',1,'crossplatformexport.h']]], ['mezz_5fframestotrack',['MEZZ_FRAMESTOTRACK',['../crossplatformexport_8h.html#ac384449f00498b42a495646c6aecfb8f',1,'crossplatformexport.h']]], ['mezz_5flib',['MEZZ_LIB',['../crossplatformexport_8h.html#a455f91aab9e6a1cf4286f5cdfa74c7bc',1,'crossplatformexport.h']]], ['mezz_5fuseatomicstodecachecompletework',['MEZZ_USEATOMICSTODECACHECOMPLETEWORK',['../crossplatformexport_8h.html#a491f7cf4e0e45f1f6e9a0098eff815a0',1,'crossplatformexport.h']]], ['mezz_5fusebarrierseachframe',['MEZZ_USEBARRIERSEACHFRAME',['../crossplatformexport_8h.html#a922f06bad05fd18425c1c933801686d3',1,'crossplatformexport.h']]], ['mezzanine',['Mezzanine',['../namespaceMezzanine.html',1,'']]], ['mfunction',['mFunction',['../structMezzanine_1_1Threading_1_1__thread__start__info.html#ad4cabd162418e28d383e711813651ea7',1,'Mezzanine::Threading::_thread_start_info']]], ['monopoly_2ecpp',['monopoly.cpp',['../monopoly_8cpp.html',1,'']]], ['monopoly_2eh',['monopoly.h',['../monopoly_8h.html',1,'']]], ['monopolyworkunit',['MonopolyWorkUnit',['../classMezzanine_1_1Threading_1_1MonopolyWorkUnit.html',1,'Mezzanine::Threading']]], ['mthread',['mThread',['../structMezzanine_1_1Threading_1_1__thread__start__info.html#a61f3bd5244b27c641d76e88b16336a1b',1,'Mezzanine::Threading::_thread_start_info']]], ['mutex',['Mutex',['../classMezzanine_1_1Threading_1_1Mutex.html#a78bb489f3977d4a3860e1c15d8d2d612',1,'Mezzanine::Threading::Mutex']]], ['mutex',['Mutex',['../classMezzanine_1_1Threading_1_1Mutex.html',1,'Mezzanine::Threading']]], ['mutex_2ecpp',['mutex.cpp',['../mutex_8cpp.html',1,'']]], ['mutex_2eh',['mutex.h',['../mutex_8h.html',1,'']]], ['mutex_5ftype',['mutex_type',['../classMezzanine_1_1Threading_1_1lock__guard.html#ab2205a43e3b1714fd4d3d00123ff4aeb',1,'Mezzanine::Threading::lock_guard::mutex_type()'],['../classMezzanine_1_1Threading_1_1ReadOnlyLockGuard.html#a7eb48add6b1fe022df74bda865f8cb6d',1,'Mezzanine::Threading::ReadOnlyLockGuard::mutex_type()'],['../classMezzanine_1_1Threading_1_1ReadWriteLockGuard.html#a12cc44e2f54d948cbb656c6c152ce57d',1,'Mezzanine::Threading::ReadWriteLockGuard::mutex_type()']]], ['this_5fthread',['this_thread',['../namespaceMezzanine_1_1Threading_1_1this__thread.html',1,'Mezzanine::Threading']]], ['threading',['Threading',['../namespaceMezzanine_1_1Threading.html',1,'Mezzanine']]] ];
BlackToppStudios/DAGFrameScheduler
doc/html/search/all_6d.js
JavaScript
gpl-3.0
3,480
/** * Copyright 2017–2019, LaborX PTY * Licensed under the AGPL Version 3 license. */ export const TX_ASSET_CREATED = 'AssetCreated'
ChronoBank/ChronoMint
packages/core/dao/constants/PlatformTokenExtensionGatewayManagerEmitterDAO.js
JavaScript
gpl-3.0
139
#include <iostream> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #include <boost/function.hpp> #pragma GCC diagnostic pop struct Speaker { Speaker(const std::string hello_message, const std::string bye_message) : m_hello_message(hello_message), m_bye_message(bye_message) { } void SayHello() const { std::cout << m_hello_message << '\n'; } void SayBye() const { std::cout << m_bye_message << '\n'; } const std::string m_hello_message; const std::string m_bye_message; }; int main() { const Speaker s1("Hello!","Bye!"); const Speaker s2("HELLO!","BYE!"); const boost::function<void (const Speaker*)> say_hello_function = &Speaker::SayHello; const boost::function<void (const Speaker*)> say_bye_function = &Speaker::SayBye; say_hello_function(&s1); say_bye_function(&s1); say_hello_function(&s2); say_bye_function(&s2); } /* Screen output: Hello! Bye! HELLO! BYE! Press <RETURN> to close this window... */
richelbilderbeek/CppTests
CppBoostFunctionExample2/main.cpp
C++
gpl-3.0
1,038
<?php /** * This file is part of GESSEH project * * @author: Pierre-François ANGRAND <pigass@medlibre.fr> * @copyright: Copyright 2013-2020 Pierre-François Angrand * @license: GPLv3 * See LICENSE file or http://www.gnu.org/licenses/gpl.html */ namespace App\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\TextType, Symfony\Component\Form\Extension\Core\Type\DateType; /** * SimulPeriodType */ class SimulPeriodType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('begin', DateType::class, [ 'label' => 'Début des simulations', 'help' => 'En l\'absence de calendrier, indiquez la date au format "AAAA-MM-JJ"', 'input' => 'string', 'widget' => 'single_text', 'html5' => true, 'mapped' => false, 'attr' => ['placeholder' => 'AAAA-MM-JJ'], ]) ->add('end', DateType::class, [ 'label' => 'Fin des simulations', 'help' => 'En l\'absence de calendrier, indiquez la date au format "AAAA-MM-JJ"', 'input' => 'string', 'widget' => 'single_text', 'html5' => true, 'mapped' => false, 'attr' => ['placeholder' => 'AAAA-MM-JJ'], ]) ; } public function configureOptions(\Symfony\Component\OptionsResolver\OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'App\Entity\SimulPeriod', )); } }
CaraGk/pigass
src/Form/SimulPeriodType.php
PHP
gpl-3.0
1,734
<?php /** * Abstract class for RESTful controllers acting on a storage * * @package framewub/rest * @author Wubbo Bos <wubbo@wubbobos.nl> * @copyright Copyright (c) Wubbo Bos * @license GPL * @link https://github.com/wubmeister/framewub */ namespace Framewub\Rest; use Framewub\Http\Message\ServerRequest; abstract class StorageAction extends AbstractAction { /** * Indicates an insert action */ const INSERT = 1; /** * Indicates an update action */ const UPDATE = 2; /** * The storage object to work with * * @var Framewub\Storage\Db\AbstractStorage */ protected $storage; /** * These are the callback methods which can be implemented. * * @var array */ protected static $callbackMethods = [ 'buildIndexQuery', 'buildDetailQuery', 'beforeDelete', 'postprocessIndex', 'postprocessDetail', 'postprocessInsert', 'postprocessUpdate', 'postprocessDelete' ]; /** * This method should return a new storage object, which te controller can * work with * * @return Framewub\Storage\Db\AbstractStorage * The storage */ abstract protected function getStorage(); /** * Handles a request and gives a response * * @param Framewub\Http\Message\ServerRequest $request * The request * * @return Framewub\Http\Message\Response * The response */ public function __invoke(ServerRequest $request) { $this->storage = $this->getStorage(); return parent::__invoke($request); } /** * Checks if the undefined method which is called is a known callback. If it * is, this method will grecefully return true. If not, this will throw an * exception * * @param string $name * The method name * @param array $args * The arguments * * @return bool * Returns true if the method is a known callback * @throws RuntimeException if the method is not a known callback */ public function __call($name, $args) { if (!in_array($name, self::$callbackMethods)) { throw new RuntimeException("Method {$name} dosn't exist"); } return true; } /** * Returns all the items in the collection * * @return Framewub\Storage\Db\Rowset */ protected function findAll() { $query = []; $this->buildIndexQuery($query); $result = $this->storage->find($query); $this->postprocessIndex($result); return $result; } /** * Returns a single item from the collection * * @param mixed $id * The ID * * @return Framewub\Storage\StorageObject */ protected function findById($id) { $query = []; $this->buildDetailQuery($query); $obj = $this->storage->findOne($id); $this->postprocessDetail($obj); return $obj; } /** * Adds an object to the collection * * @param array $values * The values for the new object * * @return Framewub\Storage\StorageObject * The newly created object */ protected function add($values) { $values = $this->filterValues($values, self::INSERT); $id = $this->storage->insert($values); $obj = $this->storage->findOne($id); $this->postprocessInsert($obj); return $obj; } /** * Updates an object in the collection with the specified ID, using the * specfied values * * @param mixed $id * The ID * @param array $values * The new values for the object * * @return Framewub\Storage\StorageObject * The modified version of the object */ protected function update($id, $values) { $values = $this->filterValues($values, self::UPDATE); $this->storage->update($values, $id); $obj = $this->storage->findOne($id); $this->postprocessUpdate($obj); return $obj; } /** * Deletes an object with the specified ID from the collection * * @param mixed $id * The ID * * @return array * The result of the delete action. Contains at least the keys 'success' * (bool) and 'id', the latter being the ID of the deleted object. */ protected function delete($id) { $result = [ 'success' => false, 'id' => $id ]; if ($this->beforeDelete()) { $obj = $this->storage->findOne($id); if ($obj && $this->storage->delete($id)) { $result['success'] = true; $this->postprocessDelete($obj); } } return $result; } }
wubmeister/framewub
src/Rest/StorageAction.php
PHP
gpl-3.0
4,818
<?php /************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko * Website: https://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ namespace Espo\Core\Di; use Espo\Core\Record\ServiceContainer as RecordServiceContainer; interface RecordServiceContainerAware { public function setRecordServiceContainer(RecordServiceContainer $recordServiceContainer); }
ayman-alkom/espocrm
application/Espo/Core/Di/RecordServiceContainerAware.php
PHP
gpl-3.0
1,591
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ Espo.define('views/admin/layouts/modals/edit-attributes', ['views/modal', 'model'], function (Dep, Model) { return Dep.extend({ _template: '<div class="edit-container">{{{edit}}}</div>', setup: function () { this.buttonList = [ { name: 'save', text: this.translate('Apply'), style: 'primary' }, { name: 'cancel', text: 'Cancel' } ]; var model = new Model(); model.name = 'LayoutManager'; model.set(this.options.attributes || {}); this.header = this.translate(this.options.name, 'fields', this.options.scope); var attributeList = Espo.Utils.clone(this.options.attributeList || []); var index = attributeList.indexOf('name'); if (~index) { attributeList.splice(index, 1); } this.createView('edit', 'Admin.Layouts.Record.EditAttributes', { el: this.options.el + ' .edit-container', attributeList: attributeList, attributeDefs: this.options.attributeDefs, model: model }); }, actionSave: function () { var editView = this.getView('edit'); var attrs = editView.fetch(); editView.model.set(attrs, {silent: true}); if (editView.validate()) { return; } var attributes = {}; attributes = editView.model.attributes; this.trigger('after:save', attributes); return true; }, }); });
IgorGulyaev/iteamzen
client/src/views/admin/layouts/modals/edit-attributes.js
JavaScript
gpl-3.0
3,096
#include "dietstdio.h" char *fgets_unlocked(char *s, int size, FILE *stream) { int l; for (l=0; l<size; ) { register int c; if (l && __likely(stream->bm<stream->bs)) { /* try common case first */ c=(unsigned char)stream->buf[stream->bm++]; } else { c=fgetc_unlocked(stream); if (__unlikely(c==EOF)) { if (!l) return 0; goto fini; } } s[l]=c; ++l; if (c=='\n') { fini: s[l]=0; return s; } } return 0; } char*fgets(char*s,int size,FILE*stream) __attribute__((weak,alias("fgets_unlocked")));
DemonSinusa/SiemanC
Platform/loaders/ElfLoader3/dev/lib_src/dietlibc/src/libstdio/fgets.c
C
gpl-3.0
575
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>PRPA_MT201310UV02.Subject2 complex typeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * * <pre> * &lt;complexType name="PRPA_MT201310UV02.Subject2"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/> * &lt;element name="position" type="{urn:hl7-org:v3}COCT_MT960000UV05.Position"/> * &lt;/sequence> * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="typeCode" use="required" type="{urn:hl7-org:v3}ParticipationTargetSubject" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PRPA_MT201310UV02.Subject2", propOrder = { "realmCode", "typeId", "templateId", "position" }) public class PRPAMT201310UV02Subject2 { protected List<CS> realmCode; protected II typeId; protected List<II> templateId; @XmlElement(required = true, nillable = true) protected COCTMT960000UV05Position position; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "typeCode", required = true) protected ParticipationTargetSubject typeCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * typeIdプロパティの値を取得します。 * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * typeIdプロパティの値を設定します。 * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * positionプロパティの値を取得します。 * * @return * possible object is * {@link COCTMT960000UV05Position } * */ public COCTMT960000UV05Position getPosition() { return position; } /** * positionプロパティの値を設定します。 * * @param value * allowed object is * {@link COCTMT960000UV05Position } * */ public void setPosition(COCTMT960000UV05Position value) { this.position = value; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * typeCodeプロパティの値を取得します。 * * @return * possible object is * {@link ParticipationTargetSubject } * */ public ParticipationTargetSubject getTypeCode() { return typeCode; } /** * typeCodeプロパティの値を設定します。 * * @param value * allowed object is * {@link ParticipationTargetSubject } * */ public void setTypeCode(ParticipationTargetSubject value) { this.typeCode = value; } }
ricecakesoftware/CommunityMedicalLink
ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/PRPAMT201310UV02Subject2.java
Java
gpl-3.0
6,019
<?php /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <brian@nesbot.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Authors: * - Philippe Vaucher * - Tsutomu Kuroda * - tjku * - valdas406 * - Justas Palumickas * - Max Melentiev * - Andrius Janauskas * - Juanito Fatas * - Akira Matsuda * - Christopher Dell * - Enrique Vidal * - Simone Carletti * - Aaron Patterson * - Nicolás Hock Isaza * - Laurynas Butkus * - Sven Fuchs * - Dominykas Tijūnaitis * - Justinas Bolys * - Ričardas * - Kirill Chalkin * - Rolandas */ return [ 'year' => ':count metus|:count metus|:count metų', 'y' => ':count metus|:count metus|:count metų', 'month' => ':count mėnesį|:count mėnesius|:count mėnesių', 'm' => ':count mėnesį|:count mėnesius|:count mėnesių', 'week' => ':count savaitę|:count savaites|:count savaičių', 'w' => ':count savaitę|:count savaites|:count savaičių', 'day' => ':count dieną|:count dienas|:count dienų', 'd' => ':count dieną|:count dienas|:count dienų', 'hour' => ':count valandą|:count valandas|:count valandų', 'h' => ':count valandą|:count valandas|:count valandų', 'minute' => ':count minutę|:count minutes|:count minučių', 'min' => ':count minutę|:count minutes|:count minučių', 'second' => ':count sekundę|:count sekundes|:count sekundžių', 's' => ':count sekundę|:count sekundes|:count sekundžių', 'second_from_now' => ':count sekundės|:count sekundžių|:count sekundžių', 'minute_from_now' => ':count minutės|:count minučių|:count minučių', 'hour_from_now' => ':count valandos|:count valandų|:count valandų', 'day_from_now' => ':count dienos|:count dienų|:count dienų', 'week_from_now' => ':count savaitės|:count savaičių|:count savaičių', 'month_from_now' => ':count mėnesio|:count mėnesių|:count mėnesių', 'year_from_now' => ':count metų', 'ago' => 'prieš :time', 'from_now' => 'už :time', 'after' => 'po :time', 'before' => ':time nuo dabar', 'first_day_of_week' => 1, 'day_of_first_week_of_year' => 4, 'diff_now' => 'ką tik', 'diff_yesterday' => 'vakar', 'diff_tomorrow' => 'rytoj', 'diff_before_yesterday' => 'užvakar', 'diff_after_tomorrow' => 'poryt', 'period_recurrences' => 'kartą|:count kartų', 'period_interval' => 'kiekvieną :interval', 'period_start_date' => 'nuo :date', 'period_end_date' => 'iki :date', 'months' => ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis'], 'months_short' => ['Sau', 'Vas', 'Kov', 'Bal', 'Geg', 'Bir', 'Lie', 'Rgp', 'Rgs', 'Spa', 'Lap', 'Gru'], 'weekdays' => ['Sekmadienis', 'Pirmadienis', 'Antradienis', 'Trečiadienis', 'Ketvirtadienis', 'Penktadienis', 'Šeštadienis'], 'weekdays_short' => ['Sek', 'Pir', 'Ant', 'Tre', 'Ket', 'Pen', 'Šeš'], 'weekdays_min' => ['Se', 'Pi', 'An', 'Tr', 'Ke', 'Pe', 'Še'], 'list' => [', ', ' ir '], 'formats' => [ 'LT' => 'HH:mm', 'LTS' => 'HH:mm:ss', 'L' => 'YYYY-MM-DD', 'LL' => 'MMMM DD, YYYY', 'LLL' => 'DD MMM HH:mm', 'LLLL' => 'MMMM DD, YYYY HH:mm', ], ];
OSTraining/OSDownloads
src/admin/vendor/nesbot/carbon/src/Carbon/Lang/lt.php
PHP
gpl-3.0
3,379
ul.tree-menu li div a.blog_item, ul.tree-menu li div a.type_blog_item, .treeview .list-group .list-group-item .icon.node-icon.type_blog_item, .treeview .list-group .list-group-item .icon.node-icon.type_blog_item_default, ul.tree-menu li div a.type_blog_item_default { background-image: url(../../Images/Aqua/Logo/16.png); }
vanpouckesven/cosnics
src/Chamilo/Core/Repository/ContentObject/BlogItem/Resources/Css/Aqua/Stylesheet.css
CSS
gpl-3.0
332
--- layout: politician2 title: navalmani.a.n profile: party: IND constituency: Namakkal state: Tamil Nadu education: level: 5th Pass details: 6th photo: sex: caste: religion: current-office-title: crime-accusation-instances: 0 date-of-birth: 1961 profession: networth: assets: liabilities: 0 pan: twitter: website: youtube-interview: wikipedia: candidature: - election: Lok Sabha 2009 myneta-link: http://myneta.info/ls2009/candidate.php?candidate_id=9024 affidavit-link: expenses-link: constituency: Namakkal party: IND criminal-cases: 0 assets: liabilities: 0 result: crime-record: date: 2014-01-28 version: 0.0.5 tags: --- ##Summary ##Education {% include "education.html" %} ##Political Career {% include "political-career.html" %} ##Criminal Record {% include "criminal-record.html" %} ##Personal Wealth {% include "personal-wealth.html" %} ##Public Office Track Record {% include "track-record.html" %} ##References {% include "references.html" %}
vaibhavb/wisevoter
site/politicians/_posts/2013-12-18-navalmani.a.n.md
Markdown
gpl-3.0
1,084
/* ide-autotools-autogen-stage.c * * Copyright 2016-2019 Christian Hergert <chergert@redhat.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/>. * * SPDX-License-Identifier: GPL-3.0-or-later */ #define G_LOG_DOMAIN "ide-autotools-autogen-stage" #include "ide-autotools-autogen-stage.h" struct _IdeAutotoolsAutogenStage { IdePipelineStage parent_instance; gchar *srcdir; }; G_DEFINE_FINAL_TYPE (IdeAutotoolsAutogenStage, ide_autotools_autogen_stage, IDE_TYPE_PIPELINE_STAGE) enum { PROP_0, PROP_SRCDIR, N_PROPS }; static GParamSpec *properties [N_PROPS]; static void ide_autotools_autogen_stage_wait_check_cb (GObject *object, GAsyncResult *result, gpointer user_data) { IdeSubprocess *subprocess = (IdeSubprocess *)object; g_autoptr(IdeTask) task = user_data; g_autoptr(GError) error = NULL; g_assert (IDE_IS_SUBPROCESS (subprocess)); g_assert (IDE_IS_TASK (task)); if (!ide_subprocess_wait_check_finish (subprocess, result, &error)) ide_task_return_error (task, g_steal_pointer (&error)); else ide_task_return_boolean (task, TRUE); } static void ide_autotools_autogen_stage_build_async (IdePipelineStage *stage, IdePipeline *pipeline, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { IdeAutotoolsAutogenStage *self = (IdeAutotoolsAutogenStage *)stage; g_autofree gchar *autogen_path = NULL; g_autoptr(IdeSubprocessLauncher) launcher = NULL; g_autoptr(IdeSubprocess) subprocess = NULL; g_autoptr(IdeTask) task = NULL; g_autoptr(GError) error = NULL; g_assert (IDE_IS_AUTOTOOLS_AUTOGEN_STAGE (self)); g_assert (!cancellable || G_IS_CANCELLABLE (cancellable)); task = ide_task_new (self, cancellable, callback, user_data); ide_task_set_source_tag (task, ide_autotools_autogen_stage_build_async); autogen_path = g_build_filename (self->srcdir, "autogen.sh", NULL); launcher = ide_pipeline_create_launcher (pipeline, &error); if (launcher == NULL) { ide_task_return_error (task, g_steal_pointer (&error)); return; } ide_subprocess_launcher_set_cwd (launcher, self->srcdir); if (g_file_test (autogen_path, G_FILE_TEST_IS_REGULAR)) { ide_subprocess_launcher_push_argv (launcher, autogen_path); ide_subprocess_launcher_setenv (launcher, "NOCONFIGURE", "1", TRUE); } else { ide_subprocess_launcher_push_argv (launcher, "autoreconf"); ide_subprocess_launcher_push_argv (launcher, "-fiv"); } subprocess = ide_subprocess_launcher_spawn (launcher, cancellable, &error); if (subprocess == NULL) { ide_task_return_error (task, g_steal_pointer (&error)); return; } ide_pipeline_stage_log_subprocess (stage, subprocess); ide_subprocess_wait_check_async (subprocess, cancellable, ide_autotools_autogen_stage_wait_check_cb, g_steal_pointer (&task)); } static gboolean ide_autotools_autogen_stage_build_finish (IdePipelineStage *stage, GAsyncResult *result, GError **error) { g_assert (IDE_IS_AUTOTOOLS_AUTOGEN_STAGE (stage)); g_assert (IDE_IS_TASK (result)); return ide_task_propagate_boolean (IDE_TASK (result), error); } static void ide_autotools_autogen_stage_finalize (GObject *object) { IdeAutotoolsAutogenStage *self = (IdeAutotoolsAutogenStage *)object; g_clear_pointer (&self->srcdir, g_free); G_OBJECT_CLASS (ide_autotools_autogen_stage_parent_class)->finalize (object); } static void ide_autotools_autogen_stage_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { IdeAutotoolsAutogenStage *self = (IdeAutotoolsAutogenStage *)object; switch (prop_id) { case PROP_SRCDIR: self->srcdir = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); } } static void ide_autotools_autogen_stage_class_init (IdeAutotoolsAutogenStageClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); IdePipelineStageClass *stage_class = IDE_PIPELINE_STAGE_CLASS (klass); object_class->finalize = ide_autotools_autogen_stage_finalize; object_class->set_property = ide_autotools_autogen_stage_set_property; stage_class->build_async = ide_autotools_autogen_stage_build_async; stage_class->build_finish = ide_autotools_autogen_stage_build_finish; properties [PROP_SRCDIR] = g_param_spec_string ("srcdir", NULL, NULL, NULL, G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS); g_object_class_install_properties (object_class, N_PROPS, properties); } static void ide_autotools_autogen_stage_init (IdeAutotoolsAutogenStage *self) { }
GNOME/gnome-builder
src/plugins/autotools/ide-autotools-autogen-stage.c
C
gpl-3.0
5,865
package com.skalvasociety.skalva.tools; import java.io.File; import javax.activation.MimetypesFileTypeMap; import org.apache.log4j.Logger; import java.util.Date; import java.util.LinkedList; import java.util.List; public class Acces { private static Logger logger = Logger.getLogger(Acces.class); /** * Lit les dossiers d'un dossier (ne lit pas dans les sous-dossiers) * @param path * @return Liste des noms de dossier */ public List<String> listDossier(String path){ List<String> listDossier = new LinkedList<String>(); File file = new File(path); File[] files = file.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { listDossier.add(files[i].getName()); } } } return listDossier; } /** * Lit les fichiers d'un dossier (ne lit pas dans les sous-dossiers) * @param path * @return Liste des noms de fichiers */ public List<FileMetaData> listFichierVideo(String path){ List<FileMetaData> listFichier = new LinkedList<FileMetaData>(); File file = new File(path); File[] files = file.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (!files[i].isDirectory()) { MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); fileTypeMap.addMimeTypes("video/x-matroska mkv"); fileTypeMap.addMimeTypes("video/m4v m4v"); fileTypeMap.addMimeTypes("video/mp4 mp4"); if(fileTypeMap.getContentType(files[i].getName()).startsWith("video")){ FileMetaData fileMetaData = new FileMetaData(); fileMetaData.setNom(files[i].getName()); fileMetaData.setDateModification(new Date(files[i].lastModified())); listFichier.add(fileMetaData); }else{ logger.error("Probleme type Fichier, Nom du fichier: " +files[i].getName() + " - type fichier: " + fileTypeMap.getContentType(files[i].getName())); } } } } return listFichier; } }
skalva50/Filmotheque
src/main/java/com/skalvasociety/skalva/tools/Acces.java
Java
gpl-3.0
1,990
#include "stdafx.h" #include "Scene.h" #include "Director.h" Scene* g_Scene = nullptr; Scene::Scene() { } Scene * Scene::getInstance() { if (g_Scene == nullptr) { g_Scene = new (std::nothrow) Scene; } return g_Scene; } void Scene::visit() { Node::visit(_transform); } std::vector<Node*> Scene::getTouchEventNodes() { return _touchEventNodes; } void Scene::pushTouchEventNode(Node * node) { node->retain(); _touchEventNodes.push_back(node); } void Scene::clearTouchEventNodes() { for (auto it : _touchEventNodes) { it->release(); } _touchEventNodes.clear(); } Scene::~Scene() { }
lixu19950414/LXGameEngine
LXGameEngine/Scene.cpp
C++
gpl-3.0
602
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> Uses of Class org.apache.poi.hpsf.UnexpectedPropertySetTypeException (POI API Documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.poi.hpsf.UnexpectedPropertySetTypeException (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= 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=2 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="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf"><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-all.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?org/apache/poi/hpsf/\class-useUnexpectedPropertySetTypeException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="UnexpectedPropertySetTypeException.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>org.apache.poi.hpsf.UnexpectedPropertySetTypeException</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf">UnexpectedPropertySetTypeException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.poi.hpsf"><B>org.apache.poi.hpsf</B></A></TD> <TD><div>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.poi.hpsf"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf">UnexpectedPropertySetTypeException</A> in <A HREF="../../../../../org/apache/poi/hpsf/package-summary.html">org.apache.poi.hpsf</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../org/apache/poi/hpsf/package-summary.html">org.apache.poi.hpsf</A> that throw <A HREF="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf">UnexpectedPropertySetTypeException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hpsf/DocumentSummaryInformation.html#DocumentSummaryInformation(org.apache.poi.hpsf.PropertySet)">DocumentSummaryInformation</A></B>(<A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf">PropertySet</A>&nbsp;ps)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a <A HREF="../../../../../org/apache/poi/hpsf/DocumentSummaryInformation.html" title="class in org.apache.poi.hpsf"><CODE>DocumentSummaryInformation</CODE></A> from a given <A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf"><CODE>PropertySet</CODE></A>.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hpsf/SummaryInformation.html#SummaryInformation(org.apache.poi.hpsf.PropertySet)">SummaryInformation</A></B>(<A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf">PropertySet</A>&nbsp;ps)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a <A HREF="../../../../../org/apache/poi/hpsf/SummaryInformation.html" title="class in org.apache.poi.hpsf"><CODE>SummaryInformation</CODE></A> from a given <A HREF="../../../../../org/apache/poi/hpsf/PropertySet.html" title="class in org.apache.poi.hpsf"><CODE>PropertySet</CODE></A>.</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=2 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="../../../../../org/apache/poi/hpsf/UnexpectedPropertySetTypeException.html" title="class in org.apache.poi.hpsf"><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-all.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?org/apache/poi/hpsf/\class-useUnexpectedPropertySetTypeException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="UnexpectedPropertySetTypeException.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> <i>Copyright 2016 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
jmemmons/university-assignments
CSC 445 WebCentric Programming/Final Project/poi-3.14/docs/apidocs/org/apache/poi/hpsf/class-use/UnexpectedPropertySetTypeException.html
HTML
gpl-3.0
9,013
/*! @file EndEffectorTouch.h @brief Declaration of a class to handle pressure data for end effectors @author Jason Kulk @class EndEffectorTouch @brief A class to handle pressure data of end effectors to produce soft sensor data. In particular, this class can calculate the following: - Total force on the end effector - Whether the end effector is in contact with something - Whether the end effector is supporting the weight of the robot - The time of the last impact with an object - The centre of pressure The related kinematic class EndEffector calculates the end effector's position and rotation. @author Jason Kulk Copyright (c) 2009, 2010, 2011 Jason Kulk This file 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 file 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 NUbot. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ENDEFFECTOR_TOUCH_H #define ENDEFFECTOR_TOUCH_H #include "Infrastructure/NUData.h" #include <vector> class EndEffectorTouch { public: EndEffectorTouch(); ~EndEffectorTouch(); void calculate(); private: void calculate(const NUData::id_t& endeffector); void invalidate(const NUData::id_t& endeffector); void calculateForce(const NUData::id_t& endeffector); void calculateContact(const NUData::id_t& endeffector); void calculateCentreOfPressure(const NUData::id_t& endeffector); void calculateSupport(const NUData::id_t &endeffector); void getHull(const NUData::id_t& endeffector, std::vector<std::vector<float> >& hull); private: std::vector<float> m_touch_data; //!< the current touch data we are working with int m_id_offset; std::vector<float> m_min_forces; //!< the min forces on each of the end effectors std::vector<float> m_max_forces; //!< the max forces on each of the end effectors std::vector<std::vector<std::vector<float> > > m_hulls; //!< the convex hulls for each of the end effectors [[[x,y],...,[x,y]],...,] float m_Nan; //!< the value used to represent invalid data std::vector<float> m_Nan_all; //!< the std::vector to invalidate all of the touch sensor }; #endif
shannonfenn/Multi-Platform-Vision-System
Darwin/NUPlatform/NUSensors/EndEffectorTouch.h
C
gpl-3.0
2,695
// // SortedList.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2008 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Text; namespace MonoTorrent.Client { public class SortList<T> : IList<T> { private List<T> list; public SortList() { list = new List<T>(); } public SortList(IEnumerable<T> list) { this.list = new List<T>(list); } public int BinarySearch(T piece, IComparer<T> comparer) { return list.BinarySearch(piece, comparer); } public bool Exists(Predicate<T> predicate) { return list.Exists(predicate); } public List<T> FindAll(Predicate<T> predicate) { return list.FindAll(predicate); } public int IndexOf(T item) { int index = list.BinarySearch(item); return index < 0 ? -1 : index; } public void Insert(int index, T item) { Add(item); } public void RemoveAt(int index) { list.RemoveAt(index); } public T this[int index] { get { return list[index]; } set { list[index] = value; } } public void Add(T item) { int index = list.BinarySearch(item); if (index < 0) list.Insert(~index, item); else list.Insert(index, item); } public void Clear() { list.Clear(); } public bool Contains(T item) { return list.BinarySearch(item) >= 0; } public void CopyTo(T[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public int Count { get { return list.Count; } } public void ForEach(Action<T> action) { list.ForEach(action); } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { int index = list.BinarySearch(item); if (index < 0) return false; list.RemoveAt(index); return true; } public int RemoveAll(Predicate<T> predicate) { return list.RemoveAll(predicate); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
leekyeongtae/TotalManagerment
MonoTorrent/MonoTorrent.Client/PiecePicking/SortedList.cs
C#
gpl-3.0
3,962
// DirImage.h : Collection of images from directory //------------------------------------------------------------------------------ // Copyright (c) 2016 Anatoly madRat L. Berenblit //------------------------------------------------------------------------------ // 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 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/>. //------------------------------------------------------------------------------ #ifndef __DirImage_H__ #define __DirImage_H__ #include <vector> #include <string> #include "MultipageImage.h" class DirImage : public MultipageImage { public: typedef MultipageImage baseClass; public: DirImage(const char *filename); DirImage(size_t count, const char *filenames[]); virtual ~DirImage(); virtual size_t num_pages() const; virtual size_t page() const; virtual const char* name() const; virtual bool page(size_t page); virtual size_t w() const; virtual size_t h() const; virtual Fl_Image *copy(int w, int h); protected: static bool isCompatible(const char *name); bool reset(Fl_Image *source); bool load(const char *filename); bool load(size_t index); void enum_files() const; std::string filename_; Fl_Image *source_; mutable std::vector<std::string> files_; mutable size_t page_; }; #endif //#ifndef DirImage_H
madrat-/flviewer
src/DirImage.h
C
gpl-3.0
1,814
namespace Maticsoft.TaoBao.Response { using Maticsoft.TaoBao; using System; using System.Runtime.CompilerServices; using System.Xml.Serialization; public class UmpActivityGetResponse : TopResponse { [XmlElement("content")] public string Content { get; set; } } }
51zhaoshi/myyyyshop
Maticsoft.TaoBao_Source/Maticsoft.TaoBao.Response/UmpActivityGetResponse.cs
C#
gpl-3.0
309
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004 - 2009 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /** * Used to call a generic method in a dashlet */ require_once('include/entryPoint.php'); require_once('ModuleInstall/PackageManager/PackageController.php'); global $current_user; $requestedMethod = $_REQUEST['method']; $pmc = new PackageController(); if(method_exists($pmc, $requestedMethod)) { echo $pmc->$requestedMethod(); } else { echo 'no method'; } // sugar_cleanup(); ?>
mitani/dashlet-subpanels
HandleAjaxCall.php
PHP
gpl-3.0
2,484
/** @file EntityFactory.h Contiene la declaración de la clase factoría de entidades del juego. @see Logic::CEntityFactory @author David Llansó García. @author Marco Antonio Gómez Martín. @author Ruben Mulero Guerrero. @author Francisco Aisa García. @date Agosto, 2010 */ #ifndef __Logic_EntityFactory_H #define __Logic_EntityFactory_H #include "Basesubsystems/Math.h" #include <map> #include <string> #include <list> #include "EntityID.h" #include "EntityIdDispatcher.h" // Predeclaración de clases para ahorrar tiempo de compilación namespace Map { class CEntity; } namespace Logic { class CMap; class CEntity; class CBluePrint; } // Definición de la clase namespace Logic { /** Factoría de CEntity que centraliza tanto la construcción como la destrucción de entidades del juego. Es un singleton de inicialización explícita. Hace uso de la factoría de componentes para ensamblar las entidades a partir de las descripciones de las entidades (blueprints). La factoría carga la descripción de las entidades (componentes que las forman) del fichero blueprints. @ingroup logicGroup @ingroup mapGroup @author David Llansó García. @author Marco Antonio Gómez Martín. @author Ruben Mulero Guerrero. @author Francisco Aisa García. @date Agosto, 2010 */ class CEntityFactory { public: /** Inicializa la base de datos de la factoría. @return false si no se ha podido inicializar. */ static bool Init(); //________________________________________________________________________ /** Libera la base de datos. Debe llamarse al finalizar la aplicación. */ static void Release(); //________________________________________________________________________ /** Devuelve un puntero al único objeto de la clase. @return Factoría de entidades. */ static CEntityFactory *getSingletonPtr(); //________________________________________________________________________ /** Carga un nuevo listado de entidades que se pueden crear mediante componentes. El fichero que contiene la definición es muy simple. Cada línea corresponde a una entidad que viene definida por una serie de palabras separadas por espacios donde la primera palabra es el tipo de la entidad y el resto son los componentes que conforman dicha entidad. <p> Se puede cargar más de un fichero con definiciones de entidades. Si los tipo de entidad se encuentran repetidos siempre prevalece el último añadido. @param filename Fichero con la descripción de las entidades. @return true si la carga se hizo correctamente. */ bool loadBluePrints(const std::string &filename); //________________________________________________________________________ /** Carga y crea entidades genéricas que se han especificado en el archivo de arquetipos. Estas entidades se guardan en una lista de la que luego el mapa creará tantas instancias como se hayan especificado. @param filename Fichero con la descripción de las entidades. @return true si la carga se hizo correctamente. */ bool loadArchetypes(const std::string &filename); //________________________________________________________________________ /** Descarga el listado de entidades creadas */ void unloadBluePrints(); //________________________________________________________________________ /** Crea una nueva entidad de juego en un mapa determinado a partir de su descripción en base a los componentes que necesita debido a su naturaleza según lo leído en el/los archivo/s blueprint. El método se encarga de asignar un nuevo identificador único a la entidad y añadirlo en el mapa del parámetro. @param entityInfo Descripción de la entidad; puede ser leída de un fichero de mapa o montada "al vuelo". @param map Mapa donde se crea la entidad. @return Entidad creada o NULL si no se pudo crear. @note Las entidades aquí creadas pueden eliminarse al final del juego o bien utilizando deferredDeleteEntity. */ CEntity* createEntity(Map::CEntity *entityInfo, CMap *map, bool replicate = true); //________________________________________________________________________ CEntity* createEntity(Map::CEntity *entityInfo, Logic::CMap *map, const Vector3& position, const Quaternion& orientation, bool replicate = true); //________________________________________________________________________ CEntity* createCustomClientEntity(Map::CEntity *entityInfo, Map::CEntity* customClientInfo, Logic::CMap *map,const Vector3& position, const Quaternion& orientation); /** Crea una nueva entidad de juego en un mapa determinado a partir de su descripción en base a los componentes que necesita debido a su naturaleza según lo leído en el/los archivo/s blueprint y a una id que le ha sido asignada a la fuerza. El método se encarga de asignar un nuevo identificador único a la entidad y añadirlo en el mapa del parámetro. @param entityInfo Descripción de la entidad; puede ser leída de un fichero de mapa o montada "al vuelo". @param map Mapa donde se crea la entidad. @param id id que tiene que tener la entidad creada. @return Entidad creada o NULL si no se pudo crear. @note Las entidades aquí creadas pueden eliminarse al final del juego o bien utilizando deferredDeleteEntity. */ CEntity* createEntityById(Map::CEntity *entityInfo, CMap *map, TEntityID id, bool replicate = false); //________________________________________________________________________ CEntity* createEntityById(Map::CEntity *entityInfo, CMap *map, TEntityID id, const Vector3& position, const Quaternion& orientation, bool replicate = false); //________________________________________________________________________ CEntity* createEntityWithTimeOut(Map::CEntity *entityInfo, CMap *map, unsigned int msecs, bool replicate = true); //________________________________________________________________________ /** Destruye el CEntity pasado como parámetro. La destrucción es inmediata, por lo que el <em>invocante debe garantizar</em> que ese objeto no está actualmente en uso (no se está destruyendo a si mismo) o no afecta a otras entidades en acciones que estén aun por realizar en el tick() actual de la lógica (si es que se está en medio de uno). De no ser así, el resultado será indeterminado. @remarks Si no se está seguro es recomendable usar el método deferredDeleteEntity() que eliminará la entidad cuando se termine el tick() de todo el mapa. @param entidad Entidad de juego que se borrará. */ void deleteEntity(CEntity *entity, bool toClients = false); //________________________________________________________________________ /** Solicita la destrucción retrasada de la entidad que se pasa como parámetro. <p> Este método se utiliza cuando se está aún con el juego activo y el objeto no puede eliminarse en este momento bien porque se intenta autodestruir en medio de su propio tick() o porque acciones que aun estar por procesar en otras entidades puedan requerir de la presencia de esta entidad. <p> La factoría retrasa la destrucción del objeto hasta que el bucle de juego invoca a deleteDefferedObjects(). Será la propia factoría la que se preocupe en ese momento de: <ul> <li>Desactivar el objeto si pertenece a un mapa activo.</li> <li>Eliminarlo del mapa al que pertenece.</li> <li>Borrarlo definitivamente.</li> </ul> @param entity Entidad del juego que se quiere borrar. @note Si se elimina la factoría (se llama al destructor) _antes_ de la invocación a deleteDefferedObjects() esos objetos _no_ son borrados por esta factoría como elementos diferidos, sino que se confía en que el mapa que aún contiene el objeto eliminará esa entidad. */ void deferredDeleteEntity(CEntity *entity, bool toClients); //________________________________________________________________________ void deferredDeleteEntity(CEntity *entity, unsigned int msecs); //________________________________________________________________________ /** Método invocado por el bucle del juego para que la factoría elimine todos los objetos pendientes de ser borrados. */ void deleteDefferedEntities(); //________________________________________________________________________ /** Método que dado un tipo de entidad, devuelve su informacion. @param type el tipo de entidad que se está buscando @return Información de la entidad, o NULL en caso de no encontrarla */ Map::CEntity * getInfo(std::string type); //________________________________________________________________________ void dynamicCreation(bool enable) { _dynamicCreation = enable; } //________________________________________________________________________ // Es necesario hacer el init, el release ya se encarga de hacerlo el unload // blueprints. void initDispatcher(unsigned int idPlayer = 0, unsigned int nbPlayers = 0) { // Para evitar memory leaks, ya que del borrado se encarga esta clase // pero de la creacion el cliente (asi aseguramos que no se crea mas de un dispatcher). assert(_idDispatcher == NULL && "Error: Ya existe una instancia del dispatcher"); _idDispatcher = new CEntityIdDispatcher<Logic::TEntityID>(idPlayer, nbPlayers); } //________________________________________________________________________ void releaseDispatcher() { if(_idDispatcher != NULL) { delete _idDispatcher; _idDispatcher = NULL; } } //________________________________________________________________________ /** Transforma un numero en string @param data Numero a formatear. @return El string resultante de formatear el numero. */ template <typename T> std::string formatToMapString(const T& data) const { std::stringstream ss (std::stringstream::in | std::stringstream::out); ss << data; return ss.str(); } //________________________________________________________________________ /** Transforma un vector3 en string con el formato en que el mapa los lee. @param data Vector a formatear. @return El vector formateado como un string. */ std::string formatToMapString(const Vector3& data) const { std::stringstream ss (std::stringstream::in | std::stringstream::out); ss << data.x; ss << " "; ss << data.y; ss << " "; ss << data.z; return ss.str(); } //________________________________________________________________________ /** Estructura que define una entidad blueprint. */ typedef struct { /** Nombre del tipo de entidad */ std::string type; /** Lista de nombres de componentes que componen la entidad. */ std::list<std::string> components; } TBluePrint; protected: Logic::CEntity* initEntity(Logic::CEntity* entity, Map::CEntity* entityInfo, CMap *map, bool replicate, Map::CEntity* customInfoForClient = NULL); //________________________________________________________________________ Logic::CEntity* initEntity(Logic::CEntity* entity, Map::CEntity* entityInfo, Logic::CMap *map, const Vector3& position, const Quaternion& orientation, bool replicate, Map::CEntity* customInfoForClient = NULL); /** Única instancia de la clase. */ static CEntityFactory *_instance; /** Constructor de la clase, protegido, pues es un singleton. Registra al objeto como observer del cargador de mapas. */ CEntityFactory(); /** Destructor protegido, por ser singleton. */ ~CEntityFactory(); /** Segunda fase de la construcción del objeto. Sirve para hacer inicializaciones de la propia instancia en vez de inicializaciones estáticas. @return true si todo fue correctamente. */ inline bool open(); /** Segunda fase de la destrucción del objeto. Sirve para hacer liberar los recursos de la propia instancia, la liberación de los recursos estáticos se hace en Release(). */ inline void close(); /** Ensambla una nueva entidad de juego a partir de su tipo de entidad. En base al tipo de entidad se crearán y añadirán a la entidad las instancias de los componentes que necesita según lo leído en el/los archivo/s blueprint. La id de la entidad puede que sea proporcionada por el motor o por otro que le fuerce a tener una id concreta. Es un procedimiento auxiliar utilizado por createEntity. @param type Tipo de la entidad que se quiere crear. @param id id de la entidad que se desea crear. @return La entidad creada o NULL si no se pudo crear. */ CEntity *assembleEntity(const std::string &type, TEntityID id); CEntity *assembleEntity(const std::string &type); /** Tipo lista de CEntity donde guardaremos los pendientes de borrar. */ typedef std::set<Logic::CEntity*> TEntitySet; /** Lista de objetos pendientes de borrar. Implementado como un set para evitar el problema de que se reciban varias peticiones. */ TEntitySet _pendingEntities; /** Tipo tabla para almacenar entidades blueprint por nombre. */ typedef std::map<std::string,TBluePrint> TBluePrintMap; /** Tabla donde se almacenan los arquetipos de las entidades. */ std::map<std::string, Map::CEntity *> _archetypes; /** Tabla donde se almacenan las entidades blueprint por nombre. */ TBluePrintMap _bluePrints; bool _dynamicCreation; Logic::CEntityIdDispatcher<Logic::TEntityID>* _idDispatcher; }; // CEntityFactory } // namespace Logic #endif // __Logic_EntityFactory_H
franaisa/Gloom
Src/Logic/Maps/EntityFactory.h
C
gpl-3.0
13,414
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'basicstyles', 'sr-latn', { bold: 'Podebljano', italic: 'Kurziv', strike: 'Precrtano', subscript: 'Indeks', superscript: 'Stepen', underline: 'Podvučeno' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/basicstyles/lang/sr-latn.js
JavaScript
gpl-3.0
355
/** * Copyright (C) 2015-2016 Jan Hajer */ #include "boca/generic/Types.hh" #include "boca/plotting/Orientation.hh" #include "boca/generic/DEBUG_MACROS.hh" namespace boca { using namespace std::string_literals; std::string Name(Orientation orientation) { auto name = ""s; FlagSwitch(orientation, [&](Orientation orientation_1) { switch (orientation_1) { case Orientation::none : name += " None"; break; case Orientation::center : name += " Center"; break; case Orientation::left : name += " Left"; break; case Orientation::right : name += " Right"; break; case Orientation::top : name += " Top"; break; case Orientation::bottom : name += " Bottom"; break; case Orientation::outside : name += " Outside"; break; default : name += std::to_string(to_int(orientation_1)); break; } }); INFO(to_int(orientation), name); return name; } }
BoostedColliderAnalysis/BoCA
source/plotting/Orientation.cpp
C++
gpl-3.0
938
<?php $plugin_tx['foldergallery']['locator_start']="Štart"; $plugin_tx['foldergallery']['locator_separator']=" > "; $plugin_tx['foldergallery']['colorbox_current']="Obrázok {current} z {total}"; $plugin_tx['foldergallery']['colorbox_previous']="predošlý"; $plugin_tx['foldergallery']['colorbox_next']="ďalší"; $plugin_tx['foldergallery']['colorbox_close']="zatvoriť"; $plugin_tx['foldergallery']['colorbox_imgError']="Tento obrázok sa nepodarilo načítať."; $plugin_tx['foldergallery']['alt_logo']="Prázdny adresár"; $plugin_tx['foldergallery']['cf_thumb_size']="Výška náhľadov v pixeloch (px).";
cmb69/foldergallery_xh
languages/sk.php
PHP
gpl-3.0
615
PROGRAM = $(NAME) FILES = types stackp nm evaluate primitives lexer parser runtime USE_OCAMLFIND = true if $(not $(OCAMLFIND_EXISTS)) eprintln(This project requires ocamlfind, but is was not found.) eprintln(You need to install ocamlfind and run "omake --configure".) exit 1 # Libraries to be ocamlfound OCAMLPACKS[] = num BYTE_ENABLED = false NATIVE_ENABLED = true # this is to remove -warn-error that is on by default OCAMLFLAGS = ################################################## # Build the executable build: $(OCamlProgram $(PROGRAM), $(FILES)) mkdir -p ../$(DISTDIR) mv $(PROGRAM).opt ../$(DISTDIR)/$(PROGRAM).opt # mv $(PROGRAM).run ../$(DISTDIR)/$(PROGRAM).run mv $(PROGRAM) ../$(DISTDIR)/$(PROGRAM) ################################################## # Create documentation doc: build mkdir -p ../$(DOCDIR) ../$(DISTDIR) ocamldoc -html -d ../$(DOCDIR) -t "$(NAME) Documentation" -hide-warnings -sort *.ml *.mli tar -c ../$(DOCDIR) | gzip -f --best > ../$(DISTDIR)/doc-$(NAME).tar.gz ################################################## # Clean up clean: rm -f *.cm[iox] *.o rm -f parser.ml parser.mli lexer.ml lexer.mli rm -rf ../$(DOCDIR) dist-clean: clean rm -f OMakefile.omc
alexleighton/shelf
src/OMakefile
Makefile
gpl-3.0
1,214
<?php /***************************************************************************\ * SPIP, Systeme de publication pour l'internet * * * * Copyright (c) 2001-2011 * * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribue sous licence GNU/GPL. * * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) return; define('_DEFAULT_DB', 'spip'); // Se connecte et retourne le nom de la fonction a connexion persistante // A la premiere connexion de l'installation (BD pas precisee) // si on ne peut se connecter sans la preciser // on reessaye avec le login comme nom de BD // et si ca marche toujours pas, avec "spip" (constante ci-dessus) // si ca ne marche toujours pas, echec. // http://doc.spip.org/@req_pg_dist function req_pg_dist($addr, $port, $login, $pass, $db='', $prefixe='') { static $last_connect = array(); if (!charger_php_extension('pgsql')) return false; // si provient de selectdb if (empty($addr) && empty($port) && empty($login) && empty($pass)){ foreach (array('addr','port','login','pass','prefixe') as $a){ $$a = $last_connect[$a]; } } @list($host, $p) = explode(';', $addr); if ($p >0) $port = " port=$p" ; else $port = ''; $erreurs = array(); if ($db) { @$link = pg_connect("host=$host$port dbname=$db user=$login password=$pass", PGSQL_CONNECT_FORCE_NEW); } elseif (!@$link = pg_connect("host=$host$port user=$login password=$pass", PGSQL_CONNECT_FORCE_NEW)) { $erreurs[] = pg_last_error(); if (@$link = pg_connect("host=$host$port dbname=$login user=$login password=$pass", PGSQL_CONNECT_FORCE_NEW)) { $db = $login; } else { $erreurs[] = pg_last_error(); $db = _DEFAULT_DB; $link = pg_connect("host=$host$port dbname=$db user=$login password=$pass", PGSQL_CONNECT_FORCE_NEW); } } if (!$link) { $erreurs[] = pg_last_error(); foreach($erreurs as $e) spip_log('Echec pg_connect. Erreur : ' . $e,'pg.'._LOG_HS); return false; } if ($link) $last_connect = array ( 'addr' => $addr, 'port' => $port, 'login' => $login, 'pass' => $pass, 'db' => $db, 'prefixe' => $prefixe, ); spip_log("Connexion vers $host, base $db, prefixe $prefixe " . ($link ? 'operationnelle' : 'impossible'),'pg.'._LOG_DEBUG); return !$link ? false : array( 'db' => $db, 'prefixe' => $prefixe ? $prefixe : $db, 'link' => $link, ); } $GLOBALS['spip_pg_functions_1'] = array( 'alter' => 'spip_pg_alter', 'count' => 'spip_pg_count', 'countsel' => 'spip_pg_countsel', 'create' => 'spip_pg_create', 'create_base' => 'spip_pg_create_base', 'create_view' => 'spip_pg_create_view', 'date_proche' => 'spip_pg_date_proche', 'delete' => 'spip_pg_delete', 'drop_table' => 'spip_pg_drop_table', 'drop_view' => 'spip_pg_drop_view', 'errno' => 'spip_pg_errno', 'error' => 'spip_pg_error', 'explain' => 'spip_pg_explain', 'fetch' => 'spip_pg_fetch', 'seek' => 'spip_pg_seek', 'free' => 'spip_pg_free', 'hex' => 'spip_pg_hex', 'in' => 'spip_pg_in', 'insert' => 'spip_pg_insert', 'insertq' => 'spip_pg_insertq', 'insertq_multi' => 'spip_pg_insertq_multi', 'listdbs' => 'spip_pg_listdbs', 'multi' => 'spip_pg_multi', 'optimize' => 'spip_pg_optimize', 'query' => 'spip_pg_query', 'quote' => 'spip_pg_quote', 'replace' => 'spip_pg_replace', 'replace_multi' => 'spip_pg_replace_multi', 'select' => 'spip_pg_select', 'selectdb' => 'spip_pg_selectdb', 'set_connect_charset' => 'spip_pg_set_connect_charset', 'showbase' => 'spip_pg_showbase', 'showtable' => 'spip_pg_showtable', 'update' => 'spip_pg_update', 'updateq' => 'spip_pg_updateq', ); // Par ou ca passe une fois les traductions faites // http://doc.spip.org/@spip_pg_trace_query function spip_pg_trace_query($query, $serveur='') { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if (isset($_GET['var_profile'])) { include_spip('public/tracer'); $t = trace_query_start(); } else $t = 0 ; $connexion['last'] = $query; $r = spip_pg_query_simple($link, $query); if ($e = spip_pg_errno($serveur)) // Log de l'erreur eventuelle $e .= spip_pg_error($query, $serveur); // et du fautif return $t ? trace_query_end($query, $t, $r, $e, $serveur) : $r; } // Fonction de requete generale quand on est sur que c'est SQL standard. // Elle change juste le noms des tables ($table_prefix) dans le FROM etc // http://doc.spip.org/@spip_pg_query function spip_pg_query($query, $serveur='',$requeter=true) { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if (preg_match('/\s(SET|VALUES|WHERE|DATABASE)\s/i', $query, $regs)) { $suite = strstr($query, $regs[0]); $query = substr($query, 0, -strlen($suite)); } else $suite =''; $query = preg_replace('/([,\s])spip_/', '\1'.$prefixe.'_', $query) . $suite; // renvoyer la requete inerte si demandee if (!$requeter) return $query; return spip_pg_trace_query($query, $serveur); } function spip_pg_query_simple($link, $query){ #spip_log(var_export($query,true), 'pg.'._LOG_DEBUG); return pg_query($link, $query); } /* * Retrouver les champs 'timestamp' * pour les ajouter aux 'insert' ou 'replace' * afin de simuler le fonctionnement de mysql * * stocke le resultat pour ne pas faire * de requetes showtable intempestives */ function spip_pg_ajouter_champs_timestamp($table, $couples, $desc='', $serveur=''){ static $tables = array(); if (!isset($tables[$table])){ if (!$desc){ $trouver_table = charger_fonction('trouver_table', 'base'); $desc = $trouver_table($table, $serveur); // si pas de description, on ne fait rien, ou on die() ? if (!$desc) return $couples; } // recherche des champs avec simplement 'TIMESTAMP' // cependant, il faudra peut etre etendre // avec la gestion de DEFAULT et ON UPDATE // mais ceux-ci ne sont pas utilises dans le core $tables[$table] = array(); foreach ($desc['field'] as $k=>$v){ $v = strtolower(ltrim($v)); // ne pas ajouter de timestamp now() si un default est specifie if (strpos($v, 'timestamp')===0 AND strpos($v, 'default')===false) $tables[$table][] = $k; } } // ajout des champs type 'timestamp' absents foreach ($tables[$table] as $maj){ if (!array_key_exists($maj, $couples)) $couples[$maj] = "NOW()"; } return $couples; } // Alter en PG ne traite pas les index // http://doc.spip.org/@spip_pg_alter function spip_pg_alter($query, $serveur='',$requeter=true) { // il faudrait une regexp pour eviter de spliter ADD PRIMARY KEY (colA, colB) // tout en cassant en deux alter distincts "ADD PRIMARY KEY (colA, colB), ADD INDEX (chose)"... // ou revoir l'api de sql_alter en creant un // sql_alter_table($table,array($actions)); if (!preg_match("/\s*((\s*IGNORE)?\s*TABLE\s*([^\s]*))\s*(.*)?/is", $query, $regs)){ spip_log("$query mal comprise", 'pg.'._LOG_ERREUR); return false; } $debut = $regs[1]; $table = $regs[3]; $suite = $regs[4]; $todo = explode(',', $suite); // on remet les morceaux dechires ensembles... que c'est laid ! $todo2 = array(); $i=0; $ouverte = false; while ($do = array_shift($todo)) { $todo2[$i] = isset($todo2[$i]) ? $todo2[$i] . "," . $do : $do; $o=(false!==strpos($do,"(")); $f=(false!==strpos($do,")")); if ($o AND !$f) $ouverte=true; elseif ($f) $ouverte=false; if (!$ouverte) $i++; } $todo=$todo2; $query = $debut.' '.array_shift($todo); if (!preg_match('/^\s*(IGNORE\s*)?TABLE\s+(\w+)\s+(ADD|DROP|CHANGE|MODIFY|RENAME)\s*(.*)$/is', $query, $r)) { spip_log("$query incompris", 'pg.'._LOG_ERREUR); } else { if ($r[1]) spip_log("j'ignore IGNORE dans $query", 'pg.'._LOG_AVERTISSEMENT); $f = 'spip_pg_alter_' . strtolower($r[3]); if (function_exists($f)) $f($r[2], $r[4], $serveur, $requeter); else spip_log("$query non prevu", 'pg.'._LOG_ERREUR); } // Alter a plusieurs args. Faudrait optimiser. if ($todo) spip_pg_alter("TABLE $table " . join(',',$todo)); } // http://doc.spip.org/@spip_pg_alter_change function spip_pg_alter_change($table, $arg, $serveur='',$requeter=true) { if (!preg_match('/^`?(\w+)`?\s+`?(\w+)`?\s+(.*?)\s*(DEFAULT .*?)?(NOT\s+NULL)?\s*(DEFAULT .*?)?$/i',$arg, $r)) { spip_log("alter change: $arg incompris", 'pg.'._LOG_ERREUR); } else { list(,$old, $new, $type, $default, $null, $def2) = $r; $actions = array("ALTER $old TYPE " . mysql2pg_type($type)); if ($null) $actions[]= "ALTER $old SET NOT NULL"; else $actions[]= "ALTER $old DROP NOT NULL"; if ($d = ($default ? $default : $def2)) $actions[]= "ALTER $old SET $d"; else $actions[]= "ALTER $old DROP DEFAULT"; spip_pg_query("ALTER TABLE $table " . join(', ', $actions)); if ($old != $new) spip_pg_query("ALTER TABLE $table RENAME $old TO $new", $serveur); } } // http://doc.spip.org/@spip_pg_alter_add function spip_pg_alter_add($table, $arg, $serveur='',$requeter=true) { if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*(.*)$/', $arg, $r)) { spip_log("alter add $arg incompris", 'pg.'._LOG_ERREUR); return NULL; } if (!$r[1] OR $r[1]=='COLUMN') { preg_match('/`?(\w+)`?(.*)/',$r[2], $m); if (preg_match('/^(.*)(BEFORE|AFTER|FIRST)(.*)$/is', $m[2], $n)) { $m[2]=$n[1]; } return spip_pg_query("ALTER TABLE $table ADD " . $m[1] . ' ' . mysql2pg_type($m[2]), $serveur, $requeter); } elseif ($r[1][0] == 'P') { // la primary peut etre sur plusieurs champs $r[2] = trim(str_replace('`','',$r[2])); $m = ($r[2][0]=='(') ? substr($r[2],1,-1) : $r[2]; return spip_pg_query("ALTER TABLE $table ADD CONSTRAINT $table" .'_pkey PRIMARY KEY (' . $m . ')', $serveur, $requeter); } else { preg_match('/([^\s,]*)\s*(.*)?/',$r[2], $m); // peut etre "(colonne)" ou "nom_index (colonnes)" // bug potentiel si qqn met "(colonne, colonne)" // // nom_index (colonnes) if ($m[2]) { $colonnes = substr($m[2],1,-1); $nom_index = $m[1]; } else { // (colonne) if ($m[1][0] == "(") { $colonnes = substr($m[1],1,-1); if (false!==strpos(",",$colonnes)) { spip_log(_LOG_GRAVITE_ERREUR,"PG : Erreur, impossible de creer un index sur plusieurs colonnes" ." sans qu'il ait de nom ($table, ($colonnes))", 'pg'); } else { $nom_index = $colonnes; } } // nom_index else { $nom_index = $colonnes = $m[1]; } } return spip_pg_create_index($nom_index, $table, $colonnes, $serveur, $requeter); } } // http://doc.spip.org/@spip_pg_alter_drop function spip_pg_alter_drop($table, $arg, $serveur='',$requeter=true) { if (!preg_match('/^(COLUMN|INDEX|KEY|PRIMARY\s+KEY|)\s*`?(\w*)`?/', $arg, $r)) spip_log("alter drop: $arg incompris", 'pg.'._LOG_ERREUR); else { if (!$r[1] OR $r[1]=='COLUMN') return spip_pg_query("ALTER TABLE $table DROP " . $r[2], $serveur); elseif ($r[1][0] == 'P') return spip_pg_query("ALTER TABLE $table DROP CONSTRAINT $table" . '_pkey', $serveur); else { return spip_pg_query("DROP INDEX " . $table . '_' . $r[2], $serveur); } } } function spip_pg_alter_modify($table, $arg, $serveur='',$requeter=true) { if (!preg_match('/^`?(\w+)`?\s+(.*)$/',$arg, $r)) { spip_log("alter modify: $arg incompris", 'pg.'._LOG_ERREUR); } else { return spip_pg_alter_change($table, $r[1].' '.$arg, $serveur='',$requeter=true); } } // attention (en pg) : // - alter table A rename to X = changer le nom de la table // - alter table A rename X to Y = changer le nom de la colonne X en Y // pour l'instant, traiter simplement RENAME TO X function spip_pg_alter_rename($table, $arg, $serveur='',$requeter=true) { $rename=""; // si TO, mais pas au debut if (!stripos($arg,'TO ')){ $rename=$arg; } elseif (preg_match('/^(TO)\s*`?(\w*)`?/', $arg, $r)) { $rename=$r[2]; } else { spip_log("alter rename: $arg incompris", 'pg.'._LOG_ERREUR); } return $rename?spip_pg_query("ALTER TABLE $table RENAME TO $rename"):false; } /** * Fonction de creation d'un INDEX * * @param string $nom : nom de l'index * @param string $table : table sql de l'index * @param string/array $champs : liste de champs sur lesquels s'applique l'index * @param string $serveur : nom de la connexion sql utilisee * @param bool $requeter : true pour executer la requete ou false pour retourner le texte de la requete * * @return bool ou requete */ function spip_pg_create_index($nom, $table, $champs, $serveur='', $requeter=true) { if (!($nom OR $table OR $champs)) { spip_log("Champ manquant pour creer un index pg ($nom, $table, (".@join(',',$champs)."))",'pg.'._LOG_ERREUR); return false; } $nom = str_replace("`","",$nom); $champs = str_replace("`","",$champs); // PG ne differentie pas noms des index en fonction des tables // il faut donc creer des noms uniques d'index pour une base pg $nom = $table.'_'.$nom; // enlever d'eventuelles parentheses deja presentes sur champs if (!is_array($champs)){ if ($champs[0]=="(") $champs = substr($champs,1,-1); $champs = array($champs); } $query = "CREATE INDEX $nom ON $table (" . join(',',$champs) . ")"; if (!$requeter) return $query; $res = spip_pg_query($query, $serveur, $requeter); return $res; } // http://doc.spip.org/@spip_pg_explain function spip_pg_explain($query, $serveur='',$requeter=true){ if (strpos(ltrim($query), 'SELECT') !== 0) return array(); $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; if (preg_match('/\s(SET|VALUES|WHERE)\s/i', $query, $regs)) { $suite = strstr($query, $regs[0]); $query = substr($query, 0, -strlen($suite)); } else $suite =''; $query = 'EXPLAIN ' . preg_replace('/([,\s])spip_/', '\1'.$prefixe.'_', $query) . $suite; if (!$requeter) return $query; $r = spip_pg_query_simple($link,$query); return spip_pg_fetch($r, NULL, $serveur); } // http://doc.spip.org/@spip_pg_selectdb function spip_pg_selectdb($db, $serveur='',$requeter=true) { // se connecter a la base indiquee // avec les identifiants connus $index = $serveur ? strtolower($serveur) : 0; if ($link = spip_connect_db('', '', '', '', $db, 'pg', '', '')){ if (($db==$link['db']) && $GLOBALS['connexions'][$index] = $link) return $db; } else return false; } // Qu'une seule base pour le moment // http://doc.spip.org/@spip_pg_listdbs function spip_pg_listdbs($serveur) { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $link = $connexion['link']; return spip_pg_query_simple($link, "select * From pg_database"); } // http://doc.spip.org/@spip_pg_select function spip_pg_select($select, $from, $where='', $groupby=array(), $orderby='', $limit='', $having='', $serveur='',$requeter=true){ $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; $limit = preg_match("/^\s*(([0-9]+),)?\s*([0-9]+)\s*$/", $limit,$limatch); if ($limit) { $offset = $limatch[2]; $count = $limatch[3]; } $select = spip_pg_frommysql($select); // si pas de tri explicitement demande, le GROUP BY ne // contient que la clef primaire. // lui ajouter alors le champ de tri par defaut if (preg_match("/FIELD\(([a-z]+\.[a-z]+),/i", $orderby[0], $groupbyplus)) { $groupby[] = $groupbyplus[1]; } $orderby = spip_pg_orderby($orderby, $select); if ($having) { if (is_array($having)) $having = join("\n\tAND ", array_map('calculer_pg_where', $having)); } $from = spip_pg_from($from, $prefixe); $query = "SELECT ". $select . (!$from ? '' : "\nFROM $from") . (!$where ? '' : ("\nWHERE " . (!is_array($where) ? calculer_pg_where($where) : (join("\n\tAND ", array_map('calculer_pg_where', $where)))))) . spip_pg_groupby($groupby, $from, $select) . (!$having ? '' : "\nHAVING $having") . ($orderby ? ("\nORDER BY $orderby") :'') . (!$limit ? '' : (" LIMIT $count" . (!$offset ? '' : " OFFSET $offset"))); // renvoyer la requete inerte si demandee if ($requeter === false) return $query; $r = spip_pg_trace_query($query, $serveur); return $r ? $r : $query;; } // Le traitement des prefixes de table dans un Select se limite au FROM // car le reste de la requete utilise les alias (AS) systematiquement // http://doc.spip.org/@spip_pg_from function spip_pg_from($from, $prefixe) { if (is_array($from)) $from = spip_pg_select_as($from); return !$prefixe ? $from : preg_replace('/(\b)spip_/','\1'.$prefixe.'_', $from); } // http://doc.spip.org/@spip_pg_orderby function spip_pg_orderby($order, $select) { $res = array(); $arg = (is_array($order) ? $order : preg_split('/\s*,\s*/',$order)); foreach($arg as $v) { if (preg_match('/(case\s+.*?else\s+0\s+end)\s*AS\s+' . $v .'/', $select, $m)) { $res[] = $m[1]; } else $res[]=$v; } return spip_pg_frommysql(join(',',$res)); } // Conversion a l'arrach' des jointures MySQL en jointures PG // A refaire pour tirer parti des possibilites de PG et de MySQL5 // et pour enlever les repetitions (sans incidence de perf, mais ca fait sale) // http://doc.spip.org/@spip_pg_groupby function spip_pg_groupby($groupby, $from, $select) { $join = strpos($from, ","); // ismplifier avant de decouper if (is_string($select)) // fct SQL sur colonne et constante apostrophee ==> la colonne $select = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/','\\1', $select); if ($join OR $groupby) $join = is_array($select) ? $select : explode(", ", $select); if ($join) { // enlever les 0 as points, '', ... foreach($join as $k=>$v){ $v = str_replace('DISTINCT ','',$v); // fct SQL sur colonne et constante apostrophee ==> la colonne $v = preg_replace('/\w+\(\s*([^(),\']*),\s*\'[^\']*\'[^)]*\)/','\\1', $v); $v = preg_replace('/CAST\(\s*([^(),\' ]*\s+)as\s*\w+\)/','\\1', $v); // resultat d'agregat ne sont pas a mettre dans le groupby $v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)(\s*AS\s+\w+)\s*,?/i','', $v); // idem sans AS (fetch numerique) $v = preg_replace('/(SUM|COUNT|MAX|MIN|UPPER)\([^)]+\)\s*,?/i','', $v); // des AS simples : on garde le cote droit du AS $v = preg_replace('/^.*\sAS\s+(\w+)\s*$/i','\\1', $v); // ne reste plus que les vrais colonnes, ou des constantes a virer if (preg_match(',^[\'"],',$v) OR is_numeric($v)) unset($join[$k]); else $join[$k] = trim($v); } $join = array_diff($join,array('')); $join = implode(',',$join); } if (is_array($groupby)) $groupby = join(',',$groupby); if ($join) $groupby = $groupby ? "$groupby, $join" : $join; if (!$groupby) return ''; $groupby = spip_pg_frommysql($groupby); $groupby = preg_replace('/\s+AS\s+\w+\s*/i','', $groupby); return "\nGROUP BY $groupby"; } // Conversion des operateurs MySQL en PG // IMPORTANT: "0+X" est vu comme conversion numerique du debut de X // Les expressions de date ne sont pas gerees au-dela de 3 () // Le 'as' du 'CAST' est en minuscule pour echapper au dernier preg_replace // de spip_pg_groupby. // A ameliorer. // http://doc.spip.org/@spip_pg_frommysql function spip_pg_frommysql($arg) { if (is_array($arg)) $arg = join(", ", $arg); $res = spip_pg_fromfield($arg); $res = preg_replace('/\brand[(][)]/i','random()', $res); $res = preg_replace('/\b0\.0[+]([a-zA-Z0-9_.]+)\s*/', 'CAST(substring(\1, \'^ *[0-9.]+\') as float)', $res); $res = preg_replace('/\b0[+]([a-zA-Z0-9_.]+)\s*/', 'CAST(substring(\1, \'^ *[0-9]+\') as int)', $res); $res = preg_replace('/\bconv[(]([^,]*)[^)]*[)]/i', 'CAST(substring(\1, \'^ *[0-9]+\') as int)', $res); $res = preg_replace('/UNIX_TIMESTAMP\s*[(]\s*[)]/', ' EXTRACT(epoch FROM NOW())', $res); // la fonction md5(integer) n'est pas connu en pg // il faut donc forcer les types en text (cas de md5(id_article)) $res = preg_replace('/md5\s*[(]([^)]*)[)]/i', 'MD5(CAST(\1 AS text))', $res); $res = preg_replace('/UNIX_TIMESTAMP\s*[(]([^)]*)[)]/', ' EXTRACT(epoch FROM \1)', $res); $res = preg_replace('/\bDAYOFMONTH\s*[(]([^()]*([(][^()]*[)][^()]*)*[^)]*)[)]/', ' EXTRACT(day FROM \1)', $res); $res = preg_replace('/\bMONTH\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/', ' EXTRACT(month FROM \1)', $res); $res = preg_replace('/\bYEAR\s*[(]([^()]*([(][^)]*[)][^()]*)*[^)]*)[)]/', ' EXTRACT(year FROM \1)', $res); $res = preg_replace('/TO_DAYS\s*[(]([^()]*([(][^)]*[)][()]*)*)[)]/', ' EXTRACT(day FROM \1 - \'0001-01-01\')', $res); $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)\"([^\"]*)\"/", '\1\'\2\'', $res); $res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m%d\'[)]/', 'to_char(\1, \'YYYYMMDD\')', $res); $res = preg_replace('/DATE_FORMAT\s*[(]([^,]*),\s*\'%Y%m\'[)]/', 'to_char(\1, \'YYYYMM\')', $res); $res = preg_replace('/DATE_SUB\s*[(]([^,]*),/', '(\1 -', $res); $res = preg_replace('/DATE_ADD\s*[(]([^,]*),/', '(\1 +', $res); $res = preg_replace('/INTERVAL\s+(\d+\s+\w+)/', 'INTERVAL \'\1\'', $res); $res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\s+\d+:\d+(:\d+)\')/', '\1 timestamp \2', $res); $res = preg_replace('/(\'\d+-\d+-\d+\s+\d+:\d+:\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res); $res = preg_replace('/([+<>-]=?)\s*(\'\d+-\d+-\d+\')/', '\1 timestamp \2', $res); $res = preg_replace('/(\'\d+-\d+-\d+\')\s*([+<>-]=?)/', 'timestamp \1 \2', $res); $res = preg_replace('/(timestamp .\d+)-00-/','\1-01-', $res); $res = preg_replace('/(timestamp .\d+-\d+)-00/','\1-01',$res); # correct en theorie mais produit des debordements arithmetiques # $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)(timestamp *'[^']*' *[+-] *timestamp *'[^']*') *[)]/", '\2', $res); $res = preg_replace("/(EXTRACT[(][^ ]* FROM *)('[^']*')/", '\1 timestamp \2', $res); $res = preg_replace("/\sLIKE\s+/", ' ILIKE ', $res); return str_replace('REGEXP', '~', $res); } // http://doc.spip.org/@spip_pg_fromfield function spip_pg_fromfield($arg) { while(preg_match('/^(.*?)FIELD\s*\(([^,]*)((,[^,)]*)*)\)/', $arg, $m)) { preg_match_all('/,([^,]*)/', $m[3], $r, PREG_PATTERN_ORDER); $res = ''; $n=0; $index = $m[2]; foreach($r[1] as $v) { $n++; $res .= "\nwhen $index=$v then $n"; } $arg = $m[1] . "case $res else 0 end " . substr($arg,strlen($m[0])); } return $arg; } // http://doc.spip.org/@calculer_pg_where function calculer_pg_where($v) { if (!is_array($v)) return spip_pg_frommysql($v); $op = str_replace('REGEXP', '~', array_shift($v)); if (!($n=count($v))) return $op; else { $arg = calculer_pg_where(array_shift($v)); if ($n==1) { return "$op($arg)"; } else { $arg2 = calculer_pg_where(array_shift($v)); if ($n==2) { return "($arg $op $arg2)"; } else return "($arg $op ($arg2) : $v[0])"; } } } // http://doc.spip.org/@calculer_pg_expression function calculer_pg_expression($expression, $v, $join = 'AND'){ if (empty($v)) return ''; $exp = "\n$expression "; if (!is_array($v)) $v = array($v); if (strtoupper($join) === 'AND') return $exp . join("\n\t$join ", array_map('calculer_pg_where', $v)); else return $exp . join($join, $v); } // http://doc.spip.org/@spip_pg_select_as function spip_pg_select_as($args) { $argsas = ""; foreach($args as $k => $v) { if (substr($k,-1)=='@') { // c'est une jointure qui se refere au from precedent // pas de virgule $argsas .= ' ' . $v ; } else { $as = ''; // spip_log("$k : $v", _LOG_DEBUG); if (!is_numeric($k)) { if (preg_match('/\.(.*)$/', $k, $r)) $v = $k; elseif ($v != $k) { $p = strpos($v, " "); if ($p) $v = substr($v,0,$p) . " AS $k" . substr($v,$p); else $as = " AS $k"; } } // spip_log("subs $k : $v avec $as", _LOG_DEBUG); // if (strpos($v, 'JOIN') === false) $argsas .= ', '; $argsas .= ', '. $v . $as; } } return substr($argsas,2); } // http://doc.spip.org/@spip_pg_fetch function spip_pg_fetch($res, $t='', $serveur='',$requeter=true) { if ($res) $res = pg_fetch_array($res, NULL, PGSQL_ASSOC); return $res; } function spip_pg_seek($r, $row_number, $serveur='',$requeter=true) { if ($r) return pg_result_seek($r,$row_number); } // http://doc.spip.org/@spip_pg_countsel function spip_pg_countsel($from = array(), $where = array(), $groupby=array(), $having = array(), $serveur='',$requeter=true) { $c = !$groupby ? '*' : ('DISTINCT ' . (is_string($groupby) ? $groupby : join(',', $groupby))); $r = spip_pg_select("COUNT($c)", $from, $where,'', '', '', $having, $serveur, $requeter); if (!$requeter) return $r; if (!is_resource($r)) return 0; list($c) = pg_fetch_array($r, NULL, PGSQL_NUM); return $c; } // http://doc.spip.org/@spip_pg_count function spip_pg_count($res, $serveur='',$requeter=true) { return !$res ? 0 : pg_numrows($res); } // http://doc.spip.org/@spip_pg_free function spip_pg_free($res, $serveur='',$requeter=true) { // rien a faire en postgres } // http://doc.spip.org/@spip_pg_delete function spip_pg_delete($table, $where='', $serveur='',$requeter=true) { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if ($prefixe) $table = preg_replace('/^spip/', $prefixe, $table); $query = calculer_pg_expression('DELETE FROM', $table, ',') . calculer_pg_expression('WHERE', $where, 'AND'); // renvoyer la requete inerte si demandee if (!$requeter) return $query; $res = spip_pg_trace_query($query, $serveur); if ($res) return pg_affected_rows($res); else return false; } // http://doc.spip.org/@spip_pg_insert function spip_pg_insert($table, $champs, $valeurs, $desc=array(), $serveur='',$requeter=true) { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if (!$desc) $desc = description_table($table); $seq = spip_pg_sequence($table,true); // si pas de cle primaire dans l'insertion, renvoyer curval if (!preg_match(",\b$seq\b,",$champs)){ $seq = spip_pg_sequence($table); if ($prefixe) $seq = preg_replace('/^spip/', $prefixe, $seq); $seq = "currval('$seq')"; } if ($prefixe) { $table = preg_replace('/^spip/', $prefixe, $table); } $ret = !$seq ? '' : (" RETURNING $seq"); $ins = (strlen($champs)<3) ? " DEFAULT VALUES" : "$champs VALUES $valeurs"; $q ="INSERT INTO $table $ins $ret"; if (!$requeter) return $q; $connexion['last'] = $q; $r = spip_pg_query_simple($link, $q); # spip_log($q,'pg.'._LOG_DEBUG); if ($r) { if (!$ret) return 0; if ($r2 = pg_fetch_array($r, NULL, PGSQL_NUM)) return $r2[0]; } return false; } // http://doc.spip.org/@spip_pg_insertq function spip_pg_insertq($table, $couples=array(), $desc=array(), $serveur='',$requeter=true) { if (!$desc) $desc = description_table($table); if (!$desc) die("$table insertion sans description"); $fields = $desc['field']; foreach ($couples as $champ => $val) { $couples[$champ]= spip_pg_cite($val, $fields[$champ]); } // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur); return spip_pg_insert($table, "(".join(',',array_keys($couples)).")", "(".join(',', $couples).")", $desc, $serveur, $requeter); } // http://doc.spip.org/@spip_pg_insertq_multi function spip_pg_insertq_multi($table, $tab_couples=array(), $desc=array(), $serveur='',$requeter=true) { if (!$desc) $desc = description_table($table); if (!$desc) die("$table insertion sans description"); $fields = isset($desc['field'])?$desc['field']:array(); // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci // une premiere fois pour ajouter maj dans les cles $les_cles = spip_pg_ajouter_champs_timestamp($table, $tab_couples[0], $desc, $serveur); $cles = "(" . join(',',array_keys($les_cles)). ')'; $valeurs = array(); foreach ($tab_couples as $couples) { foreach ($couples as $champ => $val){ $couples[$champ]= spip_pg_cite($val, $fields[$champ]); } // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur); $valeurs[] = '(' .join(',', $couples) . ')'; } $valeurs = implode(', ',$valeurs); return spip_pg_insert($table, $cles, $valeurs, $desc, $serveur, $requeter); } // http://doc.spip.org/@spip_pg_update function spip_pg_update($table, $couples, $where='', $desc='', $serveur='',$requeter=true) { if (!$couples) return; $connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if ($prefixe) $table = preg_replace('/^spip/', $prefixe, $table); // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci $couples = spip_pg_ajouter_champs_timestamp($table, $couples, $desc, $serveur); $set = array(); foreach ($couples as $champ => $val) { $set[] = $champ . '=' . $val; } $query = calculer_pg_expression('UPDATE', $table, ',') . calculer_pg_expression('SET', $set, ',') . calculer_pg_expression('WHERE', $where, 'AND'); // renvoyer la requete inerte si demandee if (!$requeter) return $query; return spip_pg_trace_query($query, $serveur); } // idem, mais les valeurs sont des constantes a mettre entre apostrophes // sauf les expressions de date lorsqu'il s'agit de fonctions SQL (NOW etc) // http://doc.spip.org/@spip_pg_updateq function spip_pg_updateq($table, $couples, $where='', $desc=array(), $serveur='',$requeter=true) { if (!$couples) return; if (!$desc) $desc = description_table($table); $fields = $desc['field']; foreach ($couples as $k => $val) { $couples[$k] = spip_pg_cite($val, $fields[$k]); } return spip_pg_update($table, $couples, $where, $desc, $serveur, $requeter); } // http://doc.spip.org/@spip_pg_replace function spip_pg_replace($table, $values, $desc, $serveur='',$requeter=true) { if (!$values) {spip_log("replace vide $table",'pg.'._LOG_AVERTISSEMENT); return 0;} $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if (!$desc) $desc = description_table($table); if (!$desc) die("$table insertion sans description"); $prim = $desc['key']['PRIMARY KEY']; $ids = preg_split('/,\s*/', $prim); $noprims = $prims = array(); foreach($values as $k=>$v) { $values[$k] = $v = spip_pg_cite($v, $desc['field'][$k]); if (!in_array($k, $ids)) $noprims[$k]= "$k=$v"; else $prims[$k]= "$k=$v"; } // recherche de champs 'timestamp' pour mise a jour auto de ceux-ci $values = spip_pg_ajouter_champs_timestamp($table, $values, $desc, $serveur); $where = join(' AND ', $prims); if (!$where) { return spip_pg_insert($table, "(".join(',',array_keys($values)).")", "(".join(',', $values).")", $desc, $serveur); } $couples = join(',', $noprims); $seq = spip_pg_sequence($table); if ($prefixe) { $table = preg_replace('/^spip/', $prefixe, $table); $seq = preg_replace('/^spip/', $prefixe, $seq); } $connexion['last'] = $q = "UPDATE $table SET $couples WHERE $where"; if ($couples) { $couples = spip_pg_query_simple($link, $q); # spip_log($q,'pg.'._LOG_DEBUG); if (!$couples) return false; $couples = pg_affected_rows($couples); } if (!$couples) { $ret = !$seq ? '' : (" RETURNING nextval('$seq') < $prim"); $connexion['last'] = $q = "INSERT INTO $table (" . join(',',array_keys($values)) . ') VALUES (' .join(',', $values) . ")$ret"; $couples = spip_pg_query_simple($link, $q); if (!$couples) { return false; } elseif ($ret) { $r = pg_fetch_array($couples, NULL, PGSQL_NUM); if ($r[0]) { $connexion['last'] = $q = "SELECT setval('$seq', $prim) from $table"; // Le code de SPIP met parfois la sequence a 0 (dans l'import) // MySQL n'en dit rien, on fait pareil pour PG $r = @pg_query($link, $q); } } } return $couples; } // http://doc.spip.org/@spip_pg_replace_multi function spip_pg_replace_multi($table, $tab_couples, $desc=array(), $serveur='',$requeter=true) { // boucler pour traiter chaque requete independemment foreach ($tab_couples as $couples){ $retour = spip_pg_replace($table, $couples, $desc, $serveur,$requeter); } // renvoie le dernier id return $retour; } // Donne la sequence eventuelle associee a une table // Pas extensible pour le moment, // http://doc.spip.org/@spip_pg_sequence function spip_pg_sequence($table,$raw=false) { global $tables_principales; include_spip('base/serial'); if (!isset($tables_principales[$table])) return false; $desc = $tables_principales[$table]; $prim = @$desc['key']['PRIMARY KEY']; if (!preg_match('/^\w+$/', $prim) OR strpos($desc['field'][$prim], 'int') === false) return ''; else { return $raw?$prim:$table . '_' . $prim . "_seq";} } // Explicite les conversions de Mysql d'une valeur $v de type $t // Dans le cas d'un champ date, pas d'apostrophe, c'est une syntaxe ad hoc // http://doc.spip.org/@spip_pg_cite function spip_pg_cite($v, $t){ if(is_null($v)) return 'NULL'; // null php se traduit en NULL SQL if (sql_test_date($t)) { if (strpos("0123456789", $v[0]) === false) return spip_pg_frommysql($v); else { if (strncmp($v,'0000',4)==0) $v = "0001" . substr($v,4); if (strpos($v, "-00-00") === 4) $v = substr($v,0,4)."-01-01".substr($v,10); return "timestamp '$v'"; } } elseif (!sql_test_int($t)) return ("'" . addslashes($v) . "'"); elseif (is_numeric($v) OR (strpos($v, 'CAST(') === 0)) return $v; elseif ($v[0]== '0' AND $v[1]!=='x' AND ctype_xdigit(substr($v,1))) return substr($v,1); else { spip_log("Warning: '$v' n'est pas de type $t", 'pg.'._LOG_AVERTISSEMENT); return intval($v); } } // http://doc.spip.org/@spip_pg_hex function spip_pg_hex($v) { return "CAST(x'" . $v . "' as bigint)"; } function spip_pg_quote($v, $type='') { return ($type === 'int' AND !$v) ? '0' : _q($v); } function spip_pg_date_proche($champ, $interval, $unite) { return '(' . $champ . (($interval <= 0) ? '>' : '<') . (($interval <= 0) ? 'DATE_SUB' : 'DATE_ADD') . '(' . sql_quote(date('Y-m-d H:i:s')) . ', INTERVAL ' . (($interval > 0) ? $interval : (0-$interval)) . ' ' . $unite . '))'; } // http://doc.spip.org/@spip_pg_in function spip_pg_in($val, $valeurs, $not='', $serveur) { // // IN (...) souvent limite a 255 elements, d'ou cette fonction assistante // if (strpos($valeurs, "CAST(x'") !== false) return "($val=" . join("OR $val=", explode(',',$valeurs)).')'; $n = $i = 0; $in_sql =""; while ($n = strpos($valeurs, ',', $n+1)) { if ((++$i) >= 255) { $in_sql .= "($val $not IN (" . substr($valeurs, 0, $n) . "))\n" . ($not ? "AND\t" : "OR\t"); $valeurs = substr($valeurs, $n+1); $i = $n = 0; } } $in_sql .= "($val $not IN ($valeurs))"; return "($in_sql)"; } // http://doc.spip.org/@spip_pg_error function spip_pg_error($query='', $serveur, $requeter=true) { $link = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]['link']; $s = $link ? pg_last_error($link) : pg_last_error(); if ($s) { $s = str_replace('ERROR', 'errcode: 1000 ', $s); spip_log("$s - $query", 'pg.'._LOG_ERREUR); } return $s; } // http://doc.spip.org/@spip_pg_errno function spip_pg_errno($serveur='') { // il faudrait avoir la derniere ressource retournee et utiliser // http://fr2.php.net/manual/fr/function.pg-result-error.php return 0; } // http://doc.spip.org/@spip_pg_drop_table function spip_pg_drop_table($table, $exist='', $serveur='',$requeter=true) { if ($exist) $exist =" IF EXISTS"; if (spip_pg_query("DROP TABLE$exist $table", $serveur, $requeter)) return true; else return false; } // supprime une vue // http://doc.spip.org/@spip_pg_drop_view function spip_pg_drop_view($view, $exist='', $serveur='',$requeter=true) { if ($exist) $exist =" IF EXISTS"; return spip_pg_query("DROP VIEW$exist $view", $serveur, $requeter); } // http://doc.spip.org/@spip_pg_showbase function spip_pg_showbase($match, $serveur='',$requeter=true) { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $link = $connexion['link']; $connexion['last'] = $q = "SELECT tablename FROM pg_tables WHERE tablename ILIKE "._q($match); return spip_pg_query_simple($link, $q); } // http://doc.spip.org/@spip_pg_showtable function spip_pg_showtable($nom_table, $serveur='',$requeter=true) { $connexion = &$GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $link = $connexion['link']; $connexion['last'] = $q = "SELECT column_name, column_default, data_type FROM information_schema.columns WHERE table_name ILIKE " . _q($nom_table); $res = spip_pg_query_simple($link, $q); if (!$res) return false; // etrangement, $res peut ne rien contenir, mais arriver ici... // il faut en tenir compte dans le return $fields = array(); while($field = pg_fetch_array($res, NULL, PGSQL_NUM)) { $fields[$field[0]] = $field[2] . (!$field[1] ? '' : (" DEFAULT " . $field[1])); } $connexion['last'] = $q = "SELECT indexdef FROM pg_indexes WHERE tablename ILIKE " . _q($nom_table); $res = spip_pg_query_simple($link, $q); $keys = array(); while($index = pg_fetch_array($res, NULL, PGSQL_NUM)) { if (preg_match('/CREATE\s+(UNIQUE\s+)?INDEX\s([^\s]+).*\((.*)\)$/', $index[0],$r)) { $nom = str_replace($nom_table.'_','',$r[2]); $keys[($r[1] ? "PRIMARY KEY" : ("KEY " . $nom))] = $r[3]; } } return count($fields) ? array('field' => $fields, 'key' => $keys) : false; } // Fonction de creation d'une table SQL nommee $nom // a partir de 2 tableaux PHP : // champs: champ => type // cles: type-de-cle => champ(s) // si $autoinc, c'est une auto-increment (i.e. serial) sur la Primary Key // Le nom des index est prefixe par celui de la table pour eviter les conflits // http://doc.spip.org/@spip_pg_create function spip_pg_create($nom, $champs, $cles, $autoinc=false, $temporary=false, $serveur='',$requeter=true) { $connexion = $GLOBALS['connexions'][$serveur ? strtolower($serveur) : 0]; $prefixe = $connexion['prefixe']; $link = $connexion['link']; $db = $connexion['db']; if ($prefixe) $nom = preg_replace('/^spip/', $prefixe, $nom); $query = $prim = $prim_name = $v = $s = $p=''; $keys = array(); // certains plugins declarent les tables (permet leur inclusion dans le dump) // sans les renseigner (laisse le compilo recuperer la description) if (!is_array($champs) || !is_array($cles)) return; foreach($cles as $k => $v) { if (strpos($k, "KEY ") === 0) { $n = str_replace('`','',$k); $v = str_replace('`','"',$v); $i = $nom . preg_replace("/KEY +/", '_',$n); if ($k != $n) $i = "\"$i\""; $keys[] = "CREATE INDEX $i ON $nom ($v);"; } elseif (strpos($k, "UNIQUE ") === 0) { $k = preg_replace("/^UNIQUE +/", '',$k); $prim .= "$s\n\t\tCONSTRAINT " . str_replace('`','"',$k) ." UNIQUE ($v)"; } else { $prim .= "$s\n\t\t" . str_replace('`','"',$k) ." ($v)"; } if ($k == "PRIMARY KEY") $prim_name = $v; $s = ","; } $s = ''; $character_set = ""; if (@$GLOBALS['meta']['charset_sql_base']) $character_set .= " CHARACTER SET ".$GLOBALS['meta']['charset_sql_base']; if (@$GLOBALS['meta']['charset_collation_sql_base']) $character_set .= " COLLATE ".$GLOBALS['meta']['charset_collation_sql_base']; foreach($champs as $k => $v) { $k = str_replace('`','"',$k); if (preg_match(',([a-z]*\s*(\(\s*[0-9]*\s*\))?(\s*binary)?),i',$v,$defs)){ if (preg_match(',(char|text),i',$defs[1]) AND !preg_match(',binary,i',$defs[1]) ){ $v = $defs[1] . $character_set . ' ' . substr($v,strlen($defs[1])); } } $query .= "$s\n\t\t$k " . (($autoinc && ($prim_name == $k) && preg_match(',\b(big|small|medium|tiny)?int\b,i', $v)) ? " bigserial" : mysql2pg_type($v) ); $s = ","; } $temporary = $temporary ? 'TEMPORARY':''; // En l'absence de "if not exists" en PG, on neutralise les erreurs $q = "CREATE $temporary TABLE $nom ($query" . ($prim ? ",$prim" : '') . ")". ($character_set?" DEFAULT $character_set":"") ."\n"; if (!$requeter) return $q; $connexion['last'] = $q; $r = @pg_query($link, $q); if (!$r) spip_log("Impossible de creer cette table: $q",'pg.'._LOG_ERREUR); else { foreach($keys as $index) {pg_query($link, $index);} } return $r; } function spip_pg_create_base($nom, $serveur='',$requeter=true) { return spip_pg_query("CREATE DATABASE $nom", $serveur, $requeter); } // Fonction de creation d'une vue SQL nommee $nom // http://doc.spip.org/@spip_pg_create_view function spip_pg_create_view($nom, $query_select, $serveur='',$requeter=true) { if (!$query_select) return false; // vue deja presente if (sql_showtable($nom, false, $serveur)) { if ($requeter) spip_log("Echec creation d'une vue sql ($nom) car celle-ci existe deja (serveur:$serveur)",'pg.'._LOG_ERREUR); return false; } $query = "CREATE VIEW $nom AS ". $query_select; return spip_pg_query($query, $serveur, $requeter); } // http://doc.spip.org/@spip_pg_set_connect_charset function spip_pg_set_connect_charset($charset, $serveur='',$requeter=true){ spip_log("changement de charset sql a ecrire en PG",'pg.'._LOG_ERREUR); } /** * Optimise une table SQL * * @param $table nom de la table a optimiser * @param $serveur nom de la connexion * @param $requeter effectuer la requete ? sinon retourner son code * @return bool|string true / false / requete **/ // http://doc.spip.org/@spip_sqlite_optimize function spip_pg_optimize($table, $serveur='',$requeter=true){ return spip_pg_query("VACUUM ". $table, $serveur, $requeter); } // Selectionner la sous-chaine dans $objet // correspondant a $lang. Cf balise Multi de Spip // http://doc.spip.org/@spip_pg_multi function spip_pg_multi ($objet, $lang) { $r = "regexp_replace(" . $objet . ",'<multi>.*[[]" . $lang . "[]]([^[]*).*</multi>', E'\\\\1') AS multi"; return $r; } // Palanquee d'idiosyncrasies MySQL dans les creations de table // A completer par les autres, mais essayer de reduire en amont. // http://doc.spip.org/@mysql2pg_type function mysql2pg_type($v){ $remplace = array( '/auto_increment/i' => '', // non reconnu '/bigint/i' => 'bigint', '/mediumint/i' => 'mediumint', '/smallint/i'=> 'smallint', "/tinyint/i" => 'int', '/int\s*[(]\s*\d+\s*[)]/i' => 'int', "/longtext/i" => 'text', "/mediumtext/i" => 'text', "/tinytext/i" => 'text', "/longblob/i" => 'text', "/0000-00-00/" =>'0001-01-01', "/datetime/i" => 'timestamp', "/unsigned/i" => '', "/double/i" => 'double precision', '/VARCHAR\((\d+)\)\s+BINARY/i' => 'varchar(\1)', "/ENUM *[(][^)]*[)]/i" => "varchar(255)", '/(timestamp .* )ON .*$/is' => '\\1', ); return preg_replace(array_keys($remplace),array_values($remplace),$v); } // Renvoie false si on n'a pas les fonctions pg (pour l'install) // http://doc.spip.org/@spip_versions_pg function spip_versions_pg(){ charger_php_extension('pgsql'); return function_exists('pg_connect'); } ?>
denisbz/SPIP
ecrire/req/pg.php
PHP
gpl-3.0
43,646
/*** * * WHAT * * A function which Extract pretty printer information from an Abstract Syntax Tree and inserts the info in a Token list. The following information will be extrected: - test coverage information - index information o definition of symbols, o use - if type info is avaliable (future) * * FILE * * $Source: /home/vdmtools/cvsroot/toolbox/code/specfile/extr_pp_info.cc,v $ * * VERSION * * $Revision: 1.11 $ * * DATE * * $Date: 2006/06/02 01:31:12 $ * * STATUS * * $State: Exp $ * * REFERENCES * * * * PROJECT * * IDERES/AFRODITE * * AUTHOR * * Lars + $Author: vdmtools $ * * COPYRIGHT * * (C) Kyushu University ***/ #include "extr_pp_info.h" #include "asquotes.h" #include "cgtag.h" #include "astaux.h" #include "ProjectTypes.h" #include "contextinfo.h" #include "tokenlist.h" void extr_pp_info (const Generic& g, // the AS tree to extr pp info from ContextInfo & c, // The context info table TokenList & t, // the token list to update bool cov_on // allow covering - true if in Stmt or Expression ) { if (g.IsSequence()) { // SEQUENCE CASE Sequence Sq (g); int len_Sq = Sq.Length(); for (int i = 1; i<= len_Sq; i++) { extr_pp_info (Sq[i], c, t, cov_on); } return; } else if (g.IsTuple()) { // TUPLE Tuple Tp(g); int Length = Tp.Length(); for (int i = 1; i <= Length; i++) { extr_pp_info(Tp.GetField(i), c, t, cov_on); } return; } else if (g.IsSet()) { // SET CASE Set St(g); Generic Element; for (bool bb = St.First (Element); bb; bb = St.Next (Element)) { extr_pp_info (Element, c, t, cov_on); } return; } else if (g.IsMap()) { // MAP CASE Map Mp(g); Set dom_Mp(Mp.Dom()); Generic Element; for (bool bb = dom_Mp.First (Element); bb; bb = dom_Mp.Next (Element)) { extr_pp_info (Element, c, t, cov_on); extr_pp_info (Mp[Element], c, t, cov_on); } return; } else if (g.IsRecord()) { // RECORD CASE Generic dummy = g; Record Rc(dummy); int Tag = Rc.GetTag(); /////////////////////// // TEST COVERAGE INFO // Unmark all non covered Stmt's and Expressions // Only Stmts and Expresssions may change the coverage /////////////////////// if (ASTAUX::IsASTRec(Rc)) { switch (Tag) { // special cases #ifdef VDMSL case TAG_TYPE_AS_DLModule: #endif // statements case TAG_TYPE_AS_DefStmt: case TAG_TYPE_AS_LetStmt: case TAG_TYPE_AS_LetBeSTStmt: case TAG_TYPE_AS_AssignStmt: case TAG_TYPE_AS_SeqForLoopStmt: case TAG_TYPE_AS_SetForLoopStmt: case TAG_TYPE_AS_IndexForLoopStmt: case TAG_TYPE_AS_WhileLoopStmt: case TAG_TYPE_AS_CallStmt: case TAG_TYPE_AS_ErrorStmt: case TAG_TYPE_AS_AlwaysStmt: case TAG_TYPE_AS_ExitStmt: case TAG_TYPE_AS_TrapStmt: case TAG_TYPE_AS_RecTrapStmt: case TAG_TYPE_AS_NonDetStmt: case TAG_TYPE_AS_ReturnStmt: case TAG_TYPE_AS_IfStmt: case TAG_TYPE_AS_ElseifStmt: case TAG_TYPE_AS_IdentStmt: #ifdef VDMPP case TAG_TYPE_AS_SpecificationStmt: case TAG_TYPE_AS_StartStmt: case TAG_TYPE_AS_StartListStmt: #endif // expressions case TAG_TYPE_AS_PrefixExpr: case TAG_TYPE_AS_BinaryExpr: case TAG_TYPE_AS_DefExpr: case TAG_TYPE_AS_LetExpr: case TAG_TYPE_AS_LetBeSTExpr: case TAG_TYPE_AS_IfExpr: case TAG_TYPE_AS_ElseifExpr: case TAG_TYPE_AS_AllOrExistsExpr: case TAG_TYPE_AS_ExistsUniqueExpr: case TAG_TYPE_AS_IotaExpr: case TAG_TYPE_AS_SetEnumerationExpr: case TAG_TYPE_AS_SetComprehensionExpr: case TAG_TYPE_AS_SetRangeExpr: case TAG_TYPE_AS_SeqEnumerationExpr: case TAG_TYPE_AS_SeqComprehensionExpr: case TAG_TYPE_AS_SubSequenceExpr: case TAG_TYPE_AS_SeqModifyMapOverrideExpr: case TAG_TYPE_AS_MapEnumerationExpr: case TAG_TYPE_AS_MapComprehensionExpr: case TAG_TYPE_AS_TupleConstructorExpr: case TAG_TYPE_AS_RecordModifierExpr: case TAG_TYPE_AS_ApplyExpr: case TAG_TYPE_AS_FieldSelectExpr: case TAG_TYPE_AS_TokenConstructorExpr: case TAG_TYPE_AS_LambdaExpr: case TAG_TYPE_AS_FctTypeInstExpr: case TAG_TYPE_AS_IsExpr: case TAG_TYPE_AS_BoolLit: case TAG_TYPE_AS_CharLit: case TAG_TYPE_AS_TextLit: case TAG_TYPE_AS_QuoteLit: case TAG_TYPE_AS_RealLit: case TAG_TYPE_AS_NumLit: case TAG_TYPE_AS_NilLit: case TAG_TYPE_AS_UndefinedExpr: case TAG_TYPE_AS_BracketedExpr: #ifdef VDMPP case TAG_TYPE_AS_SelfExpr: case TAG_TYPE_AS_NewExpr: case TAG_TYPE_AS_IsOfClassExpr: case TAG_TYPE_AS_IsOfBaseClassExpr: case TAG_TYPE_AS_SameBaseClassExpr: case TAG_TYPE_AS_SameClassExpr: case TAG_TYPE_AS_ActExpr: case TAG_TYPE_AS_FinExpr: case TAG_TYPE_AS_ActiveExpr: case TAG_TYPE_AS_WaitingExpr: case TAG_TYPE_AS_ReqExpr: #endif // VDMPP { TYPE_CI_ContextId ci = Rc.GetField(Rc.Length()); // get ci field if (ci == NilContextId) { break; } TYPE_CI_TokenSpan pos (c.GetPos(ci)); // get position for tokens // handle quote decl inside type decl #ifdef VDMSL if ( (TAG_TYPE_AS_QuoteLit == Tag || TAG_TYPE_AS_DLModule == Tag) && ! cov_on ) { #endif // VDMSL #ifdef VDMPP if ( (TAG_TYPE_AS_QuoteLit == Tag) && ! cov_on ) { #endif // VDMPP t.set_test_coverage(pos, 1); } else { t.set_test_coverage(pos, c.GetTestCoverageInfo(ci)); } cov_on = true; // allow covering break; } // Special cases compared to Expr // Names must reside inside an Expr or a Stmt case TAG_TYPE_AS_Name: { if (cov_on) { TYPE_CI_ContextId ci = Rc.GetInt(pos_AS_Name_cid); // get ci field if (ci != NilContextId) { if(c.HasTestCoverage(ci)) { TYPE_CI_TokenSpan pos (c.GetPos(ci)); // get position for tokens t.set_test_coverage(pos, c.GetTestCoverageInfo(ci)); } } } return; break; } case TAG_TYPE_AS_OldName: { if (cov_on) { TYPE_CI_ContextId ci = Rc.GetInt(pos_AS_OldName_cid); // get ci field if (ci != NilContextId) { if(c.HasTestCoverage(ci)) { TYPE_CI_TokenSpan pos (c.GetPos(ci)); // get position for tokens t.set_test_coverage(pos, c.GetTestCoverageInfo(ci)); } } } return; break; } case TAG_TYPE_AS_BlockStmt: { TYPE_AS_BlockStmt bs (g); SEQ<TYPE_AS_AssignDef> dcls (bs.get_dcls()); SEQ<TYPE_AS_Stmt> stmts (bs.get_stmts()); Generic dcl; for (bool bb = dcls.First(dcl); bb; bb = dcls.Next(dcl)) { extr_pp_info (dcl, c, t, cov_on); } Generic stmt; for (bool cc = stmts.First(stmt); cc; cc = stmts.Next(stmt)) { extr_pp_info (stmt, c, t, cov_on); } return; break; } case TAG_TYPE_AS_CasesStmt: { TYPE_AS_CasesStmt cs (g); TYPE_AS_Expr sel (cs.get_sel()); SEQ<TYPE_AS_CasesStmtAltn> altns (cs.get_altns()); Generic others (cs.get_Others()); extr_pp_info (sel, c, t, cov_on); Generic altn; for (bool bb = altns.First(altn); bb; bb = altns.Next(altn)) { extr_pp_info (altn, c, t, cov_on); } if (!others.IsNil()) { extr_pp_info (others, c, t, cov_on); } return; break; } case TAG_TYPE_AS_CasesStmtAltn: { TYPE_AS_CasesStmtAltn altn (g); SEQ<TYPE_AS_Pattern> m (altn.get_match ()); Generic pat; for (bool bb = m.First(pat); bb; bb = m.Next(pat)) { //extr_pp_info (pat, c, t, cov_on); TYPE_CI_ContextId ci = ASTAUX::GetCid(pat); if (ci != NilContextId) { if (c.HasTestCoverage(ci)) { if (c.GetTestCoverageInfo(ci) == 0) { TYPE_CI_TokenSpan pos (c.GetPos(ci)); // get position for tokens t.set_test_coverage(pos, 0); } } } } TYPE_AS_Stmt stmt (altn.get_body ()); //extr_pp_info (stmt, c, t, cov_on); extr_pp_info (stmt, c, t, true); return; break; } case TAG_TYPE_AS_CasesExpr: { TYPE_AS_CasesExpr cs (g); const TYPE_AS_Expr & sel (cs.GetRecord(pos_AS_CasesExpr_sel)); const SEQ<TYPE_AS_CaseAltn> & altns (cs.GetSequence(pos_AS_CasesExpr_altns)); const Generic & others (cs.GetField(pos_AS_CasesExpr_Others)); extr_pp_info (sel,c,t,cov_on); size_t len_altns = altns.Length(); for (size_t idx = 1; idx <= len_altns; idx++) { extr_pp_info (altns[idx], c, t, cov_on); } if (!others.IsNil()) { extr_pp_info (others, c, t, cov_on); } return; break; } case TAG_TYPE_AS_CaseAltn: { TYPE_AS_CaseAltn altn (g); SEQ<TYPE_AS_Pattern> m (altn.get_match ()); Generic pat; for (bool bb = m.First(pat); bb; bb = m.Next(pat)) { //extr_pp_info (pat, c, t, cov_on); TYPE_CI_ContextId ci = ASTAUX::GetCid(pat); if (ci != NilContextId) { if (c.HasTestCoverage(ci)) { if (c.GetTestCoverageInfo(ci) == 0) { TYPE_CI_TokenSpan pos (c.GetPos(ci)); // get position for tokens t.set_test_coverage(pos, 0); } } } } TYPE_AS_Expr expr (altn.get_body ()); //extr_pp_info (expr, c, t, cov_on); extr_pp_info (expr, c, t, true); return; break; } case TAG_TYPE_AS_PatternName: { // TYPE_AS_PatternName pn (g); // Generic nm (pn.get_nm()); // extr_pp_info (nm, c, t, cov_on); break; } case TAG_TYPE_AS_MatchVal: { TYPE_AS_MatchVal mv (g); TYPE_AS_Expr expr (mv.get_val()); extr_pp_info (expr, c, t, cov_on); break; } case TAG_TYPE_AS_SetEnumPattern: { TYPE_AS_SetEnumPattern sep (g); SEQ<TYPE_AS_Pattern> m (sep.get_Elems()); Generic pat; for (bool bb = m.First(pat); bb; bb = m.Next(pat)) { extr_pp_info (pat, c, t, cov_on); } break; } case TAG_TYPE_AS_SetUnionPattern: { TYPE_AS_SetUnionPattern sup (g); TYPE_AS_Pattern lp (sup.get_lp()); TYPE_AS_Pattern rp (sup.get_rp()); extr_pp_info (lp, c, t, cov_on); extr_pp_info (rp, c, t, cov_on); break; } case TAG_TYPE_AS_SeqEnumPattern: { TYPE_AS_SeqEnumPattern sep (g); SEQ<TYPE_AS_Pattern> m (sep.get_els()); Generic pat; for (bool bb = m.First(pat); bb; bb = m.Next(pat)) { extr_pp_info (pat, c, t, cov_on); } break; } case TAG_TYPE_AS_SeqConcPattern: { TYPE_AS_SeqConcPattern sup (g); TYPE_AS_Pattern lp (sup.get_lp()); TYPE_AS_Pattern rp (sup.get_rp()); extr_pp_info (lp, c, t, cov_on); extr_pp_info (rp, c, t, cov_on); break; } case TAG_TYPE_AS_TuplePattern: { TYPE_AS_TuplePattern tp (g); SEQ<TYPE_AS_Pattern> m (tp.get_fields()); Generic pat; for (bool bb = m.First(pat); bb; bb = m.Next(pat)) { extr_pp_info (pat, c, t, cov_on); } break; } case TAG_TYPE_AS_RecordPattern: { TYPE_AS_RecordPattern tp (g); SEQ<TYPE_AS_Pattern> m (tp.get_fields()); Generic pat; for (bool bb = m.First(pat); bb; bb = m.Next(pat)) { extr_pp_info (pat, c, t, cov_on); } break; } case TAG_TYPE_AS_AtomicAssignStmt: { TYPE_AS_AtomicAssignStmt aas (g); SEQ<TYPE_AS_AssignStmt> atm (aas.get_atm ()); Generic stmt_g; for( bool bb = atm.First(stmt_g); bb; bb = atm.Next(stmt_g)) { TYPE_AS_AssignStmt stmt (stmt_g); extr_pp_info (stmt, c, t, cov_on); } break; } case TAG_TYPE_AS_RecordConstructorExpr: { TYPE_AS_RecordConstructorExpr rce (g); Sequence fields (rce.get_fields ()); extr_pp_info (fields, c, t, cov_on); break; } default : { cov_on = false; // do not allwo covering } } } // end of if (ASTAUX::IsASTRec(Rc)) /////////////////////// // INDEX INFORMATION /////////////////////// switch(Tag) { #ifdef VDMSL case TAG_TYPE_AS_StateDef : { // State def TYPE_AS_StateDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_tp().get_name().get_cid())); t.set_index_element(pos, TokenInfo::state_def); break; } #endif // VDMSL case TAG_TYPE_AS_TypeDef: { // Types TYPE_AS_TypeDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::tp_def); break; } // Functions/Operations case TAG_TYPE_AS_ExplFnDef: { TYPE_AS_ExplFnDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::fct_def); break; } case TAG_TYPE_AS_ExplOpDef: { TYPE_AS_ExplOpDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::op_def); break; } case TAG_TYPE_AS_ExtExplFnDef: { TYPE_AS_ExplFnDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::fct_def); break; } case TAG_TYPE_AS_ExtExplOpDef: { TYPE_AS_ExtExplOpDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::op_def); break; } case TAG_TYPE_AS_ImplFnDef: { TYPE_AS_ImplFnDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::fct_def); break; } case TAG_TYPE_AS_ImplOpDef:{ TYPE_AS_ImplOpDef e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::op_def); break; } #ifdef VDMSL case TAG_TYPE_AS_Module: { // Module TYPE_AS_Module e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::mod_def); break; } #endif #ifdef VDMPP case TAG_TYPE_AS_Class : { // Class TYPE_AS_Class e(g); TYPE_CI_TokenSpan pos (c.GetPos(e.get_nm().get_cid())); t.set_index_element(pos, TokenInfo::class_def); break; } #endif //VDMPP } // ITERATE THROUGH THE RECORD FIELDS int Length; if (!ASTAUX::IsASTRec(Rc)) { Length = Rc.Length(); } else { // In this case the last entry is the record is an context identifier // and it should not be transformed. Length = Rc.Length() -1; } for(int i = 1; i <= Length; i++) { extr_pp_info(Rc.GetField(i), c, t, cov_on); } return; } // DEFAULT }
vdmtools/vdmtools
code/specfile/extr_pp_info.cc
C++
gpl-3.0
16,202
'use strict'; import express = require('express'); const router: express.Router = express.Router(); const service = require('../../services').GalleryService; router.get('/:limit', service.getAll); router.get('/main/:limit', service.getAll); router.get('/main/random/:limit', service.getRandomGallery); router.get('/main/popular/:limit', service.getPopularGallery); router.get('/category/:id/:itemid', service.getGalleries); router.get('/single/random', service.getRandomCollection); router.get('/single/:id/:catid/:itemid', service.getCollection); module.exports = router;
optikool/XMiddleWare
app/routes/subroutes/GalleryRoute.ts
TypeScript
gpl-3.0
576
<?php /*** COPYRIGHT NOTICE ********************************************************* * * Copyright 2009-2014 Pascal BERNARD - support@projeqtor.org * Contributors : - * * This file is part of ProjeQtOr. * * ProjeQtOr 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. * * ProjeQtOr 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 * ProjeQtOr. If not, see <http://www.gnu.org/licenses/>. * * You can get complete code of ProjeQtOr, other resource, help and information * about contributors at http://www.projeqtor.org * *** DO NOT REMOVE THIS NOTICE ************************************************/ /** =========================================================================== * Save a note : call corresponding method in SqlElement Class * The new values are fetched in $_REQUEST */ require_once "../tool/projeqtor.php"; scriptLog(' ->/tool/saveAffectation.php'); // Get the info if (! array_key_exists('affectationId',$_REQUEST)) { throwError('affectationId parameter not found in REQUEST'); } $id=($_REQUEST['affectationId']); $idTeam=null; if (array_key_exists('affectationIdTeam',$_REQUEST)) { $idTeam=$_REQUEST['affectationIdTeam']; } if (! array_key_exists('affectationProject',$_REQUEST)) { throwError('affectationProject parameter not found in REQUEST'); } $project=($_REQUEST['affectationProject']); if (! array_key_exists('affectationResource',$_REQUEST) and !$idTeam) { throwError('affectationResource parameter not found in REQUEST'); } $resource=($_REQUEST['affectationResource']); if (! array_key_exists('affectationRate',$_REQUEST)) { throwError('affectationRate parameter not found in REQUEST'); } $rate=($_REQUEST['affectationRate']); $startDate=""; if (array_key_exists('affectationStartDate',$_REQUEST)) { $startDate=($_REQUEST['affectationStartDate']);; } $endDate=""; if (array_key_exists('affectationEndDate',$_REQUEST)) { $endDate=($_REQUEST['affectationEndDate']);; } $idle=false; if (array_key_exists('affectationIdle',$_REQUEST)) { $idle=1; } Sql::beginTransaction(); if (! $idTeam) { $affectation=new Affectation($id); $affectation->idProject=$project; $affectation->idResource=$resource; $affectation->idle=$idle; $affectation->rate=$rate; $affectation->startDate=$startDate; $affectation->endDate=$endDate; $result=$affectation->save(); } else { $crit=array('idTeam'=>$idTeam); $ress=new Resource(); $list=$ress->getSqlElementsFromCriteria($crit, false); $nbAff=0; foreach ($list as $ress) { $affectation=new Affectation($id); $affectation->idProject=$project; $affectation->idResource=$ress->id; $affectation->idle=$idle; $affectation->rate=$rate; $affectation->startDate=$startDate; $affectation->endDate=$endDate; $res=$affectation->save(); if (stripos($res,'id="lastOperationStatus" value="OK"')>0 ) { $nbAff++; } } if ($nbAff) { $result='<b>' . i18n('menuAffectation') . ' ' . i18n('resultInserted') . ' : ' . $nbAff . '</b>'; $result .= '<input type="hidden" id="lastSaveId" value="" />'; $result .= '<input type="hidden" id="lastOperation" value="insert" />'; $result .= '<input type="hidden" id="lastOperationStatus" value="OK" />'; } else { $result=i18n('Affectation') . ' ' . i18n('resultInserted') . ' : 0'; $result .= '<input type="hidden" id="lastSaveId" value="" />'; $result .= '<input type="hidden" id="lastOperation" value="control" />'; $result .= '<input type="hidden" id="lastOperationStatus" value="INVALID" />'; } } // Message of correct saving if (stripos($result,'id="lastOperationStatus" value="ERROR"')>0 ) { Sql::rollbackTransaction(); echo '<span class="messageERROR" >' . $result . '</span>'; } else if (stripos($result,'id="lastOperationStatus" value="OK"')>0 ) { Sql::commitTransaction(); echo '<span class="messageOK" >' . $result . '</span>'; } else { Sql::rollbackTransaction(); echo '<span class="messageWARNING" >' . $result . '</span>'; } ?>
nikochan2k/projeqtor-ja
tool/saveAffectation.php
PHP
gpl-3.0
4,420
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2019 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::fv::steadyStateDdtScheme Description SteadyState implicit/explicit ddt which returns 0. SourceFiles steadyStateDdtScheme.C \*---------------------------------------------------------------------------*/ #ifndef steadyStateDdtScheme_H #define steadyStateDdtScheme_H #include "ddtScheme.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fv { /*---------------------------------------------------------------------------*\ Class steadyStateDdtScheme Declaration \*---------------------------------------------------------------------------*/ template<class Type> class steadyStateDdtScheme : public fv::ddtScheme<Type> { public: //- Runtime type information TypeName("steadyState"); // Constructors //- Construct from mesh steadyStateDdtScheme(const fvMesh& mesh) : ddtScheme<Type>(mesh) {} //- Construct from mesh and Istream steadyStateDdtScheme(const fvMesh& mesh, Istream& is) : ddtScheme<Type>(mesh, is) {} //- Disallow default bitwise copy construction steadyStateDdtScheme(const steadyStateDdtScheme&) = delete; // Member Functions //- Return mesh reference const fvMesh& mesh() const { return fv::ddtScheme<Type>::mesh(); } virtual tmp<GeometricField<Type, fvPatchField, volMesh>> fvcDdt ( const dimensioned<Type>& ); virtual tmp<GeometricField<Type, fvPatchField, volMesh>> fvcDdt ( const GeometricField<Type, fvPatchField, volMesh>& ); virtual tmp<GeometricField<Type, fvPatchField, volMesh>> fvcDdt ( const dimensionedScalar&, const GeometricField<Type, fvPatchField, volMesh>& ); virtual tmp<GeometricField<Type, fvPatchField, volMesh>> fvcDdt ( const volScalarField&, const GeometricField<Type, fvPatchField, volMesh>& ); virtual tmp<GeometricField<Type, fvPatchField, volMesh>> fvcDdt ( const volScalarField& alpha, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& psi ); virtual tmp<fvMatrix<Type>> fvmDdt ( const GeometricField<Type, fvPatchField, volMesh>& ); virtual tmp<fvMatrix<Type>> fvmDdt ( const dimensionedScalar&, const GeometricField<Type, fvPatchField, volMesh>& ); virtual tmp<fvMatrix<Type>> fvmDdt ( const volScalarField&, const GeometricField<Type, fvPatchField, volMesh>& ); virtual tmp<fvMatrix<Type>> fvmDdt ( const volScalarField& alpha, const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& psi ); typedef typename ddtScheme<Type>::fluxFieldType fluxFieldType; virtual tmp<fluxFieldType> fvcDdtUfCorr ( const GeometricField<Type, fvPatchField, volMesh>& U, const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf ); virtual tmp<fluxFieldType> fvcDdtPhiCorr ( const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ); virtual tmp<fluxFieldType> fvcDdtUfCorr ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf ); virtual tmp<fluxFieldType> fvcDdtPhiCorr ( const volScalarField& rho, const GeometricField<Type, fvPatchField, volMesh>& U, const fluxFieldType& phi ); virtual tmp<surfaceScalarField> meshPhi ( const GeometricField<Type, fvPatchField, volMesh>& ); // Member Operators //- Disallow default bitwise assignment void operator=(const steadyStateDdtScheme&) = delete; }; template<> tmp<surfaceScalarField> steadyStateDdtScheme<scalar>::fvcDdtUfCorr ( const GeometricField<scalar, fvPatchField, volMesh>& U, const GeometricField<scalar, fvsPatchField, surfaceMesh>& Uf ); template<> tmp<surfaceScalarField> steadyStateDdtScheme<scalar>::fvcDdtPhiCorr ( const volScalarField& U, const surfaceScalarField& phi ); template<> tmp<surfaceScalarField> steadyStateDdtScheme<scalar>::fvcDdtUfCorr ( const volScalarField& rho, const volScalarField& U, const surfaceScalarField& Uf ); template<> tmp<surfaceScalarField> steadyStateDdtScheme<scalar>::fvcDdtPhiCorr ( const volScalarField& rho, const volScalarField& U, const surfaceScalarField& phi ); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fv // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository #include "steadyStateDdtScheme.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
will-bainbridge/OpenFOAM-dev
src/finiteVolume/finiteVolume/ddtSchemes/steadyStateDdtScheme/steadyStateDdtScheme.H
C++
gpl-3.0
6,624
/* * 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 jssdv; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.stream.XMLStreamException; /** * * @author User */ public class JSSDV extends javax.swing.JFrame { /** * Creates new form mainform */ public JSSDV() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { topPane = new javax.swing.JTabbedPane(); rxPanel = new javax.swing.JPanel(); txPanel = new javax.swing.JPanel(); tximgPane = new javax.swing.JTabbedPane(); tximgPanel = new javax.swing.JPanel(); compressionSlider = new javax.swing.JSlider(); jSlider1 = new javax.swing.JSlider(); overlayPanel = new javax.swing.JPanel(); jLayeredPane1 = new javax.swing.JLayeredPane(); jPanel3 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); txList = new javax.swing.JList<>(); jTabbedPane1 = new javax.swing.JTabbedPane(); jProgressBar1 = new javax.swing.JProgressBar(); sidetalkPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList<>(); jTextField1 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox<>(); jComboBox2 = new javax.swing.JComboBox<>(); jButton2 = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); jTree1 = new javax.swing.JTree(); settingsPanel = new javax.swing.JPanel(); debugPanel = new javax.swing.JPanel(); debugtext = new javax.swing.JTextField(); fldigiPane = new javax.swing.JTabbedPane(); fldigi_settingsPanel = new javax.swing.JPanel(); host = new javax.swing.JTextField(); port = new javax.swing.JTextField(); setdefaultButton = new javax.swing.JButton(); fldigi_connectButton = new javax.swing.JToggleButton(); rigPanel = new javax.swing.JPanel(); QRG = new javax.swing.JLabel(); rxidButton = new javax.swing.JToggleButton(); txidButton = new javax.swing.JToggleButton(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767)); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("jSSDV"); setResizable(false); topPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT); javax.swing.GroupLayout rxPanelLayout = new javax.swing.GroupLayout(rxPanel); rxPanel.setLayout(rxPanelLayout); rxPanelLayout.setHorizontalGroup( rxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 827, Short.MAX_VALUE) ); rxPanelLayout.setVerticalGroup( rxPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 478, Short.MAX_VALUE) ); topPane.addTab("RX .", rxPanel); compressionSlider.setBackground(new java.awt.Color(250, 250, 250)); compressionSlider.setForeground(new java.awt.Color(40, 40, 40)); compressionSlider.setMajorTickSpacing(3); compressionSlider.setMaximum(9); compressionSlider.setMinorTickSpacing(1); compressionSlider.setPaintLabels(true); compressionSlider.setPaintTicks(true); compressionSlider.setSnapToTicks(true); compressionSlider.setBorder(javax.swing.BorderFactory.createTitledBorder("Compression")); compressionSlider.setName("Compression"); // NOI18N jSlider1.setBorder(javax.swing.BorderFactory.createTitledBorder("Img-Size")); jSlider1.setOpaque(false); javax.swing.GroupLayout tximgPanelLayout = new javax.swing.GroupLayout(tximgPanel); tximgPanel.setLayout(tximgPanelLayout); tximgPanelLayout.setHorizontalGroup( tximgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(compressionSlider, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE) .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); tximgPanelLayout.setVerticalGroup( tximgPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tximgPanelLayout.createSequentialGroup() .addContainerGap(262, Short.MAX_VALUE) .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compressionSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); tximgPane.addTab("Image", tximgPanel); javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1); jLayeredPane1.setLayout(jLayeredPane1Layout); jLayeredPane1Layout.setHorizontalGroup( jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 279, Short.MAX_VALUE) ); jLayeredPane1Layout.setVerticalGroup( jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 237, Short.MAX_VALUE) ); javax.swing.GroupLayout overlayPanelLayout = new javax.swing.GroupLayout(overlayPanel); overlayPanel.setLayout(overlayPanelLayout); overlayPanelLayout.setHorizontalGroup( overlayPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(overlayPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(103, Short.MAX_VALUE)) ); overlayPanelLayout.setVerticalGroup( overlayPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(overlayPanelLayout.createSequentialGroup() .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 168, Short.MAX_VALUE)) ); tximgPane.addTab("Overlay", overlayPanel); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 392, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 405, Short.MAX_VALUE) ); tximgPane.addTab("tab3", jPanel3); txList.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); txList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPane2.setViewportView(txList); jProgressBar1.setValue(25); jProgressBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jProgressBar1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jProgressBar1.setFocusable(false); jProgressBar1.setName(""); // NOI18N javax.swing.GroupLayout txPanelLayout = new javax.swing.GroupLayout(txPanel); txPanel.setLayout(txPanelLayout); txPanelLayout.setHorizontalGroup( txPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(txPanelLayout.createSequentialGroup() .addGroup(txPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(txPanelLayout.createSequentialGroup() .addGroup(txPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTabbedPane1) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(tximgPane, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 827, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) ); txPanelLayout.setVerticalGroup( txPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(txPanelLayout.createSequentialGroup() .addGroup(txPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tximgPane) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, txPanelLayout.createSequentialGroup() .addComponent(jTabbedPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); topPane.addTab("TX .", txPanel); jList1.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); jScrollPane1.setViewportView(jList1); jTextField1.setText("jTextField1"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jButton2.setText("jButton2"); jScrollPane3.setViewportView(jTree1); javax.swing.GroupLayout sidetalkPanelLayout = new javax.swing.GroupLayout(sidetalkPanel); sidetalkPanel.setLayout(sidetalkPanelLayout); sidetalkPanelLayout.setHorizontalGroup( sidetalkPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(sidetalkPanelLayout.createSequentialGroup() .addGroup(sidetalkPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(sidetalkPanelLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 691, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)) .addGroup(sidetalkPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 392, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); sidetalkPanelLayout.setVerticalGroup( sidetalkPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(sidetalkPanelLayout.createSequentialGroup() .addGroup(sidetalkPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE) .addComponent(jScrollPane1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(sidetalkPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2)) .addGap(0, 60, Short.MAX_VALUE)) ); topPane.addTab("Sidetalk .", sidetalkPanel); javax.swing.GroupLayout settingsPanelLayout = new javax.swing.GroupLayout(settingsPanel); settingsPanel.setLayout(settingsPanelLayout); settingsPanelLayout.setHorizontalGroup( settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 827, Short.MAX_VALUE) ); settingsPanelLayout.setVerticalGroup( settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 478, Short.MAX_VALUE) ); topPane.addTab("Settings .", new javax.swing.ImageIcon(getClass().getResource("/jssdv/if_preferences-system_118842 (2).png")), settingsPanel); // NOI18N debugtext.setText("jTextField1"); javax.swing.GroupLayout debugPanelLayout = new javax.swing.GroupLayout(debugPanel); debugPanel.setLayout(debugPanelLayout); debugPanelLayout.setHorizontalGroup( debugPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(debugPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(debugtext, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(499, Short.MAX_VALUE)) ); debugPanelLayout.setVerticalGroup( debugPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(debugPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(debugtext, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE) .addContainerGap()) ); topPane.addTab("debug", debugPanel); getContentPane().add(topPane, java.awt.BorderLayout.CENTER); host.setText("127.0.0.1"); host.setBorder(javax.swing.BorderFactory.createTitledBorder("Host:")); host.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hostActionPerformed(evt); } }); port.setText("1234"); port.setBorder(javax.swing.BorderFactory.createTitledBorder("Port:")); port.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { portActionPerformed(evt); } }); setdefaultButton.setText("default"); setdefaultButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { setdefaultButtonActionPerformed(evt); } }); fldigi_connectButton.setText("connect"); fldigi_connectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fldigi_connectButtonActionPerformed(evt); } }); javax.swing.GroupLayout fldigi_settingsPanelLayout = new javax.swing.GroupLayout(fldigi_settingsPanel); fldigi_settingsPanel.setLayout(fldigi_settingsPanelLayout); fldigi_settingsPanelLayout.setHorizontalGroup( fldigi_settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, fldigi_settingsPanelLayout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(fldigi_settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(fldigi_settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(fldigi_connectButton, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE) .addComponent(setdefaultButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); fldigi_settingsPanelLayout.setVerticalGroup( fldigi_settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(fldigi_settingsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(fldigi_settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(fldigi_connectButton)) .addGap(18, 18, 18) .addGroup(fldigi_settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(fldigi_settingsPanelLayout.createSequentialGroup() .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 13, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, fldigi_settingsPanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(setdefaultButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); fldigiPane.addTab("FLDIGI", fldigi_settingsPanel); QRG.setText("qrg"); rxidButton.setLabel("RXID"); txidButton.setLabel("TXID"); javax.swing.GroupLayout rigPanelLayout = new javax.swing.GroupLayout(rigPanel); rigPanel.setLayout(rigPanelLayout); rigPanelLayout.setHorizontalGroup( rigPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rigPanelLayout.createSequentialGroup() .addGroup(rigPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rigPanelLayout.createSequentialGroup() .addComponent(QRG, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(rxidButton)) .addGroup(rigPanelLayout.createSequentialGroup() .addGap(213, 213, 213) .addComponent(txidButton))) .addGap(0, 557, Short.MAX_VALUE)) ); rigPanelLayout.setVerticalGroup( rigPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(rigPanelLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(rigPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rxidButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(QRG, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addComponent(txidButton) .addGap(0, 43, Short.MAX_VALUE)) ); fldigiPane.addTab("RIG", rigPanel); getContentPane().add(fldigiPane, java.awt.BorderLayout.PAGE_START); fldigiPane.getAccessibleContext().setAccessibleName("RIG"); fldigiPane.getAccessibleContext().setAccessibleDescription(""); getContentPane().add(filler1, java.awt.BorderLayout.LINE_END); pack(); }// </editor-fold> private void hostActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void portActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void fldigi_connectButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void setdefaultButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new mainform().setVisible(true); } catch (XMLStreamException ex) { Logger.getLogger(JSSDV.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JSSDV.class.getName()).log(Level.SEVERE, null, ex); } } }); } // Variables declaration - do not modify private javax.swing.JLabel QRG; private javax.swing.JSlider compressionSlider; private javax.swing.JPanel debugPanel; private javax.swing.JTextField debugtext; private javax.swing.Box.Filler filler1; private javax.swing.JTabbedPane fldigiPane; private javax.swing.JToggleButton fldigi_connectButton; private javax.swing.JPanel fldigi_settingsPanel; private javax.swing.JTextField host; private javax.swing.JButton jButton2; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLayeredPane jLayeredPane1; private javax.swing.JList<String> jList1; private javax.swing.JPanel jPanel3; private javax.swing.JProgressBar jProgressBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSlider jSlider1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextField jTextField1; private javax.swing.JTree jTree1; private javax.swing.JPanel overlayPanel; private javax.swing.JTextField port; private javax.swing.JPanel rigPanel; private javax.swing.JPanel rxPanel; private javax.swing.JToggleButton rxidButton; private javax.swing.JButton setdefaultButton; private javax.swing.JPanel settingsPanel; private javax.swing.JPanel sidetalkPanel; private javax.swing.JTabbedPane topPane; private javax.swing.JList<String> txList; private javax.swing.JPanel txPanel; private javax.swing.JToggleButton txidButton; private javax.swing.JTabbedPane tximgPane; private javax.swing.JPanel tximgPanel; // End of variables declaration }
ploeffler/jSSDV
src/jssdv/JSSDV.java
Java
gpl-3.0
28,811
/* Copyright 2013 Northern Arizona University This file is part of Sweet Jumps. Sweet Jumps 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. Sweet Jumps 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 Sweet Jumps. If not, see <http://www.gnu.org/licenses/>. */ 'use strict' var logger = require('log4js').getLogger('[ctrl] {%= name %}') /** * {%= name %} controller initialization function. * @param {express} app The global express app. Preferably mount a subapp or router for all of this controller's routes. * @param {object} options Configuration if it exists * @param {[type]} context The instance of the SweetJumps class. Preferably you would not use this unless necessary (to getModule for instance). */ module.exports = function (app, options, context) { logger.info('{%= name %} controller init') app.get('/', function (req, res) { res.render('{%= filename %}/index', { 'message': 'Controller: {%= name %}' }) }) }
NorthernArizonaUniversity/sweet-jumps
templates/controller/root/controller.js
JavaScript
gpl-3.0
1,401
// -------------------------- // SPL Team Communication // (c) 2014 Qin He // -------------------------- #include <iostream> #include <string> #include <deque> #include "string.h" #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif #include "lua.h" #include "lualib.h" #include "lauxlib.h" #ifdef __cplusplus } #endif #include <vector> #include <algorithm> #include <stdint.h> #include "SPLStandardMessage.h" #define MAX_LENGTH 16000 //10240 static struct SPLStandardMessage SPLMessageData; static int nSPLMessageData = 0; static double recvTime = 0; //TODO: How long do we want the queue to be? const int maxQueueSize = 10; static std::string IP; static int PORT = 0; static int parsed = 0; static std::deque<SPLStandardMessage> recvQueue; static int send_fd, recv_fd; // Set IP and PORT static int lua_teamcomm_init(lua_State *L) { const char *ip = luaL_checkstring(L, 1); int port = luaL_checkint(L,2); IP = ip; PORT = port; assert(IP.empty()!=1); assert(PORT!=0); struct hostent *hostptr = gethostbyname(IP.c_str()); if (hostptr == NULL) { printf("Could not get hostname\n"); return -1; } send_fd = socket(AF_INET, SOCK_DGRAM, 0); if (send_fd < 0) { printf("Could not open datagram send socket\n"); return -1; } int i = 1; if (setsockopt(send_fd, SOL_SOCKET, SO_BROADCAST, (const char *) &i, sizeof(i)) < 0) { printf("Could not set broadcast option\n"); return -1; } struct sockaddr_in dest_addr; bzero((char *) &dest_addr, sizeof(dest_addr)); dest_addr.sin_family = AF_INET; bcopy(hostptr->h_addr, (char *) &dest_addr.sin_addr, hostptr->h_length); dest_addr.sin_port = htons(PORT); if (connect(send_fd, (struct sockaddr *) &dest_addr, sizeof(dest_addr)) < 0) { printf("Could not connect to destination address\n"); return -1; } recv_fd = socket(AF_INET, SOCK_DGRAM, 0); if (recv_fd < 0) { printf("Could not open datagram recv socket\n"); return -1; } struct sockaddr_in local_addr; bzero((char *) &local_addr, sizeof(local_addr)); local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = htonl(INADDR_ANY); local_addr.sin_port = htons(PORT); if (bind(recv_fd, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0) { printf("Could not bind to port\n"); return -1; } // Nonblocking receive: int flags = fcntl(recv_fd, F_GETFL, 0); if (flags == -1) flags = 0; if (fcntl(recv_fd, F_SETFL, flags | O_NONBLOCK) < 0) { printf("Could not set nonblocking mode\n"); return -1; } return 1; } // Parse incoming SPL standard message static int lua_teamcomm_recv_parse(lua_State *L, SPLStandardMessage *data) { if (data == NULL) { return 0; } // Verify struct header if (strncmp(data->header, SPL_STANDARD_MESSAGE_STRUCT_HEADER, 4) != 0) { return 0; } lua_createtable(L, 0, 13); //TODO: recvTime // version field lua_pushstring(L, "version"); lua_pushnumber(L, data->version); lua_settable(L, -3); // Player number: 1-5 lua_pushstring(L, "playerNum"); lua_pushnumber(L, data->playerNum); lua_settable(L, -3); // Team: 0-blue, 1-red lua_pushstring(L, "teamNum"); lua_pushnumber(L, data->teamNum); lua_settable(L, -3); //1: fallen, 0: able to play lua_pushstring(L, "fallen"); lua_pushnumber(L, data->fallen); lua_settable(L, -3); // position and orientation of robot // coordinates in millimeters, angle in radians lua_pushstring(L, "pose"); lua_createtable(L, 3, 0); for (int i=0; i<3; i++) { lua_pushnumber(L, data->pose[i]); lua_rawseti(L, -2, i+1); } lua_settable(L, -3); // the robot's target position on the field // if the robot does not have any target, // this attribute should be set to the robot's position lua_pushstring(L, "walkingTo"); lua_createtable(L, 2, 0); lua_pushnumber(L, data->walkingTo[0]); lua_rawseti(L, -2, 1); lua_pushnumber(L, data->walkingTo[1]); lua_rawseti(L, -2, 2); lua_settable(L, -3); // the target position of the next shot (either pass or goal shot) // if the robot does not intend to shoot, //this attribute should be set to the robot's position lua_pushstring(L, "shootingTo"); lua_createtable(L, 2, 0); lua_pushnumber(L, data->shootingTo[0]); lua_rawseti(L, -2, 1); lua_pushnumber(L, data->shootingTo[1]); lua_rawseti(L, -2, 2); lua_settable(L, -3); // ms since this robot last saw the ball. -1 if we haven't seen it lua_pushstring(L, "ballAge"); lua_pushnumber(L, data->ballAge); lua_settable(L, -3); // position of ball relative to the robot // coordinates in millimeters lua_pushstring(L, "ball"); lua_createtable(L, 2, 0); lua_pushnumber(L, data->ball[0]); lua_rawseti(L, -2, 1); lua_pushnumber(L, data->ball[1]); lua_rawseti(L, -2, 2); lua_settable(L, -3); lua_pushstring(L, "ballVel"); lua_createtable(L, 2, 0); lua_pushnumber(L, data->ballVel[0]); lua_rawseti(L, -2, 1); lua_pushnumber(L, data->ballVel[1]); lua_rawseti(L, -2, 2); lua_settable(L, -3); lua_pushstring(L, "suggestion"); lua_createtable(L, 2, 0); lua_pushnumber(L, data->suggestion[0]); lua_rawseti(L, -2, 1); lua_pushnumber(L, data->suggestion[1]); lua_rawseti(L, -2, 2); lua_pushnumber(L, data->suggestion[2]); lua_rawseti(L, -2, 3); lua_pushnumber(L, data->suggestion[3]); lua_rawseti(L, -2, 4); lua_pushnumber(L, data->suggestion[4]); lua_rawseti(L, -2, 5); lua_settable(L, -3); // Intention lua_pushstring(L, "intention"); lua_pushnumber(L, data->intention); lua_settable(L, -3); lua_pushstring(L, "averageWalkSpeed"); lua_pushnumber(L, data->averageWalkSpeed); lua_settable(L, -3); lua_pushstring(L, "maxKickDistance"); lua_pushnumber(L, data->maxKickDistance); lua_settable(L, -3); lua_pushstring(L, "currentPositionConfidence"); lua_pushnumber(L, data->currentPositionConfidence); lua_settable(L, -3); lua_pushstring(L, "currentSideConfidence"); lua_pushnumber(L, data->currentSideConfidence); lua_settable(L, -3); lua_pushstring(L, "numOfDataBytes"); lua_pushnumber(L, data->numOfDataBytes); lua_settable(L, -3); //Simple array instead of string uint16_t textlength = data->numOfDataBytes; lua_pushstring(L, "data"); lua_createtable(L, textlength, 0); for (int i=0; i<textlength; i++) { lua_pushnumber(L, data->data[i]); lua_rawseti(L, -2, i+1); } lua_settable(L, -3); return 1; } // Set SPLStandardMessage struct static int lua_teamcomm_send_parse(lua_State *L, SPLStandardMessage *msg) { luaL_checktype(L,1, LUA_TTABLE); // TODO: check if the key exists // header lua_pushstring(L, "header"); lua_gettable(L, -2); *(uint32_t*) msg->header = *(const uint32_t*)SPL_STANDARD_MESSAGE_STRUCT_HEADER; lua_pop(L, 1); lua_pushstring(L, "version"); lua_gettable(L, -2); uint8_t userversion = (uint8_t)lua_tonumber(L, -1); if (userversion != SPL_STANDARD_MESSAGE_STRUCT_VERSION) printf("version wrong! Must use %d\n",SPL_STANDARD_MESSAGE_STRUCT_VERSION); msg->version = SPL_STANDARD_MESSAGE_STRUCT_VERSION; lua_pop(L, 1); lua_pushstring(L, "playerNum"); lua_gettable(L, -2); msg->playerNum = lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "teamNum"); lua_gettable(L, -2); msg->teamNum = lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "fallen"); lua_gettable(L, -2); msg->fallen = lua_tonumber(L, -1); lua_pop(L, 1); //TODO: better way to get values from lua table? lua_pushstring(L, "pose"); lua_gettable(L, -2); for (int i=0; i<3; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->pose[i] = lua_tonumber(L, -1); lua_pop(L, 1); } lua_pop(L,1); lua_pushstring(L, "walkingTo"); lua_gettable(L, -2); for (int i=0; i<2; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->walkingTo[i] = lua_tonumber(L, -1); lua_pop(L, 1); } lua_pop(L,1); lua_pushstring(L, "shootingTo"); lua_gettable(L, -2); for (int i=0; i<2; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->shootingTo[i] = lua_tonumber(L, -1); lua_pop(L, 1); } lua_pop(L,1); lua_pushstring(L, "ballAge"); lua_gettable(L, -2); msg->ballAge = lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "ball"); lua_gettable(L, -2); for (int i=0; i<2; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->ball[i] = lua_tonumber(L, -1); lua_pop(L, 1); } lua_pop(L,1); lua_pushstring(L, "ballVel"); lua_gettable(L, -2); for (int i=0; i<2; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->ballVel[i] = lua_tonumber(L, -1); lua_pop(L, 1); } lua_pop(L,1); lua_pushstring(L, "suggestion"); lua_gettable(L, -2); for (int i=0; i<5; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->suggestion[i] = (int8_t)lua_tonumber(L, -1); lua_pop(L, 1); } lua_pop(L,1); lua_pushstring(L, "intention"); lua_gettable(L, -2); msg->intention = (int8_t)lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "averageWalkSpeed"); lua_gettable(L, -2); msg->averageWalkSpeed = (int16_t)lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "maxKickDistance"); lua_gettable(L, -2); msg->maxKickDistance = (int16_t)lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "currentPositionConfidence"); lua_gettable(L, -2); msg->currentPositionConfidence = (int8_t)lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "currentSideConfidence"); lua_gettable(L, -2); msg->currentSideConfidence = (int8_t)lua_tonumber(L, -1); lua_pop(L, 1); lua_pushstring(L, "numOfDataBytes"); lua_gettable(L, -2); int num = lua_tonumber(L, -1); if (num>SPL_STANDARD_MESSAGE_DATA_SIZE){ num = SPL_STANDARD_MESSAGE_DATA_SIZE; printf("Warning! Arbitrary data oversized. Only the first %d bytes will be sent\n",num); } msg->numOfDataBytes = num; lua_pop(L, 1); //Simple array instead of string lua_pushstring(L, "data"); lua_gettable(L, -2); for (int i=0; i<num; i++) { lua_pushinteger(L, i+1); lua_gettable(L, -2); msg->data[i] = (uint8_t)lua_tonumber(L, -1);; lua_pop(L, 1); } lua_pop(L,1); return 1; } static int lua_teamcomm_update(lua_State *L) { static sockaddr_in source_addr; static char data[MAX_LENGTH]; // Process incoming messages socklen_t source_addr_len = sizeof(source_addr); int len = recvfrom(recv_fd, data, MAX_LENGTH, 0, (struct sockaddr *) &source_addr, &source_addr_len); nSPLMessageData = 0; while (len > 0) { //TODO: this might be slow memcpy(&SPLMessageData, data, sizeof(SPLStandardMessage)); nSPLMessageData++; //printf("parsed? %d\n", parsed); if (!recvQueue.empty() && parsed==1) { parsed = 0; recvQueue.pop_front(); } recvQueue.push_back(SPLMessageData); // printf("Queue size: %d \n", recvQueue.size()); len = recvfrom(recv_fd, data, MAX_LENGTH, 0, (struct sockaddr *) &source_addr, &source_addr_len); } // Remove older messages while (recvQueue.size() > maxQueueSize) { recvQueue.pop_front(); } return 1; } static int lua_teamcomm_size(lua_State *L) { int updateRet = lua_teamcomm_update(L); lua_pushinteger(L, recvQueue.size()); return 1; } static int lua_teamcomm_receive(lua_State *L) { int updateRet = lua_teamcomm_update(L); if (nSPLMessageData==0 || recvQueue.empty()) { // no messages received yet lua_pushnil(L); return 1; } if (!recvQueue.empty()) { parsed = 1; return lua_teamcomm_recv_parse(L, &recvQueue.front()); } return 1; } static int lua_teamcomm_send(lua_State *L) { struct SPLStandardMessage senddata; lua_teamcomm_send_parse(L, &senddata); int ret = send(send_fd, &senddata, sizeof(senddata), 0); lua_pushinteger(L, ret); return 1; } static const struct luaL_reg TeamComm_lib [] = { {"init", lua_teamcomm_init}, {"size", lua_teamcomm_size}, {"receive", lua_teamcomm_receive}, {"send", lua_teamcomm_send}, {NULL, NULL} }; #ifdef __cplusplus extern "C" #endif int luaopen_TeamComm (lua_State *L) { luaL_register(L, "TeamComm", TeamComm_lib); return 1; }
UPenn-RoboCup/UPennalizers
Lib/Platform/NaoV4/TeamComm/lua_TeamComm.cpp
C++
gpl-3.0
12,408
<?php if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Cash on Delivery Gateway. * * Provides a Cash on Delivery Payment Gateway. * * @class WC_Gateway_COD * @extends WC_Payment_Gateway * @version 2.1.0 * @package WooCommerce/Classes/Payment * @author WooThemes */ class WC_Gateway_COD extends WC_Payment_Gateway { /** * Constructor for the gateway. */ public function __construct() { $this->id = 'cod'; $this->icon = apply_filters( 'woocommerce_cod_icon', '' ); $this->method_title = __( 'Cash on delivery', 'woocommerce' ); $this->method_description = __( 'Have your customers pay with cash (or by other means) upon delivery.', 'woocommerce' ); $this->has_fields = false; // Load the settings $this->init_form_fields(); $this->init_settings(); // Get settings $this->title = $this->get_option( 'title' ); $this->description = $this->get_option( 'description' ); $this->instructions = $this->get_option( 'instructions', $this->description ); $this->enable_for_methods = $this->get_option( 'enable_for_methods', array() ); $this->enable_for_virtual = $this->get_option( 'enable_for_virtual', 'yes' ) === 'yes' ? true : false; add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); add_action( 'woocommerce_thankyou_cod', array( $this, 'thankyou_page' ) ); // Customer Emails add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 ); } /** * Initialise Gateway Settings Form Fields. */ public function init_form_fields() { $shipping_methods = array(); foreach ( WC()->shipping()->load_shipping_methods() as $method ) { $shipping_methods[ $method->id ] = $method->get_method_title(); } $this->form_fields = array( 'enabled' => array( 'title' => __( 'Enable/Disable', 'woocommerce' ), 'label' => __( 'Enable cash on delivery', 'woocommerce' ), 'type' => 'checkbox', 'description' => '', 'default' => 'no', ), 'title' => array( 'title' => __( 'Title', 'woocommerce' ), 'type' => 'text', 'description' => __( 'Payment method description that the customer will see on your checkout.', 'woocommerce' ), 'default' => __( 'Cash on delivery', 'woocommerce' ), 'desc_tip' => true, ), 'description' => array( 'title' => __( 'Description', 'woocommerce' ), 'type' => 'textarea', 'description' => __( 'Payment method description that the customer will see on your website.', 'woocommerce' ), 'default' => __( 'Pay with cash upon delivery.', 'woocommerce' ), 'desc_tip' => true, ), 'instructions' => array( 'title' => __( 'Instructions', 'woocommerce' ), 'type' => 'textarea', 'description' => __( 'Instructions that will be added to the thank you page.', 'woocommerce' ), 'default' => __( 'Pay with cash upon delivery.', 'woocommerce' ), 'desc_tip' => true, ), 'enable_for_methods' => array( 'title' => __( 'Enable for shipping methods', 'woocommerce' ), 'type' => 'multiselect', 'class' => 'wc-enhanced-select', 'css' => 'width: 450px;', 'default' => '', 'description' => __( 'If COD is only available for certain methods, set it up here. Leave blank to enable for all methods.', 'woocommerce' ), 'options' => $shipping_methods, 'desc_tip' => true, 'custom_attributes' => array( 'data-placeholder' => __( 'Select shipping methods', 'woocommerce' ), ), ), 'enable_for_virtual' => array( 'title' => __( 'Accept for virtual orders', 'woocommerce' ), 'label' => __( 'Accept COD if the order is virtual', 'woocommerce' ), 'type' => 'checkbox', 'default' => 'yes', ), ); } /** * Check If The Gateway Is Available For Use. * * @return bool */ public function is_available() { $order = null; $needs_shipping = false; // Test if shipping is needed first if ( WC()->cart && WC()->cart->needs_shipping() ) { $needs_shipping = true; } elseif ( is_page( wc_get_page_id( 'checkout' ) ) && 0 < get_query_var( 'order-pay' ) ) { $order_id = absint( get_query_var( 'order-pay' ) ); $order = wc_get_order( $order_id ); // Test if order needs shipping. if ( 0 < sizeof( $order->get_items() ) ) { foreach ( $order->get_items() as $item ) { $_product = $item->get_product(); if ( $_product && $_product->needs_shipping() ) { $needs_shipping = true; break; } } } } $needs_shipping = apply_filters( 'woocommerce_cart_needs_shipping', $needs_shipping ); // Virtual order, with virtual disabled if ( ! $this->enable_for_virtual && ! $needs_shipping ) { return false; } // Check methods if ( ! empty( $this->enable_for_methods ) && $needs_shipping ) { // Only apply if all packages are being shipped via chosen methods, or order is virtual $chosen_shipping_methods_session = WC()->session->get( 'chosen_shipping_methods' ); if ( isset( $chosen_shipping_methods_session ) ) { $chosen_shipping_methods = array_unique( $chosen_shipping_methods_session ); } else { $chosen_shipping_methods = array(); } $check_method = false; if ( is_object( $order ) ) { if ( $order->shipping_method ) { $check_method = $order->shipping_method; } } elseif ( empty( $chosen_shipping_methods ) || sizeof( $chosen_shipping_methods ) > 1 ) { $check_method = false; } elseif ( sizeof( $chosen_shipping_methods ) == 1 ) { $check_method = $chosen_shipping_methods[0]; } if ( ! $check_method ) { return false; } $found = false; foreach ( $this->enable_for_methods as $method_id ) { if ( strpos( $check_method, $method_id ) === 0 ) { $found = true; break; } } if ( ! $found ) { return false; } } return parent::is_available(); } /** * Process the payment and return the result. * * @param int $order_id * @return array */ public function process_payment( $order_id ) { $order = wc_get_order( $order_id ); // Mark as processing or on-hold (payment won't be taken until delivery) $order->update_status( apply_filters( 'woocommerce_cod_process_payment_order_status', $order->has_downloadable_item() ? 'on-hold' : 'processing', $order ), __( 'Payment to be made upon delivery.', 'woocommerce' ) ); // Reduce stock levels wc_reduce_stock_levels( $order_id ); // Remove cart WC()->cart->empty_cart(); // Return thankyou redirect return array( 'result' => 'success', 'redirect' => $this->get_return_url( $order ), ); } /** * Output for the order received page. */ public function thankyou_page() { if ( $this->instructions ) { echo wpautop( wptexturize( $this->instructions ) ); } } /** * Add content to the WC emails. * * @access public * @param WC_Order $order * @param bool $sent_to_admin * @param bool $plain_text */ public function email_instructions( $order, $sent_to_admin, $plain_text = false ) { if ( $this->instructions && ! $sent_to_admin && 'cod' === $order->get_payment_method() ) { echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL; } } }
bryceadams/woocommerce
includes/gateways/cod/class-wc-gateway-cod.php
PHP
gpl-3.0
7,485
Ext.define('Hrproject.view.clouddrive.documentview.DocumentsViewController',{ extend : 'Ext.app.ViewController', requires:['Hrproject.view.fw.PDF.panel.PDF'], alias : 'controller.documentview', clouddrive : null, drivelist : null, driveDetails : null, driveDetailsController : null, frame : null, downloadFileform : null, selectedFileId:null, selectedFileNode:null, baseFileId:null, moveToTagId:null, fileUploadWindow:null, init : function() { this.clouddrive = this.getView().up().up(); /*create form and iframe used to download file*/ var body = Ext.getBody(); this.frame = body.createChild({ tag : 'iframe', cls : 'x-hidden', id : 'hiddenform-iframe' + this.getView().id, name : 'iframe' + this.getView().id }); this.downloadFileform = body.createChild({ tag : 'form', cls : 'x-hidden', id : 'hiddenform-form' + this.getView().id, method : 'post', ContentType : 'application/json;application/xml', action : "", target : 'iframe' + this.getView().id }); }, initObject : function() { this.driveDetails = this.clouddrive.down("#drivedetails"); this.driveDetailsController = this.driveDetails.controller; this.drivelist = this.driveDetails.down("#drivelist"); this.manageRevGridStore=this.getManageRevGridStore(); }, loadData : function(panel, eopts) { this.initObject(); }, /* * this method call when user call on folder/file if user * click on folder then folder will open if user clock on * file the file will download */ itemdblclick : function(dataview, record) { if (record.data.hierarchy.length > 0) { this.driveDetailsController.selectNode(record.data.id, true) } else { this.downloadFiles(record.data.ftId); } }, /** this method is used to download file*/ downloadFiles : function(fileId) { this.downloadFileform.dom.action = "secure/cloudDriveController/downloadFilePost?fileId=" + fileId, this.downloadFileform.dom.submit(); }, /* * this method call on right click of any file/folder * this will show menu which contains - preview,download */ itemcontextmenu : function(dataview, record, item, index,e, eOpts) { debugger; e.stopEvent(); this.selectedFileId = record.data.ftId; this.selectedFileNode =record; var menu = this.getRightClickMenu(record.data.hierarchy); menu.showAt(e.getXY()); }, getRightClickMenu : function(hierarchy) { var nodesHieraObj = this.driveDetailsController.nodesHieraObj; if (nodesHieraObj[nodesHieraObj.length - 1].data.ftId == -1&& hierarchy.length > 0) { return; } return Ext.create('Ext.menu.Menu',{ items : [ hierarchy.length > 0 ? "": Ext.create('Ext.Action', { text : 'Preview', icon : 'images/cloud/previewDoc.png', listeners:{ click:'onPreviewClick', scope:this } },this), hierarchy.length > 0 ? "": Ext.create('Ext.Action', { text : 'Download', icon : 'images/cloud/download.png', listeners:{ click:'onDownLoadClick', scope:this } }), hierarchy.length > 0 ? "": '-', nodesHieraObj[nodesHieraObj.length - 1].data.ftId == -2 && hierarchy.length == 0 ? Ext.create('Ext.Action', { text : 'Move To', icon : 'images/cloud/moveTo.png', listeners:{ click:'onMoveToClick', scope:this } }) : "", nodesHieraObj[nodesHieraObj.length - 1].data.ftId == -2 && hierarchy.length == 0 ? Ext.create('Ext.Action', { text : 'Share', icon : 'images/cloud/ic_share.png', listeners:{ click:'onShareClick', scope:this } }) : "", nodesHieraObj[nodesHieraObj.length - 1].data.ftId == -2 && hierarchy.length == 0 ? Ext.create('Ext.Action', { text : 'Rename', icon : 'images/cloud/rename.png', listeners:{ click:'onRenameClick', scope:this } }) : "", nodesHieraObj[nodesHieraObj.length - 1].data.ftId == -2 && hierarchy.length == 0 ? Ext.create('Ext.Action', { text : 'Add Star', disabled:true, icon : 'images/cloud/addStar.png', handler : function() { } }) : "", nodesHieraObj[nodesHieraObj.length - 1].data.ftId != -1 && hierarchy.length == 0 ? Ext.create('Ext.Action', { text : 'Manage revisions', icon : 'images/cloud/mr.png', listeners:{ click:'onMakeRevisionClick', scope:this } }) : "", nodesHieraObj[nodesHieraObj.length - 1].data.ftId != -1 && hierarchy.length == 0 ? Ext.create('Ext.Action', { text : 'Make a Copy', icon : 'images/cloud/make-copy.png', listeners:{ click:'onMakeCopyClick', scope:this } }):"", nodesHieraObj[nodesHieraObj.length - 1].data.ftId == -1 ? "": Ext.create('Ext.Action', { text : 'Remove', icon : 'images/trash.png', listeners:{ click:'deleteFunc1', scope:this } }) ] },this); },//getRightClickMenu ends onPreviewClick : function() { var appType = this.selectedFileNode.data.applicationType; if (appType.search("pdf") != -1) { this.openPDFViewer(this.selectedFileId,this.selectedFileNode.data.text); } else if (appType.search("image") != -1) { this.openImageViewer(this.selectedFileId,this.selectedFileNode.data.text); } else { this.downloadFiles(this.selectedFileId); } }, openPDFViewer:function(fileId, displayName) { debugger;; Ext.create('Ext.window.Window', { title : displayName, height : 500, width : 700, maximizable : true, layout : 'fit', items : [{ xtype :'pdfpanel', title : '', width : 589, height : 433, pageScale : 0.75, // Initial scaling of the PDF. 1 = 100% // src : '../buzzor/SpringByExample.pdf', // URL to the PDF - // Same Domain or Server with CORS Support src : 'secure/cloudDriveController/downloadFile?fileId=' + fileId }] }).show(); }, openImageViewer:function(fileId, displayName) { Ext.create('Ext.window.Window', { title : displayName, height : 500, width : 700, maximizable : true, layout : 'fit', items : { xtype : 'image', title : '', width : 589, height : 433, pageScale : 0.75, // Initial scaling of the PDF. 1 = 100% // src : '../buzzor/SpringByExample.pdf', // URL to the PDF - // Same Domain or Server with CORS Support src : 'secure/cloudDriveController/downloadFile?fileId=' + fileId } }).show(); }, onDownLoadClick:function() { this.downloadFiles(this.selectedFileId); }, deleteFunc1:function() { debugger; // File - 0 // Tag - 1 var isFileTag = -1; var selId = this.selectedFileNode.data.id; if (selId.search("f") == 0) { isFileTag = 0; } else if (selId.search("t") == 0) { isFileTag = 1; } this.deleteFunc(isFileTag, this.selectedFileId); }, deleteFunc:function(isFileTag, selectedFileId, rowIndex, grid) { Ext.Msg.confirm('Confirmation',"Are you sure you want to delete Folder/File", function(id, value) { if (id == 'yes') { /**Check if grid is defined then del function is called from grid or else called from right click menu*/ if(this.grid!=undefined){ this.grid.getStore().removeAt(this.rowIndex); this.me.deleteOperation(isFileTag, selectedFileId); } else{ this.me.deleteOperation(isFileTag, selectedFileId); } } }, { me : this, rowIndex:rowIndex, grid:grid }); }, deleteOperation:function(isFileTag, selectedFileId) { debugger; Ext.Ajax.request({ url : 'secure/cloudDriveController/deleteTagsFile?fileId='+selectedFileId+"&isFileTag="+isFileTag, headers : { 'Content-Type' : 'application/json;application/xml' }, waitMsg : 'Loading...', method : 'POST', scope:this, params : { fileId : selectedFileId, isFileTag : isFileTag }, success : function(response,currentObject) { debugger; currentObject.scope.driveDetails.controller.refreshDriveTree(); Ext.Msg.alert('Success',"Files Deleted successfully"); }, failure : function(response) { Ext.Msg.alert('Error', 'Cannot connect to server'); } }); }, onMakeCopyClick:function() { debugger; var selectedFileId= this.selectedFileId; Ext.Ajax.request({ url : 'secure/cloudDriveController/copyFile?fileId='+selectedFileId, headers : {'Content-Type' : 'application/json;application/xml'}, waitMsg : 'Loading...', method : 'POST', scope:this, params : { fileId : selectedFileId, }, success : function(response,currentObject) { currentObject.scope.driveDetails.controller.refreshDriveTree(); Ext.Msg.alert('Success',"Files Copied successfully"); }, failure : function(response) { Ext.Msg.alert('Error', 'Cannot connect to server'); } }); }, onRenameClick:function() { Ext.create('Ext.window.Window', { title :'Rename File', width:'25%', maximizable : true, resizable : true, layout : 'vbox', bodyPadding:'8', items :[{ xtype:'textfield', fieldLabel:'New Name', value:this.selectedFileNode.data.text, itemId:'renameFieldId', width:'100%', }], buttons:[{ text:'Save', icon:'images/greenFlopy_save.png', style:'float:right', listeners:{ click:'onRenameSaveBtnClick', scope:this, } },{ text:'Cancel', icon:'images/delete_icon.png', style:'float:right', handler:function(){ this.up().up().close(); } }] }).show(); }, onRenameSaveBtnClick:function(btn) { var selectedFileId=this.selectedFileId; var newFileName=btn.up().up().down('#renameFieldId').getValue(); Ext.Ajax.request({ url : 'secure/cloudDriveController/renameFile?fileId='+selectedFileId+"&newFileName="+newFileName, headers : {'Content-Type' : 'application/json;application/xml'}, waitMsg : 'Loading...', method : 'POST', scope:this, btn:btn, params : { fileId : selectedFileId, newFileName : newFileName }, success : function(response,currentObject) { currentObject.scope.driveDetails.controller.refreshDriveTree(); currentObject.btn.up().up().close(); Ext.Msg.alert('Success',"Files Renamed successfully"); }, failure : function(response) { Ext.Msg.alert('Error', 'Cannot connect to server'); } }); }, onMoveToClick:function() { Ext.create('Ext.window.Window', { title :'Choose Destination Folder', width:'20%', height:300, maximizable : true, resizable : true, tbar:['->',{ xtype : 'button', icon : 'images/cloud/newFolder.png', tooltip:'Add New Folder', listeners:{ click:'onAddNewFolderClick', scope:this } }], items :[{ xtype : 'treepanel', itemId : 'folderlist', rootVisible :false, useArrows: true, listeners : { load : 'loadMoveToFolderList', itemClick:'onClickFolderList', scope:this } }], buttons:[{ text:'Move', icon:'images/cloud/moveRight.png', style:'float:right', listeners:{ click:'onMoveBtnClick', scope:this, } },{ text:'Cancel', icon:'images/delete_icon.png', style:'float:right', handler:function(){ this.up().up().close(); } }] }).show(); }, loadMoveToFolderList:function(treepanel) { debugger; var data=this.driveDetailsController.drivelistTreeData; var rootNode = treepanel.getRootNode(); rootNode.removeAll(); for (var x1 = 0; x1 < data.length; x1++) { this.addChild(rootNode, data[x1]); } }, addChild : function(parentNode, node) { if (node.hasOwnProperty("children")&& node.children != null) { if(node.hierarchy!=3) { var child = { text : node.text, icon : "images/folder_crisp.png", image : node.image, hierarchy : node.hierarchy, id : node.id, files : node.files, displayText : node.displayText, ftId : node.ftId, mimeType : node.mimeType, } if(node.children.length==0){ child["leaf"]=true; } var newNode = parentNode.appendChild(child); } for (var x = 0; x < node.children.length; x++) { this.addChild(newNode, node.children[x]); } } else { node["leaf"]=true; parentNode.appendChild(node); } }, onClickFolderList : function(view, record, item, index, e) { debugger; this.driveDetailsController.moveToSelectedNode=record.data; this.moveToTagId=record.data.ftId }, onMoveBtnClick:function(btn) { debugger; var selectedFileId=this.selectedFileId; var tagId=this.moveToTagId; /*grid=btn.up().up().down('#folderListGrid'); var tagId=grid.getSelectionModel().getSelection()[0].data.tagId;*/ Ext.Ajax.request({ url : 'secure/cloudDriveController/moveFile?fileId='+selectedFileId+"&tagId="+tagId, headers : {'Content-Type' : 'application/json;application/xml'}, waitMsg : 'Loading...', method : 'POST', scope:this, btn:btn, params : { fileId : selectedFileId, tagId : tagId }, success : function(response,currentObject) { debugger; currentObject.scope.driveDetails.controller.refreshDriveTree(); currentObject.btn.up().up().close(); Ext.Msg.alert('Success',"Files Moved successfully"); }, failure : function(response) { Ext.Msg.alert('Error', 'Cannot connect to server'); } }); }, onAddNewFolderClick:function(btn) { debugger; this.driveDetailsController.createFolderFlag="gridView"; this.driveDetailsController.moveToTreePanel=btn.up().up().down("#folderlist"); this.driveDetailsController.onCreateFolderBtnClick(); }, onShareClick:function() { Ext.create('Ext.window.Window', { title :'Share With', width:'25%', maximizable : true, resizable : true, layout : 'vbox', //bodyPadding:'8', items :[{ xtype:'gridpanel', itemId:'shareUserGrid', selType: 'checkboxmodel', multiSelect : true, border:true, store:new Ext.create('Ext.data.Store', { fields : ['loginId','firstName','userId','lastName'], data : [], sorters: ['firstName'] }), columns : [{ text : "User Name", sortable : true, resizable : true, menuDisabled : true, dataIndex : 'loginId', flex : 0.333333333, },{ text : "First Name", sortable : true, resizable : true, menuDisabled : true, dataIndex : 'firstName', flex : 0.333333333, },{ text : "Last Name", sortable : true, resizable : true, menuDisabled : true, dataIndex : 'lastName', flex : 0.333333333, },{ dataIndex:"userId", hidden:true, } ], title : '', width : '100%', //height : 380, listeners:{ afterrender:'afterShareUserGridRender', scope:this } }], buttons:[{ text:'Share', icon:'images/cloud/share.png', style:'float:right', listeners:{ click:'onShareBtnClick', scope:this, } },{ text:'Cancel', icon:'images/delete_icon.png', style:'float:right', handler:function(){ this.up().up().close(); } }] }).show(); }, afterShareUserGridRender:function(grid) { Ext.Ajax.request({ url : "secure/cloudDriveController/getUsers", method : 'POST', scope : this, grid:grid, waitMsg : 'Loading...', jsonData : {}, success : function(response, currentObject,options) { debugger; var jsonResponse = Ext.JSON.decode(response.responseText); var data = jsonResponse.response.data; var tempData=[]; for(var i=0;i<data.length;i++) { var obj={ loginId:data[i].loginId, firstName:data[i].firstName, lastName:data[i].lastName, userId:data[i].userId } tempData.push(obj); } currentObject.grid.getStore().loadData(tempData); }, failure : function() { Ext.Msg.alert('Error','Cannot connect to server'); } }); }, onShareBtnClick:function(btn) { debugger; var grid=btn.up().up().down("#shareUserGrid"); var jsonData=[]; if (grid.getSelectionModel().hasSelection()) { var rows = grid.getSelectionModel().getSelection(); for (var x = 0; x < rows.length; x++) { var obj={ sharedUserId:rows[x].data.userId, fileId:this.selectedFileId } jsonData.push(obj); } //console.log(jsonData); Ext.Ajax.request({ url : "secure/cloudDriveController/saveFileSharedToUser", method : 'POST', headers : {'Content-Type' : 'application/json;application/xml'}, jsonData:jsonData, btn:btn, success : function(response, currentObject,options) { debugger; var jsonResponse = Ext.JSON.decode(response.responseText); if(jsonResponse.response.success==true){ Ext.Msg.alert('Success',"File Shared Successfully"); currentObject.btn.up().up().close(); } else{ Ext.Msg.alert('Error', 'Sharing of File Failed!'); } }, failure : function() { Ext.Msg.alert('Error', 'Cannot connect to server!'); } }); } }, onMakeRevisionClick:function() { Ext.create('Ext.window.Window', { title :'Manage Revision', width:'30%', height:300, maximizable : true, resizable : true, autoScroll:true, layout:'fit', items:[{ xtype:'form', layout : 'vbox', items :[{ xtype : 'filefield', margin:'5 1 5 322', msgTarget : 'side', allowBlank : false, buttonOnly : true, name : 'uploadFile', buttonConfig : { text:'Upload New Revision', icon : 'images/cloud/uploadRevision.png', tooltip:'Upload New Revision', }, listeners:{ change:'onUpldNewRev', scope:this } }, { xtype:'gridpanel', width:'100%', border:true, margin:'2', selType: 'cellmodel', scope:this, //Pass current controller scope store:this.manageRevGridStore, columns : [ { xtype : 'actioncolumn', menuDisabled : true, text : 'Delete', align: 'center', flex:0.15, items : [ { //icon : 'images/delete.gif',/**No need to give icon or tooltip if they are mentioned in getClass & if hidden-class is returned then icon attr req*/ tooltip : 'Delete Record', getClass: function(v, metadata, r, rowIndex, colIndex, store) { if(rowIndex==0) { return "icon-disable"; //return "x-hidden-display"; }else{ return "icon-enable"; } }, handler : function(grid, rowIndex, colIndex){ if(rowIndex!=0){ rec=grid.getStore().getAt(rowIndex); var me=this.up().up().scope; me.deleteFunc(0, rec.data.fileId,rowIndex,grid); }else{ Ext.Msg.alert('Info',"Cannot delete latest version of the file"); } } }] },{ text:'Current Revision Date', dataIndex:'createdDate', flex:0.3 },{ text:'Current Revision By', dataIndex:'updatedBy', flex:0.3 },{ text:'Storage Used', dataIndex:'fileSize', flex:0.2 }], listeners:{ afterrender:'afterManageRevGridRender', cellclick :'revGridCellClick', scope:this } }], }], buttons:[{ text:'Cancel', icon:'images/delete_icon.png', style:'float:right', handler:function(){ this.up().up().close(); } }] }).show(); }, getManageRevGridStore:function() { return new Ext.create('Ext.data.Store', { fields : ['baseFileId','fileId','updatedBy','createdDate','fileSize'], data : [] }); }, afterManageRevGridRender:function(grid) { var selectedFileId=this.selectedFileId; Ext.Ajax.request({ url : "secure/cloudDriveController/getFileRevision?fileId="+selectedFileId, method : 'POST', scope : this, waitMsg : 'Loading...', jsonData : {}, /*params:{ fileId:selectedFileId },*/ success : function(response, params,options) { debugger; var responseJson = Ext.JSON.decode(response.responseText).response; if (responseJson.success == 'true') { var data = responseJson.data; params.scope.baseFileId=data[0].baseFileId; params.scope.manageRevGridStore.loadData(data); } else { Ext.Msg.alert('Error',"loading of manage revision grid failed"); } }, failure : function() { Ext.Msg.alert('Error','Cannot connect to server'); } }); }, onUpldNewRev:function(fileupload) { debugger; this.fileUploadWindow=fileupload.up().up(); var entMask = new Ext.LoadMask({ msg : 'Uploading...', target : fileupload.up().up() }).show(); var form = fileupload.up('form').getForm(); if (form.isValid()) { form.submit({url : 'secure/cloudDriveController/uploadRevisionFile?parentId=' + this.driveDetailsController.selNode.ftId + "&parentHierachy=" + this.driveDetailsController.selNode.hierarchy + "&oldFileId=" + this.selectedFileId + "&baseFileId=" + this.baseFileId, scope : this, entMask:entMask, success : function(fp, currentObject) { debugger; currentObject.entMask.hide(); currentObject.scope.driveDetails.controller.refreshDriveTree(); currentObject.scope.afterManageRevGridRender(); currentObject.scope.fileUploadWindow.close(); Ext.Msg.alert('Success',"Files With New Revision Uploaded successfully"); } }); } }, revGridCellClick:function(iView, iCellEl,iColIdx, iStore, iRowEl, iRowIdx,iEvent) { /** If 2nd Column's cell is clicked then Download File*/ if (iColIdx == 1) { this.downloadFiles(iStore.data.fileId); } } });
applifireAlgo/HR
hrproject/src/main/webapp/app/view/clouddrive/documentview/DocumentsViewController.js
JavaScript
gpl-3.0
23,318
# -*- coding: utf-8 -*- import re from channels import renumbertools from channelselector import get_thumb from core import httptools from core import scrapertools from core import servertools from core import tmdb from core.item import Item from platformcode import config, logger from channels import autoplay IDIOMAS = {'latino': 'Latino'} list_language = IDIOMAS.values() list_servers = ['openload', 'okru', 'netutv', 'rapidvideo' ] list_quality = ['default'] host = "http://www.anitoonstv.com" def mainlist(item): logger.info() thumb_series = get_thumb("channels_tvshow.png") autoplay.init(item.channel, list_servers, list_quality) itemlist = list() itemlist.append(Item(channel=item.channel, action="lista", title="Anime", url=host, thumbnail=thumb_series)) itemlist.append(Item(channel=item.channel, action="lista", title="Series Animadas", url=host, thumbnail=thumb_series)) itemlist.append(Item(channel=item.channel, action="lista", title="Novedades", url=host, thumbnail=thumb_series)) itemlist.append(Item(channel=item.channel, action="lista", title="Pokemon", url=host, thumbnail=thumb_series)) itemlist = renumbertools.show_option(item.channel, itemlist) autoplay.show_option(item.channel, itemlist) return itemlist def lista(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;", "", data) if 'Novedades' in item.title: patron_cat = '<div class="activos"><h3>(.+?)<\/h2><\/a><\/div>' patron = '<a href="(.+?)"><h2><span>(.+?)<\/span>' else: patron_cat = '<li><a href=.+?>' patron_cat += str(item.title) patron_cat += '<\/a><div>(.+?)<\/div><\/li>' patron = "<a href='(.+?)'>(.+?)<\/a>" data = scrapertools.find_single_match(data, patron_cat) matches = scrapertools.find_multiple_matches(data, patron) for link, name in matches: if "Novedades" in item.title: url = link title = name.capitalize() else: url = host + link title = name if ":" in title: cad = title.split(":") show = cad[0] else: if "(" in title: cad = title.split("(") if "Super" in title: show = cad[1] show = show.replace(")", "") else: show = cad[0] else: show = title if "&" in show: cad = title.split("xy") show = cad[0] context1=[renumbertools.context(item), autoplay.context] itemlist.append( item.clone(title=title, url=url, plot=show, action="episodios", show=show, context=context1)) tmdb.set_infoLabels(itemlist) return itemlist def episodios(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;", "", data) patron = '<div class="pagina">(.+?)<\/div><div id="fade".+?>' data = scrapertools.find_single_match(data, patron) patron_caps = "<a href='(.+?)'>Capitulo: (.+?) - (.+?)<\/a>" matches = scrapertools.find_multiple_matches(data, patron_caps) show = scrapertools.find_single_match(data, '<span>Titulo.+?<\/span>(.+?)<br><span>') scrapedthumbnail = scrapertools.find_single_match(data, "<img src='(.+?)'.+?>") scrapedplot = scrapertools.find_single_match(data, '<span>Descripcion.+?<\/span>(.+?)<br>') i = 0 temp = 0 for link, cap, name in matches: if int(cap) == 1: temp = temp + 1 if int(cap) < 10: cap = "0" + cap season = temp episode = int(cap) season, episode = renumbertools.numbered_for_tratk( item.channel, item.show, season, episode) date = name title = "%sx%s %s (%s)" % (season, str(episode).zfill(2), "Episodio %s" % episode, date) # title = str(temp)+"x"+cap+" "+name url = host + "/" + link if "NO DISPONIBLE" not in name: itemlist.append(Item(channel=item.channel, action="findvideos", title=title, thumbnail=scrapedthumbnail, plot=scrapedplot, url=url, show=show)) if config.get_videolibrary_support() and len(itemlist) > 0: itemlist.append(Item(channel=item.channel, title="Añadir esta serie a la videoteca", url=item.url, action="add_serie_to_library", extra="episodios", show=show)) return itemlist def findvideos(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data data1 = re.sub(r"\n|\r|\t|\s{2}|&nbsp;", "", data) data_vid = scrapertools.find_single_match(data1, '<div class="videos">(.+?)<\/div><div .+?>') # name = scrapertools.find_single_match(data,'<span>Titulo.+?<\/span>([^<]+)<br>') scrapedplot = scrapertools.find_single_match(data, '<br><span>Descrip.+?<\/span>([^<]+)<br>') scrapedthumbnail = scrapertools.find_single_match(data, '<div class="caracteristicas"><img src="([^<]+)">') itemla = scrapertools.find_multiple_matches(data_vid, '<div class="serv">.+?-(.+?)-(.+?)<\/div><.+? src="(.+?)"') for server, quality, url in itemla: if "Calidad Alta" in quality: quality = quality.replace("Calidad Alta", "HQ") server = server.lower().strip() if "ok" == server: server = 'okru' if "netu" == server: continue itemlist.append(item.clone(url=url, action="play", server=server, contentQuality=quality, thumbnail=scrapedthumbnail, plot=scrapedplot, title="Enlace encontrado en %s: [%s]" % (server.capitalize(), quality))) autoplay.start(itemlist, item) return itemlist def play(item): logger.info() itemlist = [] # Buscamos video por servidor ... devuelve = servertools.findvideosbyserver(item.url, item.server) if not devuelve: # ...sino lo encontramos buscamos en todos los servidores disponibles devuelve = servertools.findvideos(item.url, skip=True) if devuelve: # logger.debug(devuelve) itemlist.append(Item(channel=item.channel, title=item.contentTitle, action="play", server=devuelve[0][2], url=devuelve[0][1], thumbnail=item.thumbnail)) return itemlist
pitunti/alfaPitunti
plugin.video.alfa/channels/anitoonstv.py
Python
gpl-3.0
6,699
<?php /** * Copyright Intermesh * * This file is part of Group-Office. You should have received a copy of the * Group-Office license along with Group-Office. See the file /LICENSE.TXT * * If you have questions write an e-mail to info@intermesh.nl * * @copyright Copyright Intermesh * @author Wilmar van Beusekom <wilmar@intermesh.nl> * @property int $errors * @property int $sent * @property int $total * @property int $status * @property int $alias_id * @property int $addresslist_id * @property int $ctime * @property string $message_path * @property string $subject * @property int $user_id * @property int $id * @property int $opened * @property int $campaign_id * @property int $campaign_status_id * @property string $temp_pass The temporary password for sending newsletters * * @property \GO\Base\Fs\File $logFile * @property \GO\Base\Fs\File $messageFile */ namespace GO\Addressbook\Model; class SentMailing extends \GO\Base\Db\ActiveRecord { const STATUS_RUNNING=1; const STATUS_FINISHED=2; const STATUS_PAUSED=3; const STATUS_WAIT_PAUSED=4; /** * Returns a static model of itself * * @param String $className * @return Addressbook */ public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return 'ab_sent_mailings'; } public function relations() { return array( 'addresslist' => array('type' => self::BELONGS_TO, 'model' => 'GO\Addressbook\Model\Addresslist', 'field' => 'addresslist_id'), 'campaign' => array('type' => self::BELONGS_TO, 'model' => 'GO\Campaigns\Model\Campaign', 'field' => 'campaign_id'), 'contacts' => array('type'=>self::MANY_MANY, 'model'=>'GO\Addressbook\Model\Contact', 'field'=>'sent_mailing_id', 'linkModel' => 'GO\Addressbook\Model\SentMailingContact'), 'companies' => array('type'=>self::MANY_MANY, 'model'=>'GO\Addressbook\Model\Company', 'field'=>'sent_mailing_id', 'linkModel' => 'GO\Addressbook\Model\SentMailingCompany') ); } public function aclField(){ return 'addresslist.acl_id'; } protected function afterSave($wasNew) { $campaignModel = $this->campaign; if (!empty($campaignModel)) { $sentAdd = $this->isModified('sent') ? $this->sent - $this->getOldAttributeValue('sent') : 0; $errorAdd = $this->isModified('errors') ? $this->errors - $this->getOldAttributeValue('errors') : 0; $totalAdd = $this->isModified('total') ? $this->total - $this->getOldAttributeValue('total') : 0; $openedAdd = $this->isModified('opened') ? $this->opened - $this->getOldAttributeValue('opened') : 0; if ($sentAdd!=0 || $errorAdd!=0 || $totalAdd!=0 || $openedAdd!=0) { $campaignModel->n_sent += $sentAdd; $campaignModel->n_send_errors += $errorAdd; $campaignModel->n_total += $totalAdd; $campaignModel->n_opened += $openedAdd; $campaignModel->save(); } } return parent::afterSave($wasNew); } /** * Clears or initializes the sending status of the mailing. */ public function reset() { $nMailsToSend = 0; // Clear list of company recipients to send to, if there are any in this list $this->removeAllManyMany('companies'); // Add company recipients to this list and count them $stmt = Addresslist::model()->findByPk($this->addresslist_id)->companies(); while ($company = $stmt->fetch()) { $this->addManyMany('companies', $company->id); $nMailsToSend++; } // Clear list of contact recipients to send to, if there are any in this list $this->removeAllManyMany('contacts'); // Add contact recipients to this list and count them $stmt = Addresslist::model()->findByPk($this->addresslist_id)->contacts(); while ($contact = $stmt->fetch()) { $this->addManyMany('contacts', $contact->id); $nMailsToSend++; } $this->setAttributes( array( "status" => self::STATUS_RUNNING, "total" => $nMailsToSend ) ); $this->save(); } protected function getLogFile(){ $file = new \GO\Base\Fs\File(\GO::config()->file_storage_path.'log/mailings/'.$this->id.'.log'); return $file; } protected function getMessageFile(){ $file = new \GO\Base\Fs\File(\GO::config()->file_storage_path.$this->message_path); return $file; } protected function beforeDelete() { if($this->status==self::STATUS_RUNNING) throw new \Exception("Can't delete a running mailing. Pause it first."); return parent::beforeDelete(); } protected function afterDelete() { $this->logFile->delete(); $this->messageFile->delete(); $this->removeAllManyMany('contacts'); $this->removeAllManyMany('companies'); $campaignModel = $this->campaign; if (!empty($campaignModel)) { $campaignModel->n_sent -= $this->sent; $campaignModel->n_send_errors -= $this->errors; $campaignModel->n_total -= $this->total; $campaignModel->n_opened -= $this->opened; $campaignModel->save(); } return parent::afterDelete(); } }
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.2/groupoffice-6.2-setup-www/modules/addressbook/model/SentMailing.php
PHP
gpl-3.0
4,949
Ext.define('Zenws.zenws.shared.com.zen.viewmodel.location.LanguageViewModel', { "extend": "Ext.app.ViewModel", "alias": "viewmodel.LanguageViewModel", "model": "LanguageModel", "data": {} });
applifireAlgo/ZenClubApp
zenws/src/main/webapp/app/zenws/shared/com/zen/viewmodel/location/LanguageViewModel.js
JavaScript
gpl-3.0
211
class CreateGames < ActiveRecord::Migration def up create_table :games do |t| t.string :name t.datetime :date t.string :round t.timestamps end end def down drop_table :games end end
antoniobg/Las-Notas-de-Brasil-2014
db/migrate/20140611172911_create_games.rb
Ruby
gpl-3.0
228
#!/usr/bin/env python3 import argparse import logging import string # Quiet scapy logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy import volatile # noqa: E402 from scapy import sendrecv # noqa: E402 from scapy import config # noqa: E402 from scapy.layers import l2 # noqa: E402 from scapy.layers import inet # noqa: E402 from scapy.layers import dhcp # noqa: E402 # Configuration requires these imports to properly initialize from scapy import route # noqa: E402, F401 from scapy import route6 # noqa: E402, F401 def dhcp_flood(**kwargs): iface = kwargs["interface"] count = kwargs["count"] unique_hexdigits = str.encode("".join(set(string.hexdigits.lower()))) packet = ( l2.Ether(dst="ff:ff:ff:ff:ff:ff") / inet.IP(src="0.0.0.0", dst="255.255.255.255") / inet.UDP(sport=68, dport=67) / dhcp.BOOTP(chaddr=volatile.RandString(12, unique_hexdigits)) / dhcp.DHCP(options=[("message-type", "discover"), "end"]) ) sendrecv.sendp( packet, iface=iface, count=count ) def print_dhcp_response(response): print("Source: {}".format(response[l2.Ether].src)) print("Destination: {}".format(response[l2.Ether].dst)) for option in response[dhcp.DHCP].options: if isinstance(option, tuple): option, *values = option else: # For some reason some options are strings instead of tuples option, *values = option, None if option in ["end", "pad"]: break output = "Option: {} -> {}".format(option, values) if option == "message-type" and len(values) == 1: dhcp_type = dhcp.DHCPTypes.get(values[0], "unknown") output = "{} ({})".format(output, dhcp_type) print(output) def dhcp_sniff(**kwargs): sendrecv.sniff(filter="udp and (port 67 or 68)", prn=print_dhcp_response) def parse_args(): p = argparse.ArgumentParser(description=''' All your IPs are belong to us. ''', formatter_class=argparse.RawTextHelpFormatter) p.add_argument( '-i', '--interface', action='store', default=config.conf.iface, help='network interface to use' ) subparsers = p.add_subparsers(dest='command') subparsers.required = True flood = subparsers.add_parser('flood') flood.add_argument( '-c', '--count', action='store', default=10, type=int, help='number of addresses to consume' ) subparsers.add_parser('sniff') args = p.parse_args() return args def main(): args = parse_args() dispatch = { "flood": dhcp_flood, "sniff": dhcp_sniff, } dispatch[args.command](**vars(args)) if __name__ == "__main__": main()
mschwager/dhcpwn
dhcpwn.py
Python
gpl-3.0
2,829
/* Flexiport * * Header file for some types that are not defined on Windows. * * Copyright 2008-2011 Geoffrey Biggs geoffrey.biggs@aist.go.jp * RT-Synthesis Research Group * Intelligent Systems Research Institute, * National Institute of Advanced Industrial Science and Technology (AIST), * Japan * All rights reserved. * * This file is part of Flexiport. * * Flexiport 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. * * Flexiport 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 Flexiport. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef __FLEXIPORT_TYPES_H #define __FLEXIPORT_TYPES_H #if defined (WIN32) typedef unsigned char uint8_t; typedef unsigned int uint32_t; #if defined (_WIN64) typedef __int64 ssize_t; #else typedef _W64 int ssize_t; #endif #else #include <stdint.h> #include <sys/types.h> #endif #endif // __FLEXIPORT_TYPES_H
gbiggs/flexiport
include/flexiport/flexiport_types.h
C
gpl-3.0
1,465
/** ****************************************************************************** * * @file uploaderplugin.cpp * @author dRonin, http://dRonin.org/, Copyright (C) 2015 * @author Tau Labs, http://taulabs.org, Copyright (C) 2014 * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup Uploader Uploader Plugin * @{ * @brief The Tau Labs uploader plugin *****************************************************************************/ /* * 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, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "uploaderplugin.h" #include "uploadergadgetfactory.h" #include <QtPlugin> #include <QStringList> #include <extensionsystem/pluginmanager.h> #include <QTest> UploaderPlugin::UploaderPlugin() { // Do nothing } UploaderPlugin::~UploaderPlugin() { // Do nothing } bool UploaderPlugin::initialize(const QStringList& args, QString *errMsg) { Q_UNUSED(args); Q_UNUSED(errMsg); mf = new UploaderGadgetFactory(this); addAutoReleasedObject(mf); return true; } void UploaderPlugin::extensionsInitialized() { // Do nothing } void UploaderPlugin::shutdown() { // Do nothing } void UploaderPlugin::testStuff() { QCOMPARE(QString("hello").toUpper(), QString("HELLO")); QCOMPARE(mf->isAutoUpdateCapable(), true); }
droidicus/dRonin
ground/gcs/src/plugins/uploader/uploaderplugin.cpp
C++
gpl-3.0
1,990
package de.dumischbaenger.ws; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für CalendarPermissionReadAccessType. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * <p> * <pre> * &lt;simpleType name="CalendarPermissionReadAccessType"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="None"/&gt; * &lt;enumeration value="TimeOnly"/&gt; * &lt;enumeration value="TimeAndSubjectAndLocation"/&gt; * &lt;enumeration value="FullDetails"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "CalendarPermissionReadAccessType") @XmlEnum public enum CalendarPermissionReadAccessType { @XmlEnumValue("None") NONE("None"), @XmlEnumValue("TimeOnly") TIME_ONLY("TimeOnly"), @XmlEnumValue("TimeAndSubjectAndLocation") TIME_AND_SUBJECT_AND_LOCATION("TimeAndSubjectAndLocation"), @XmlEnumValue("FullDetails") FULL_DETAILS("FullDetails"); private final String value; CalendarPermissionReadAccessType(String v) { value = v; } public String value() { return value; } public static CalendarPermissionReadAccessType fromValue(String v) { for (CalendarPermissionReadAccessType c: CalendarPermissionReadAccessType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
dumischbaenger/ews-example
src/main/java/de/dumischbaenger/ws/CalendarPermissionReadAccessType.java
Java
gpl-3.0
1,607
<?php namespace CoasterCms; use Auth; use CoasterCms\Events\Cms\LoadAuth; use CoasterCms\Events\Cms\LoadMiddleware; use CoasterCms\Events\Cms\SetViewPaths; use CoasterCms\Http\Middleware\AdminAuth; use CoasterCms\Http\Middleware\GuestAuth; use CoasterCms\Http\Middleware\SecureUpload; use CoasterCms\Http\Middleware\UploadChecks; use CoasterCms\Libraries\Builder\FormMessage; use Illuminate\Foundation\Http\Kernel; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; use Illuminate\Foundation\AliasLoader; class CmsServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @param Router $router * @param Kernel $kernel * @return void */ public function boot(Router $router, Kernel $kernel) { // add router middleware $globalMiddleware = [ UploadChecks::class ]; $routerMiddleware = [ 'coaster.cms' => [], 'coaster.admin' => [AdminAuth::class], 'coaster.guest' => [GuestAuth::class], 'coaster.secure_upload' => [SecureUpload::class], ]; event(new LoadMiddleware($globalMiddleware, $routerMiddleware)); foreach ($globalMiddleware as $globalMiddlewareClass) { $kernel->pushMiddleware($globalMiddlewareClass); } foreach ($routerMiddleware as $routerMiddlewareName => $routerMiddlewareClass) { $router->middlewareGroup($routerMiddlewareName, $routerMiddlewareClass); } // use coater guard and user provider $authGuard = Helpers\Cms\CoasterGuard::class; $authUserProvider = Providers\CoasterAuthUserProvider::class; event(new LoadAuth($authGuard, $authUserProvider)); if ($authGuard && $authUserProvider) { Auth::extend('coaster', function ($app) use ($authGuard, $authUserProvider) { $guard = new $authGuard( 'coasterguard', new $authUserProvider($app['hash'], config('auth.providers.users.model')), $app['session.store'], $app['request'] ); // set cookie jar for cookies if (method_exists($guard, 'setCookieJar')) { $guard->setCookieJar($this->app['cookie']); } if (method_exists($guard, 'setDispatcher')) { $guard->setDispatcher($this->app['events']); } if (method_exists($guard, 'setRequest')) { $guard->setRequest($this->app->refresh('request', $guard, 'setRequest')); } return $guard; }); } // load coaster views $adminViews = [ rtrim(config('coaster::admin.view'), '/') ]; $frontendViews = [ rtrim(config('coaster::frontend.view'), '/') ]; event(new SetViewPaths($adminViews, $frontendViews)); $this->loadViewsFrom($adminViews, 'coaster'); $this->loadViewsFrom($frontendViews, 'coasterCms'); $this->app->singleton('formMessage', function () { return new FormMessage($this->app['session'], 'default', config('coaster::frontend.form_error_class')); }); } /** * Register the service provider. * * @return void */ public function register() { if (!defined('COASTER_ROOT')) { define('COASTER_ROOT', dirname(__DIR__)); } $this->app->register('CoasterCms\Providers\CoasterEventsProvider'); $this->app->register('CoasterCms\Providers\CoasterConfigProvider'); $this->app->register('CoasterCms\Providers\CoasterConsoleProvider'); $this->app->register('CoasterCms\Providers\CoasterPageBuilderProvider'); // register third party providers $this->app->register('Bkwld\Croppa\ServiceProvider'); $this->app->register('Collective\Html\HtmlServiceProvider'); // register aliases $loader = AliasLoader::getInstance(); $loader->alias('Form', 'Collective\Html\FormFacade'); $loader->alias('HTML', 'Collective\Html\HtmlFacade'); $loader->alias('Croppa', 'CoasterCms\Helpers\Cms\Croppa\CroppaFacade'); $loader->alias('CmsBlockInput', 'CoasterCms\Helpers\Cms\View\CmsBlockInput'); $loader->alias('FormMessage', 'CoasterCms\Facades\FormMessage'); $loader->alias('AssetBuilder', 'CoasterCms\Libraries\Builder\AssetBuilder'); $loader->alias('DateTimeHelper', 'CoasterCms\Helpers\Cms\DateTimeHelper'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ 'CoasterCms\Providers\CoasterConfigProvider', 'CoasterCms\Providers\CoasterEventsProvider', 'CoasterCms\Providers\CoasterConsoleProvider', 'CoasterCms\Providers\CoasterPageBuilderProvider', 'Bkwld\Croppa\ServiceProvider', 'Collective\Html\HtmlServiceProvider' ]; } }
Web-Feet/coasterframework
src/CmsServiceProvider.php
PHP
gpl-3.0
5,256
<!DOCTYPE html> <html lang="en"> <head> <style type="text/css" media="screen"> #adjust { display: block; margin: 0 auto; width: 940px; height: 470px; position: relative; overflow: hidden; clear: both; } #column { text-align: left; width: 120px; } #header { align: top; } </style> </head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css"> <body> <div class="jumbotron"> <div id="adjust"> <div class="card"> <div class="header" id=header style="text-align:center;"> <table class="table"> <tr> <td id=c olumn> <div class="image"> <a href="{% url 'landing_home'%}"> <img src="/static/logo/hugo1.png" width="230px" height="265px"></img> <!-- <img src="/static/logo/logo.png" width="205px" height="115px"></img> --> </a> </td> <td> <p> <h2 class="title"><b>Oops!</b> 404</h2></p> <p>Não foi possível entrar essa página</p> <p>Verifique se a url foi digitada corretamente. A página pode ter sido removida ou não existe.</p> </td> <td></td> <td></td> </tr> </table> </div> </div> <div class="card"> <div class="content "> <table class="table"> <tr> <td id=c olumn> <p> <center> <a href="{% url 'landing_home'%}"> <button class="btn btn-outline-success" type="button">Página inicial</button></a> </center> </td> </tr> </table> </div> </div> </div> </div> </div> </body> </html>
CodaMais/CodaMais
CodaMais/templates/404.html
HTML
gpl-3.0
2,179
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Fri Oct 31 17:29:00 EST 2014 --> <title>Uses of Class org.grants.google.cse.UrlTemplate</title> <meta name="date" content="2014-10-31"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.grants.google.cse.UrlTemplate"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../org/grants/google/cse/package-summary.html">Package</a></li> <li><a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/grants/google/cse/class-use/UrlTemplate.html" target="_top">Frames</a></li> <li><a href="UrlTemplate.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.grants.google.cse.UrlTemplate" class="title">Uses of Class<br>org.grants.google.cse.UrlTemplate</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.grants.google.cse"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">UrlTemplate</a> in <a href="../../../../../org/grants/google/cse/package-summary.html">org.grants.google.cse</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/grants/google/cse/package-summary.html">org.grants.google.cse</a> that return <a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">UrlTemplate</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">UrlTemplate</a></code></td> <td class="colLast"><span class="strong">QueryResponse.</span><code><strong><a href="../../../../../org/grants/google/cse/QueryResponse.html#getUrl()">getUrl</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/grants/google/cse/package-summary.html">org.grants.google.cse</a> with parameters of type <a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">UrlTemplate</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">QueryResponse.</span><code><strong><a href="../../../../../org/grants/google/cse/QueryResponse.html#setUrl(org.grants.google.cse.UrlTemplate)">setUrl</a></strong>(<a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">UrlTemplate</a>&nbsp;url)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../org/grants/google/cse/package-summary.html">Package</a></li> <li><a href="../../../../../org/grants/google/cse/UrlTemplate.html" title="class in org.grants.google.cse">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/grants/google/cse/class-use/UrlTemplate.html" target="_top">Frames</a></li> <li><a href="UrlTemplate.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
rd-switchboard/Inference
Libraries/Google/google_cse/doc/org/grants/google/cse/class-use/UrlTemplate.html
HTML
gpl-3.0
6,329
MODX Evolution 1.1 = 6c5e02783a79b572e09102b05854077e
gohdan/DFC
known_files/hashes/assets/plugins/tinymce/tiny_mce/plugins/emotions/langs/he_dlg.js
JavaScript
gpl-3.0
54
<?php /*%%SmartyHeaderCode:13655040015825e69b5d2f30-65991127%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '297249cc5985461aca1ee47074b9229d90accf94' => array ( 0 => '/home/koomaakiey/pprod/themes/default-bootstrap/modules/productcomments/productcomments_reviews.tpl', 1 => 1420621556, 2 => 'file', ), ), 'nocache_hash' => '13655040015825e69b5d2f30-65991127', 'version' => 'Smarty-3.1.19', 'unifunc' => 'content_5825e7421d3f99_23877779', 'has_nocache_code' => false, 'cache_lifetime' => 31536000, ),true); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_5825e7421d3f99_23877779')) {function content_5825e7421d3f99_23877779($_smarty_tpl) {?><?php }} ?>
tantchontampo/koomaakiti.com
cache/smarty/cache/productcomments/1/6/8/40/29/72/49/297249cc5985461aca1ee47074b9229d90accf94.productcomments_reviews.tpl.php
PHP
gpl-3.0
819
# pixy_roimux 3D reconstruction for pixelated LArTPCs employing mutliplexing through inductive regions of interest
70rc/pixy_roimux
README.md
Markdown
gpl-3.0
115
package nc.noumea.mairie.model.bean.sirh; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PersistenceUnit; import javax.persistence.Table; import javax.validation.constraints.NotNull; @Entity @Table(name = "ACTIVITE") @PersistenceUnit(unitName = "sirhPersistenceUnit") public class Activite { @Id @Column(name = "ID_ACTIVITE") private Integer idActivite; @NotNull @Column(name = "NOM_ACTIVITE") private String nomActivite; public Integer getIdActivite() { return idActivite; } public void setIdActivite(Integer idActivite) { this.idActivite = idActivite; } public String getNomActivite() { return nomActivite; } public void setNomActivite(String nomActivite) { this.nomActivite = nomActivite; } }
DSI-Ville-Noumea/sirh-ws
src/main/java/nc/noumea/mairie/model/bean/sirh/Activite.java
Java
gpl-3.0
799
-- MySQL dump 10.13 Distrib 5.5.44, for debian-linux-gnu (armv7l) -- -- Host: localhost Database: monitor -- ------------------------------------------------------ -- Server version 5.5.44-0+deb8u1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `sensor_alarms` -- DROP TABLE IF EXISTS `sensor_alarms`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sensor_alarms` ( `id` int(11) NOT NULL AUTO_INCREMENT, `sensor` varchar(50) NOT NULL, `alarm_type` enum('min','max') DEFAULT NULL, `alarm_value` float DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `sensor_data` -- DROP TABLE IF EXISTS `sensor_data`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sensor_data` ( `sensor` varchar(50) NOT NULL DEFAULT '', `value` float DEFAULT NULL, `date_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`sensor`,`date_time`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `sensors` -- DROP TABLE IF EXISTS `sensors`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sensors` ( `sensor` varchar(50) NOT NULL DEFAULT '', `name` varchar(50) DEFAULT NULL, `thingspeak_field` smallint(5) unsigned DEFAULT NULL, PRIMARY KEY (`sensor`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `thingspeak_config` -- DROP TABLE IF EXISTS `thingspeak_config`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `thingspeak_config` ( `write_key` varchar(200) DEFAULT NULL, `read_key` varchar(200) DEFAULT NULL, `channel` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `users` ( `id` mediumint(9) NOT NULL AUTO_INCREMENT, `username` varchar(30) NOT NULL, `password` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2016-03-19 1:03:10
dorgan/home-monitor
src/database.sql
SQL
gpl-3.0
3,662
/* radare - LGPL - Copyright 2007-2015 - pancake */ #include "r_types.h" #include "r_util.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdarg.h> /* stable code */ static const char *nullstr = ""; static const char *nullstr_c = "(null)"; // TODO: simplify this horrible loop R_API void r_str_chop_path (char *s) { char *src, *dst, *p; int i = 0; if (!s || !*s) return; dst = src = s+1; while (*src) { if (*(src-1) == '/' && *src == '.' && *(src+1) == '.') { if (*(src+2) == '/' || *(src+2) == '\0') { p = dst-1; while (s != p) { if (*p == '/') { if (i) { dst = p+1; i = 0; break; } i = 1; } p--; } if (s == p && *p == '/') dst = p+1; src = src+2; } else { *dst = *src; dst++; } } else if (*src == '/' && *(src+1) == '.' && (*(src+2) == '/' || *(src+2) == '\0')) { src++; } else if (*src != '/' || *(src-1) != '/') { *dst = *src; dst++; } src++; } if (dst>s+1 && *(dst-1) == '/') *(dst-1) = 0; else *dst = 0; } R_API int r_str_replace_char_once (char *s, int a, int b) { int ret = 0; char *o = s; if (a==b) return 0; for (; *o; s++, o++) { if (*o==a) { if (b) { *s = b; ret++; continue; } o++; } *s = *o; } *s = 0; return ret; } // Spagetti.. must unify and support 'g', 'i' ... R_API int r_str_replace_char (char *s, int a, int b) { int ret = 0; char *o = s; if (a==b) return 0; for (; *o; s++, o++) { if (*o==a) { ret++; if (b) { *s = b; } else { /* remove char */ s--; } } else *s = *o; } *s = 0; return ret; } // TODO: do not use toupper.. must support modes to also append lowercase chars like in r1 // TODO: this functions needs some stabilization R_API int r_str_bits (char *strout, const ut8 *buf, int len, const char *bitz) { int i, j; if (bitz) { for (i=j=0; i<len && (!bitz||bitz[i]); i++) { if (i>0 && (i%8)==0) buf++; if (*buf&(1<<(i%8))) strout[j++] = toupper ((const unsigned char)bitz[i]); } } else { for (i=j=0; i<len; i++) { if (i>0 && (i%8)==0) buf++; strout[j++] = (*buf&(1<<(7-(i%8))))?'1':'0'; } } strout[j] = 0; return j; } /** * function: r_str_bits_from_num * */ R_API ut64 r_str_bits_from_string(const char *buf, const char *bitz) { ut64 out = 0LL; /* return the numberic value associated to a string (rflags) */ for (; *buf; buf++) { char *ch = strchr (bitz, toupper ((const unsigned char)*buf)); if (!ch) ch = strchr (bitz, tolower ((const unsigned char)*buf)); if (ch) { int bit = (int)(size_t)(ch - bitz); out |= (ut64)(1LL << bit); } else { return UT64_MAX; } } return out; } /* int c; ret = hex2int(&c, 'c'); */ static int hex2int (ut8 *val, ut8 c) { if ('0' <= c && c <= '9') *val = (ut8)(*val) * 16 + ( c - '0'); else if (c >= 'A' && c <= 'F') *val = (ut8)(*val) * 16 + ( c - 'A' + 10); else if (c >= 'a' && c <= 'f') *val = (ut8)(*val) * 16 + ( c - 'a' + 10); else return 1; return 0; } R_API int r_str_binstr2bin(const char *str, ut8 *out, int outlen) { int n, i, j, k, ret, len; len = strlen (str); for (n=i=0; i<len; i+=8) { ret = 0; while (str[i]==' ') str++; if (i+7<len) for (k=0, j=i+7; j>=i; j--, k++) { // INVERSE for (k=0,j=i; j<i+8; j++,k++) { if (str[j]==' ') { //k--; continue; } // printf ("---> j=%d (%c) (%02x)\n", j, str[j], str[j]); if (str[j]=='1') ret|=1<<k; else if (str[j]!='0') return n; } // printf ("-======> %02x\n", ret); out[n++] = ret; if (n==outlen) return n; } return n; } R_API int r_str_rwx(const char *str) { int ret = atoi (str); if (!ret) { ret |= strchr (str, 'r')?4:0; ret |= strchr (str, 'w')?2:0; ret |= strchr (str, 'x')?1:0; } return ret; } R_API const char *r_str_rwx_i(int rwx) { static const char *rwxstr[16] = { [0] = "---", [1] = "--x", [2] = "-w-", [3] = "-wx", [4] = "r--", [5] = "r-x", [6] = "rw-", [7] = "rwx", /* ... */ }; return rwxstr[rwx&7]; // 15 for srwx } R_API const char *r_str_bool(int b) { return b? "true": "false"; } R_API void r_str_case(char *str, int up) { if (up) { char oc = 0; for (; *str; oc = *str++) *str = (*str=='x' && oc=='0') ? 'x': toupper ((unsigned char)*str); } else for (; *str; str++) *str = tolower ((unsigned char)*str); } R_API char *r_str_home(const char *str) { char *dst, *home = r_sys_getenv (R_SYS_HOME); size_t length; if (home == NULL) return NULL; length = strlen (home) + 1; if (str) length += strlen (R_SYS_DIR) + strlen (str); dst = (char *)malloc (length); if (dst == NULL) goto fail; strcpy (dst, home); if (str) { strcat (dst, R_SYS_DIR); strcat (dst, str); } fail: free (home); return dst; } R_API ut64 r_str_hash64(const char *s) { ut64 len, h = 5381; if (!s) return 0; for (len=strlen (s); len>0; len--) h = (h^(h<<5)) ^ *s++; return h; } R_API ut32 r_str_hash (const char *s) { return (ut32) r_str_hash64 (s); } R_API int r_str_delta(char *p, char a, char b) { char *_a = strchr (p, a); char *_b = strchr (p, b); return (!_a||!_b)?0:(_a-_b); } R_API int r_str_split(char *str, char ch) { int i; char *p; if (!str || !*str) return 0; /* TODO: sync with r1 code */ for (i=1, p=str; *p; p++) if (*p==ch) { i++; *p='\0'; } // s/ /\0/g return i; } R_API int r_str_word_set0(char *str) { int i, quote = 0; char *p; if (!str || !*str) return 0; for (i=0; str[i] && str[i+1]; i++) { if (str[i]==' ' && str[i+1]==' ') { int len = strlen (str+i+1)+1; memmove (str+i, str+i+1, len); } } if (str[i]==' ') str[i] = 0; for (i=1, p=str; *p; p++) { if (*p=='\"') { if (quote) { quote = 0; *p = '\0'; // FIX: i++; continue; } else { quote = 1; memmove (p, p+1, strlen (p+1)+1); } } if (quote) continue; if (*p==' ') { char *q = p-1; if (p>str && *q=='\\') { memmove (q, p, strlen (p)+1); continue; } i++; *p='\0'; } // s/ /\0/g } return i; } R_API char *r_str_word_get0set(char *stra, int stralen, int idx, const char *newstr, int *newlen) { char *p = NULL; char *out; int alen, blen, nlen; if (!stra && !newstr) return NULL; if (stra) p = (char *)r_str_word_get0 (stra, idx); if (!p) { int nslen = strlen (newstr); out = malloc (nslen+1); strcpy (out, newstr); out[nslen] = 0; if (newlen) *newlen = nslen; return out; } alen = (size_t)(p-stra); blen = stralen - ((alen + strlen (p))+1); if (blen<0) blen = 0; nlen = alen+blen+strlen (newstr); out = malloc (nlen + 2); if (alen>0) memcpy (out, stra, alen); memcpy (out+alen, newstr, strlen (newstr)+1); if (blen>0) memcpy (out+alen+strlen (newstr)+1, p+strlen (p)+1, blen+1); out[nlen+1] = 0; if (newlen) *newlen = nlen + ((blen==0)?1:0); return out; } R_API const char *r_str_word_get0(const char *str, int idx) { int i; const char *ptr = str; if (ptr == NULL) return (char *)nullstr; for (i=0; *ptr && i != idx; i++) ptr += strlen (ptr) + 1; return ptr; } R_API int r_str_char_count(const char *string, char ch) { int i, count = 0; for (i=0; string[i]; i++) if (string[i]==ch) count++; return count; } R_API int r_str_word_count(const char *string) { const char *text, *tmp; int word; for (text = tmp = string; *text && isseparator (*text); text++); for (word = 0; *text; word++) { for (;*text && !isseparator (*text); text++); for (tmp = text; *text && isseparator (*text); text++); } return word; } R_API char *r_str_ichr(char *str, char chr) { while (*str==chr) str++; return str; } // find last char R_API const char *r_str_lchr(const char *str, char chr) { if (str) { int len = strlen (str); for (;len>=0;len--) if (str[len]==chr) return str+len; } return NULL; } R_API const char *r_str_rchr(const char *base, const char *p, int ch) { if (!base) return NULL; if (!p) p = base + strlen (base); for (; p>base; p--) if (ch == *p) break; return p; } R_API int r_str_nchr(const char *str, char chr) { int n; for (n = 0; *str; str++) if (*str==chr) n++; return n; } R_API int r_str_nstr(char *from, char *to, int size) { int i; for (i=0; i<size; i++) if (from==NULL || to==NULL || from[i]!=to[i]) break; return (size!=i); } // TODO: rewrite in macro? R_API const char *r_str_chop_ro(const char *str) { if (str) while (*str && iswhitechar (*str)) str++; return str; } R_API char *r_str_new(const char *str) { if (!str) return NULL; return strdup (str); } R_API char *r_str_newlen(const char *str, int len) { char *buf; if (len<1) return NULL; buf = malloc (len+1); memcpy (buf, str, len); buf[len] = 0; return buf; } R_API char *r_str_newf(const char *fmt, ...) { int ret, ret2; char *p, string[1024]; va_list ap, ap2; va_start (ap, fmt); va_start (ap2, fmt); ret = vsnprintf (string, sizeof (string)-1, fmt, ap); if (ret < 1 || ret >= sizeof (string)) { p = malloc (ret+2); if (!p) { va_end (ap2); va_end (ap); return NULL; } ret2 = vsnprintf (p, ret+1, fmt, ap2); if (ret2 < 1 || ret2 > ret+1) { free (p); va_end (ap2); va_end (ap); return NULL; } fmt = r_str_new (p); free (p); } else { fmt = r_str_new (string); } va_end (ap2); va_end (ap); return (char*)fmt; } R_API char *r_str_chop(char *str) { int len; char *ptr; if (str == NULL) return NULL; while (*str && iswhitechar (*str)) memmove (str, str+1, strlen (str+1)+1); len = strlen (str); if (len>0) for (ptr = str+len-1; ptr!=str; ptr--) { if (iswhitechar (*ptr)) *ptr = '\0'; else break; } return str; } R_API const char *r_str_trim_const(const char *str) { if (str) for (; *str && iswhitechar (*str); str++); return str; } R_API char *r_str_trim_head(char *str) { char *p; if (!str) return NULL; for (p = str; *p && iswhitechar (*p); p++) ; /* Take the trailing null into account */ memmove (str, p, strlen (p) + 1); return str; } R_API char *r_str_trim_tail(char *str) { int length; if (!str) return NULL; length = strlen (str); if (!length) return str; while (length--) { if (iswhitechar (str[length])) str[length] = '\0'; else break; } return str; } R_API char *r_str_trim_head_tail(char *str) { return r_str_trim_tail (r_str_trim_head (str)); } R_API char *r_str_trim(char *str) { int i; char *ptr; if (str == NULL) return NULL; for (ptr=str, i=0;str[i]; i++) if (!iswhitechar (str[i])) *ptr++ = str[i]; *ptr = '\0'; return str; } R_API void r_str_ncpy(char *dst, const char *src, int n) { int i; for (i=0; src[i] && n>0; i++, n--) dst[i] = IS_PRINTABLE (src[i])? src[i]: '.'; dst[i] = 0; } /* memccmp("foo.bar", "foo.cow, '.') == 0 */ R_API int r_str_ccmp(const char *dst, const char *src, int ch) { int i; for (i=0;src[i] && src[i] != ch; i++) if (dst[i] != src[i]) return 1; return 0; } R_API int r_str_cmp(const char *a, const char *b, int len) { if (a==b) return R_TRUE; for (;len--;) { if (*a=='\0'||*b=='\0'||*a!=*b) return R_TRUE; a++; b++; } return R_FALSE; } R_API int r_str_ccpy(char *dst, char *src, int ch) { int i; for (i=0; src[i] && src[i] != ch; i++) dst[i] = src[i]; dst[i] = '\0'; return i; } R_API char *r_str_word_get_first(const char *text) { char *ret; int len = 0; for (;*text && isseparator (*text); text++); /* strdup */ len = strlen (text); ret = (char *)malloc (len+1); if (ret == NULL) { eprintf ("Cannot allocate %d bytes.\n", len+1); exit (1); } strncpy (ret, text, len); ret[len]='\0'; return ret; } R_API const char *r_str_get(const char *str) { if (str == NULL) return nullstr_c; return str; } R_API char *r_str_ndup(const char *ptr, int len) { char *out = malloc (len+1); memcpy (out, ptr, len); out[len] = 0; return out; } // TODO: deprecate? R_API char *r_str_dup(char *ptr, const char *string) { int len; free (ptr); if (!string) return NULL; len = strlen (string)+1; ptr = malloc (len+1); memcpy (ptr, string, len); return ptr; } R_API void r_str_writef(int fd, const char *fmt, ...) { char *buf; va_list ap; va_start (ap, fmt); if ((buf = malloc (4096)) != NULL) { vsnprintf (buf, 4096, fmt, ap); r_str_write (fd, buf); free (buf); } va_end (ap); } R_API char *r_str_prefix(char *ptr, const char *string) { int slen, plen; if (ptr == NULL) return strdup (string); //plen = r_str_len_utf8 (ptr); //slen = r_str_len_utf8 (string); plen = strlen (ptr); slen = strlen (string); ptr = realloc (ptr, slen + plen + 1); if (ptr == NULL) return NULL; memmove (ptr+slen, ptr, plen+1); memmove (ptr, string, slen); return ptr; } R_API char *r_str_concatlen(char *ptr, const char *string, int slen) { char *ret, *msg = r_str_newlen (string, slen); ret = r_str_concat (ptr, msg); free (msg); return ret; } /* * first argument must be allocated * return: the pointer ptr resized to string size. */ // TODO: use vararg here? R_API char *r_str_concat(char *ptr, const char *string) { int slen, plen; if (!string && !ptr) return NULL; if (!string && ptr) return ptr; if (string && !ptr) return strdup (string); plen = strlen (ptr); slen = strlen (string); ptr = realloc (ptr, slen + plen + 1); if (ptr == NULL) return NULL; memcpy (ptr+plen, string, slen+1); return ptr; } R_API char *r_str_concatf(char *ptr, const char *fmt, ...) { int ret; char string[4096]; va_list ap; va_start (ap, fmt); ret = vsnprintf (string, sizeof (string), fmt, ap); if (ret>=sizeof (string)) { char *p = malloc (ret+2); if (!p) { va_end (ap); return NULL; } vsnprintf (p, ret+1, fmt, ap); ptr = r_str_concat (ptr, p); free (p); } else ptr = r_str_concat (ptr, string); va_end (ap); return ptr; } R_API char *r_str_concatch(char *x, char y) { char b[2] = {y, 0}; return r_str_concat (x,b); } // XXX: wtf must deprecate R_API void *r_str_free(void *ptr) { free (ptr); return NULL; } R_API char* r_str_replace(char *str, const char *key, const char *val, int g) { int off, i, klen, vlen, slen; char *newstr, *scnd, *p = str; if (!str || !key || !val) return NULL; klen = strlen (key); vlen = strlen (val); if (klen == vlen && !strcmp (key, val)) return str; slen = strlen (str); for (i = 0; i < slen; ) { p = (char *)r_mem_mem ( (const ut8*)str + i, slen - i, (const ut8*)key, klen); if (!p) break; off = (int)(size_t)(p-str); scnd = strdup (p+klen); slen += vlen - klen; // HACK: this 32 avoids overwrites wtf newstr = realloc (str, slen+klen+1); if (!newstr) { eprintf ("realloc fail\n"); free (str); free (scnd); str = NULL; break; } str = newstr; p = str+off; memcpy (p, val, vlen); memcpy (p+vlen, scnd, strlen (scnd)+1); i = off+vlen; free (scnd); if (!g) break; } return str; } R_API char *r_str_clean(char *str) { int len; char *ptr; if (str != NULL) { while (*str && iswhitechar (*str)) str++; if ((len = strlen (str)) > 0 ) for (ptr = str+len-1; ptr!=str; ptr = ptr - 1) { if (iswhitechar (*ptr)) *ptr = '\0'; else break; } } return str; } R_API int r_str_unescape(char *buf) { unsigned char ch = 0, ch2 = 0; int err = 0; int i; for (i=0; buf[i]; i++) { if (buf[i]!='\\') continue; if (buf[i+1]=='e') { buf[i] = 0x1b; memmove (buf+i+1, buf+i+2, strlen (buf+i+2)+1); } else if (buf[i+1]=='r') { buf[i] = 0x0d; memmove (buf+i+1, buf+i+2, strlen (buf+i+2)+1); } else if (buf[i+1]=='n') { buf[i] = 0x0a; memmove (buf+i+1, buf+i+2, strlen (buf+i+2)+1); } else if (buf[i+1]=='x') { err = ch2 = ch = 0; if (!buf[i+2] || !buf[i+3]) { eprintf ("Unexpected end of string.\n"); return 0; } err |= hex2int (&ch, buf[i+2]); err |= hex2int (&ch2, buf[i+3]); if (err) { eprintf ("Error: Non-hexadecimal chars in input.\n"); return 0; // -1? } buf[i] = (ch<<4)+ch2; memmove (buf+i+1, buf+i+4, strlen (buf+i+4)+1); } else { eprintf ("'\\x' expected.\n"); return 0; // -1? } } return i; } R_API void r_str_sanitize(char *c) { char *d = c; if (d) for (; *d; c++, d++) { switch (*d) { case '`': case '$': case '{': case '}': case '~': case '|': case ';': case '#': case '@': case '&': case '<': case '>': *c = '_'; continue; } } } /* Internal function. dot_nl specifies wheter to convert \n into the * graphiz-compatible newline \l */ static char *r_str_escape_ (const char *buf, const int dot_nl) { char *new_buf, *q; const char *p; if (!buf) return NULL; /* Worst case scenario, we convert every byte */ new_buf = malloc (1 + (strlen(buf) * 4)); if (!new_buf) return NULL; p = buf; q = new_buf; while (*p) { switch (*p) { case '\n': *q++ = '\\'; *q++ = dot_nl? 'l': 'n'; break; case '\r': *q++ = '\\'; *q++ = 'r'; break; case '\\': *q++ = '\\'; *q++ = '\\'; break; case '\t': *q++ = '\\'; *q++ = 't'; break; case '"' : *q++ = '\\'; *q++ = '"'; break; case '\f': *q++ = '\\'; *q++ = 'f'; break; case '\b': *q++ = '\\'; *q++ = 'b'; break; case 0x1b: // ESC p++; /* Parse the ANSI code (only the graphic mode * set ones are supported) */ if (*p == '[') for (p++; *p != 'm'; p++) ; break; default: /* Outside the ASCII printable range */ if (*p < ' ' && *p > 0x7E) { *q++ = '\\'; *q++ = 'x'; *q++ = '0'+((*p)>>4); *q++ = '0'+((*p)&0xf); } else { *q++ = *p; } } p++; } *q = '\0'; return new_buf; } R_API char *r_str_escape (const char *buf) { return r_str_escape_ (buf, R_FALSE); } R_API char *r_str_escape_dot (const char *buf) { return r_str_escape_ (buf, R_TRUE); } /* ansi helpers */ R_API int r_str_ansi_len(const char *str) { int ch, ch2, i=0, len = 0, sub = 0; while (str[i]) { ch = str[i]; ch2 = str[i+1]; if (ch == 0x1b) { if (ch2 == '\\') { i++; } else if (ch2 == ']') { if (!strncmp (str+2+5, "rgb:", 4)) i += 18; } else if (ch2 == '[') { for (++i; str[i]&&str[i]!='J'&& str[i]!='m'&&str[i]!='H';i++); } } else { len++; #if 0 int olen = strlen (str); int ulen = r_str_len_utf8 (str); if (olen != ulen) { len += (olen-ulen); } else len++; //sub -= (r_str_len_utf8char (str+i, 4))-2; #endif }//len++; i++; } return len-sub; } R_API int r_str_ansi_chop(char *str, int str_len, int n) { /* suposed to chop a string with ansi controls to * max length of n */ char ch, ch2; int back, i = 0, len = 0; /* simple case - no need to cut */ if (n >= str_len){ str[str_len - 1] = 0; return str_len - 1; } while ((i < str_len) && str[i] && (len < n)) { ch = str[i]; ch2 = str[i+1]; back = i; /* index in the original array */ if (ch == 0x1b) { if (ch2 == '\\') { i++; } else if (ch2 == ']') { if (!strncmp (str+2+5, "rgb:", 4)) i += 18; } else if (ch2 == '[') { for (++i; (i < str_len) && str[i] && str[i]!='J' && str[i]!='m' && str[i]!='H'; i++); } } else if ((str[i] & 0xc0) != 0x80) len++; i++; } str[back] = 0; return back; } // TODO: support wide char strings R_API int r_str_nlen(const char *str, int n) { int len = 0; if (str) { //while (IS_PRINTABLE (*str) && n>0) { while (*str && n>0) { len++; str++; n--; } } return len; } // Length in chars of a wide string (find better name?) R_API int r_wstr_clen (const char *s) { int len = 0; if (*s++ == 0) return 0; while (*s++ || *s++) len++; return len+1; } R_API const char *r_str_ansi_chrn(const char *str, int n) { int len, i, li; for (li=i=len=0; str[i] && (n!=len); i++) { if (str[i]==0x1b && str[i+1]=='[') { for (++i;str[i]&&str[i]!='J'&&str[i]!='m'&&str[i]!='H';i++); } else { if ((str[i] & 0xc0) != 0x80) len++; //len++; li = i; } } return str+li; } R_API int r_str_ansi_filter(char *str, int len) { int i, j; char *tmp; if (len<1) len = strlen (str)+1; tmp = malloc (len); if (!tmp) return -1; memcpy (tmp, str, len); for (i=j=0; i<len; i++) if (i+1<len && tmp[i] == 0x1b && tmp[i+1] == '[') for (i+=2;i<len&&str[i]!='J'&&str[i]!='m'&&str[i]!='H';i++); else str[j++] = tmp[i]; free (tmp); return j; } R_API void r_str_filter_zeroline(char *str, int len) { int i; for (i=0; i<len && str[i]; i++) { if (str[i]=='\n' || str[i]=='\r') break; if (!IS_PRINTABLE (str[i])) break; } str[i] = 0; } R_API void r_str_filter(char *str, int len) { int i; if (len<1) len = strlen (str); for (i=0; i<len; i++) if (!IS_PRINTABLE (str[i])) str[i] = '.'; } R_API int r_str_glob (const char *str, const char *glob) { const char *p; int slen, glen; if (!*str) return R_TRUE; glen = strlen (glob); slen = strlen (str); if (*glob == '*') { if (glob[1] == '\0') return R_TRUE; if (glob[glen-1] == '*') { return r_mem_mem ((const ut8*)str, slen, (const ut8*)glob+1, glen-2) != 0; } if (slen<glen-2) return R_FALSE; p = str + slen - (glen-1); return memcmp (p, glob+1, glen-1) == 0; } else { if (glob[glen-1] == '*') { if (slen<glen-1) return R_FALSE; return memcmp (str, glob, glen-1) == 0; } else { char *p = strchr (glob, '*'); if (p) { int a = (int)(size_t)(p-glob); return ((!memcmp (str, glob, a)) && \ (!memcmp (str+slen-a, glob+a+1, glen-a-1)))? 1: 0; } return !strcmp (str, glob); } } return R_FALSE; // statement never reached } // Escape the string arg so that it is parsed as a single argument by r_str_argv R_API char *r_str_arg_escape (const char *arg) { char *str; int dest_i = 0, src_i = 0; if (!arg) return NULL; str = malloc ((2 * strlen (arg) + 1) * sizeof (char)); // Worse case when every character need to be escaped for (src_i = 0; arg[src_i] != '\0'; src_i++) { char c = arg[src_i]; switch (c) { case '\'': case '"': case '\\': case ' ': str[dest_i++] = '\\'; break; default: str[dest_i++] = c; break; } } str[dest_i] = '\0'; return realloc (str, (strlen(str)+1) * sizeof (char)); } R_API char **r_str_argv(const char *cmdline, int *_argc) { int argc = 0; int argv_len = 128; // Begin with that, argv will reallocated if necessary char **argv; char *args; // Working buffer for writing unescaped args int cmdline_current = 0; // Current character index in _cmdline int args_current = 0; // Current character index in args int arg_begin = 0; // Index of the first character of the current argument in args if (!cmdline) return NULL; argv = malloc (argv_len * sizeof (char *)); args = malloc (128 + strlen (cmdline) * sizeof (char)); // Unescaped args will be shorter, so strlen (cmdline) will be enough do { // States for parsing args int escaped = 0; int singlequoted = 0; int doublequoted = 0; // Seek the beginning of next argument (skip whitespaces) while (cmdline[cmdline_current] != '\0' && iswhitechar (cmdline[cmdline_current])) cmdline_current++; if (cmdline[cmdline_current] == '\0') break; // No more arguments // Read the argument while (1) { char c = cmdline[cmdline_current]; int end_of_current_arg = 0; if (escaped) { switch (c) { case '\'': case '"': case ' ': case '\\': args[args_current++] = c; break; case '\0': args[args_current++] = '\\'; end_of_current_arg = 1; break; default: args[args_current++] = '\\'; args[args_current++] = c; } escaped = 0; } else { switch (c) { case '\'': if (doublequoted) args[args_current++] = c; else singlequoted = !singlequoted; break; case '"': if (singlequoted) args[args_current++] = c; else doublequoted = !doublequoted; break; case '\\': escaped = 1; break; case ' ': if (singlequoted || doublequoted) args[args_current++] = c; else end_of_current_arg = 1; break; case '\0': end_of_current_arg = 1; break; default: args[args_current++] = c; } } if (end_of_current_arg) break; cmdline_current++; } args[args_current++] = '\0'; argv[argc++] = strdup (&args[arg_begin]); if (argc >= argv_len) { argv_len *= 2; argv = realloc (argv, argv_len * sizeof (char *)); } arg_begin = args_current; } while (cmdline[cmdline_current++] != '\0'); argv[argc] = NULL; argv = realloc (argv, (argc+1) * sizeof (char *)); if (_argc) *_argc = argc; free (args); return argv; } R_API void r_str_argv_free(char **argv) { // TODO: free the internal food or just the first element // free (argv[0]); // MEMORY LEAK int argc = 0; while (argv[argc]) free (argv[argc++]); free (argv); } R_API const char *r_str_lastbut (const char *s, char ch, const char *but) { int idx, _b = 0; ut8 *b = (ut8*)&_b; const char *isbut, *p, *lp = NULL; const int bsz = sizeof (_b); if (!but) return r_str_lchr (s, ch); if (strlen (but) >= bsz) { eprintf ("r_str_lastbut: but string too long\n"); return NULL; } for (p=s; *p; p++) { isbut = strchr (but, *p); if (isbut) { idx = (int)(size_t)(isbut-but); _b = R_BIT_CHK (b, idx)? R_BIT_UNSET (b, idx): R_BIT_SET (b, idx); continue; } if (*p == ch && !_b) lp = p; } return lp; } // Must be merged inside strlen R_API int r_str_len_utf8char (const char *s, int left) { int i = 1; while (s[i] && (!left || i<left)) { if ((s[i] & 0xc0) != 0x80) { i++; } else break; } return i; } R_API int r_str_len_utf8 (const char *s) { int i = 0, j = 0; while (s[i]) { if ((s[i] & 0xc0) != 0x80) j++; i++; } return j; } R_API const char *r_str_casestr(const char *a, const char *b) { // That's a GNUism that works in many places.. but we dont want it // return strcasestr (a, b); size_t hay_len = strlen (a); size_t needle_len = strlen (b); while (hay_len >= needle_len) { if (strncasecmp (a, b, needle_len) == 0) return (const char *) a; a++; hay_len--; } return NULL; } R_API int r_str_write (int fd, const char *b) { return write (fd, b, strlen (b)); } R_API void r_str_range_foreach(const char *r, RStrRangeCallback cb, void *u) { const char *p = r; for (; *r; r++) { if (*r == ',') { cb (u, atoi (p)); p = r+1; } if (*r == '-') { if (p != r) { int from = atoi (p); int to = atoi (r+1); for (; from<=to; from++) cb (u, from); } else fprintf (stderr, "Invalid range\n"); for (r++; *r && *r!=','&& *r!='-'; r++); p = r; } } if (*p) cb (u, atoi (p)); } // convert from html escaped sequence "foo%20bar" to "foo bar" // TODO: find better name.. unencode? decode R_API void r_str_uri_decode (char *s) { int n; char *d; for (d=s; *s; s++, d++) { #if 0 if (*s == '+') { *d = ' '; } else #endif if (*s == '%') { sscanf (s+1, "%02x", &n); *d = n; s+=2; } else *d = *s; } *d = 0; } R_API char *r_str_uri_encode (const char *s) { char ch[4], *d, *od; if (!s) return NULL; od = d = malloc (1+(strlen (s)*4)); if (!d) return NULL; for (; *s; s++) { if((*s>='0' && *s<='9') || (*s>='a' && *s<='z') || (*s>='A' && *s<='Z')) { *d++ = *s; } else { *d++ = '%'; sprintf (ch, "%02x", 0xff & ((ut8)*s)); *d++ = ch[0]; *d++ = ch[1]; } } *d = 0; return realloc (od, strlen (od)+1); // FIT } R_API char *r_str_utf16_encode (const char *s, int len) { int i; char ch[4], *d, *od; if (!s) return NULL; if (len<0) len = strlen (s); od = d = malloc (1+(len*7)); if (!d) return NULL; for (i=0; i<len; s++, i++) { if ((*s>=0x20) && (*s<=126)) { *d++ = *s; } else { *d++ = '\\'; *d++ = '\\'; *d++ = 'u'; *d++ = '0'; *d++ = '0'; sprintf (ch, "%02x", 0xff & ((ut8)*s)); *d++ = ch[0]; *d++ = ch[1]; } } *d = 0; return realloc (od, strlen (od)+1); // FIT } // TODO: merge print inside rutil /* hack from print */ R_API int r_print_format_length (const char *fmt) { int nargs, i, j, idx, times, endian; char *args, *bracket, tmp, last = 0; const char *arg = fmt; const char *argend = arg+strlen (fmt); char namefmt[8]; int viewflags = 0; nargs = endian = i = j = 0; while (*arg && iswhitechar (*arg)) arg++; /* get times */ times = atoi (arg); if (times > 0) while ((*arg>='0'&&*arg<='9')) arg++; bracket = strchr (arg,'{'); if (bracket) { char *end = strchr (arg,'}'); if (end == NULL) { eprintf ("No end bracket. Try pm {ecx}b @ esi\n"); return 0; } *end='\0'; times = r_num_math (NULL, bracket+1); arg = end + 1; } if (*arg=='\0') return 0; /* get args */ args = strchr (arg, ' '); if (args) { int l=0, maxl = 0; argend = args; args = strdup (args+1); nargs = r_str_word_set0 (args+1); if (nargs == 0) R_FREE (args); for (i=0; i<nargs; i++) { int len = strlen (r_str_word_get0 (args+1, i)); if (len>maxl) maxl = len; } l++; snprintf (namefmt, sizeof (namefmt), "%%%ds : ", maxl); } /* go format */ i = 0; if (!times) times = 1; for (; times; times--) { // repeat N times const char * orig = arg; idx = 0; arg = orig; for (idx=0; arg<argend && *arg; idx++, arg++) { tmp = *arg; feed_me_again: if (tmp == 0 && last != '*') break; /* skip chars */ switch (tmp) { case '*': if (i<=0) break; tmp = last; arg--; idx--; goto feed_me_again; case '+': idx--; viewflags = !viewflags; continue; case 'e': // tmp swap endian idx--; endian ^= 1; continue; case '.': // skip char i++; idx--; continue; case 'p': tmp = (sizeof (void*)==8)? 'q': 'x'; break; case '?': // help idx--; if (args) free (args); return 0; } switch (tmp) { case 'e': i += 8; break; case 'q': i += 8; break; case 'b': i++; break; case 'c': i++; break; case 'B': i += 4; break; case 'i': i += 4; break; case 'd': i += 4; break; case 'x': i += 4; break; case 'w': case '1': i += 2; break; case 'z': // XXX unsupported case 'Z': // zero terminated wide string break; case 's': i += 4; break; // S for 8? case 'S': i += 8; break; // S for 8? default: /* ignore unknown chars */ break; } last = tmp; } arg = orig; idx = 0; } if (args) { free (args); } return i; } R_API char *r_str_prefix_all (char *s, const char *pfx) { int newlines = 1; int len = 0; int plen = 0; char *o, *p, *os = s; if (s) { len = strlen (s); if (pfx) { plen = strlen (pfx); } for (p=s;*p;p++) if (*p=='\n') newlines++; o = malloc (len + (plen*newlines)+1); memcpy (o, pfx, plen); for (p=o+plen;*s;s++) { *p++ = *s; if (*s=='\n' && s[1]) { memcpy (p, pfx, plen); p += plen; } } *p = 0; free (os); return o; } else { return NULL; } } #define HASCH(x) strchr (input_value,x) #define CAST (void*)(size_t) R_API ut8 r_str_contains_macro(const char *input_value) { char *has_tilde = input_value ? HASCH('~') : NULL, *has_bang = input_value ? HASCH('!') : NULL, *has_brace = input_value ? CAST(HASCH('[') || HASCH(']')) : NULL, *has_paren = input_value ? CAST(HASCH('(') || HASCH(')')) : NULL, *has_cbrace = input_value ? CAST(HASCH('{') || HASCH('}')) : NULL, *has_qmark = input_value ? HASCH('?') : NULL, *has_colon = input_value ? HASCH(':') : NULL, *has_at = input_value ? strchr (input_value, '@') : NULL; return has_tilde || has_bang || has_brace || has_cbrace || has_qmark \ || has_paren || has_colon || has_at; } R_API void r_str_truncate_cmd(char *string) { ut32 pos = 0, done = 0; if (string) { ut32 sz = strlen (string); for (pos = 0; pos < sz; pos++) { switch (string[pos]) { case '!': case ':': case ';': case '@': case '~': case '(': case '[': case '{': case '?': string[pos] = '\0'; done = 1; } if (done) break; } } } R_API const char *r_str_closer_chr (const char *b, const char *s) { const char *a; while (*b) { for (a=s;*a;a++) if (*b==*a) return b; b++; } return NULL; } #if 0 R_API int r_str_bounds(const char *str, int *h) { int W = 0, H = 0; int cw = 0; if (!str) return W; while (*str) { if (*str=='\n') { H++; if (cw>W) W = cw; cw = 0; } str++; cw++; } if (*str == '\n') // skip last newline H--; if (h) *h = H; return W; } #else R_API int r_str_bounds(const char *_str, int *h) { char *ostr, *str, *ptr; int W = 0, H = 0; int cw = 0; if (_str) { ptr = str = ostr = strdup (_str); while (*str) { if (*str=='\n') { H++; *str = 0; cw = (size_t)(str-ptr); cw = r_str_ansi_len (ptr); if (cw>W) W = cw; *str = '\n'; cw = 0; ptr = str; } str++; cw++; } if (*str == '\n') // skip last newline H--; if (h) *h = H; free (ostr); } return W; } #endif R_API char *r_str_crop(const char *str, int x, int y, int w, int h) { char *r, *ret; int ch = 0, cw = 0; if (w<1 || h<1) return strdup (""); r = ret = strdup (str); while (*str) { /* crop height */ if (ch>=h) { r--; break; } if (*str == '\n') { if (ch>=y && ch<h) if (cw>=x && cw<w) *r++ = *str; ch++; cw = 0; } else { /* crop width */ if (w>0 && cw>=w) { *r++ = '\n'; /* skip str until newline */ while (*str && *str != '\n') { str++; } if (!*str)break; if (*str=='\n') { str++; if (!*str)break; } cw = 0; ch++; } if (ch>=y && ch<h) if (cw>=x && cw<w) *r++ = *str; } str++; cw++; } *r = 0; return ret; } R_API const char * r_str_tok (const char *str1, const char b, size_t len) { const char *p = str1; size_t i = 0; if (!p || !*p) return p; if (len == -1) len = strlen (str1); for ( ; i < len; i++,p++) if (*p == b) break; if (i == len) p = NULL; return p; } R_API const char *r_str_pad(const char ch, int sz) { static char pad[1024]; if (sz<0) sz = 0; memset (pad, ch, R_MIN (sz, sizeof (pad))); if (sz<sizeof(pad)) pad[sz] = 0; pad[sizeof(pad)-1] = 0; return pad; }
aoighost/radare2
libr/util/str.c
C
gpl-3.0
34,267
<!DOCTYPE html> <html lang="en-US"> <!--********************************************--> <!--* Generated from PreTeXt source *--> <!--* on 2021-03-10T19:25:42-08:00 *--> <!--* A recent stable commit (2020-08-09): *--> <!--* 98f21740783f166a773df4dc83cab5293ab63a4a *--> <!--* *--> <!--* https://pretextbook.org *--> <!--* *--> <!--********************************************--> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="robots" content="noindex, nofollow"> </head> <body> <h6 xmlns:svg="http://www.w3.org/2000/svg" class="heading"><span class="type">Paragraph</span></h6> <p xmlns:svg="http://www.w3.org/2000/svg">The middle two parts (Violin II and Viola) are paired together and the Violin I and Cello/Bass part engage in imitation</p> <span class="incontext"><a href="Eine-kleine-ii.html#p-822">in-context</a></span> </body> </html>
rhutchinson20/mt21c
images/unit5/knowl/p-822.html
HTML
gpl-3.0
1,007
class Solution { public String licenseKeyFormatting(String S, int K) { S = S.replaceAll("-", "").toUpperCase(); StringBuilder F = new StringBuilder(); int first = S.length() % K; if (first > 0) { F.append(S.substring(0, first)); } for (int i = first; i <= S.length() - K; i += K) { if (i > 0) { F.append("-"); } F.append(S.substring(i, i + K)); } return F.toString(); } }
rishabhtulsian/problem-solving
leet-code/482-LicenseKeyFormatting.java
Java
gpl-3.0
523