code
stringlengths
5
1.01M
repo_name
stringlengths
5
84
path
stringlengths
4
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
5
1.01M
input_ids
listlengths
502
502
token_type_ids
listlengths
502
502
attention_mask
listlengths
502
502
labels
listlengths
502
502
package trendli.me.makhana.common.entities; import java.util.Arrays; import java.util.Collections; import java.util.List; public enum ActionType { MOVE( "Moving", "newTile" ), FABRICATING( "Fabricating" ); private final String verb; private final List< String > dataKeys; private ActionType( String verb, String... dataKeys ) { this.verb = verb; if ( dataKeys != null ) { this.dataKeys = Arrays.asList( dataKeys ); } else { this.dataKeys = Collections.emptyList( ); } } /** * @return the dataKeys */ public List< String > getDataKeys( ) { return dataKeys; } /** * @return the verb */ public String getVerb( ) { return verb; } }
elliottmb/makhana
common/src/main/java/trendli/me/makhana/common/entities/ActionType.java
Java
apache-2.0
806
[ 30522, 7427, 9874, 3669, 1012, 2033, 1012, 5003, 26370, 2050, 1012, 2691, 1012, 11422, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 27448, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 6407, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 2862, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Greeter module for xdm Copyright (C) 1997, 1998 Steffen Hansen <hansen@kde.org> Copyright (C) 2000-2003 Oswald Buddenhagen <ossi@kde.org> 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. */ #include "kdm_greet.h" #include "kdmshutdown.h" #include "kdmconfig.h" #include "kgapp.h" #include "kgreeter.h" #ifdef XDMCP # include "kchooser.h" #endif #include <kprocess.h> #include <kcmdlineargs.h> #include <kcrash.h> #include <kstandarddirs.h> #include <ksimpleconfig.h> #include <qtimer.h> #include <qcursor.h> #include <qpalette.h> #include <stdlib.h> // free(), exit() #include <unistd.h> // alarm() #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <X11/cursorfont.h> extern "C" { static void sigAlarm( int ) { exit( EX_RESERVER_DPY ); } } GreeterApp::GreeterApp() { pingInterval = _isLocal ? 0 : _pingInterval; if (pingInterval) { struct sigaction sa; sigemptyset( &sa.sa_mask ); sa.sa_flags = 0; sa.sa_handler = sigAlarm; sigaction( SIGALRM, &sa, 0 ); alarm( pingInterval * 70 ); // sic! give the "proper" pinger enough time startTimer( pingInterval * 60000 ); } } void GreeterApp::timerEvent( QTimerEvent * ) { alarm( 0 ); if (!PingServer( qt_xdisplay() )) ::exit( EX_RESERVER_DPY ); alarm( pingInterval * 70 ); // sic! give the "proper" pinger enough time } bool GreeterApp::x11EventFilter( XEvent * ev ) { KeySym sym; switch (ev->type) { case FocusIn: case FocusOut: // Hack to tell dialogs to take focus when the keyboard is grabbed ev->xfocus.mode = NotifyNormal; break; case KeyPress: sym = XLookupKeysym( &ev->xkey, 0 ); if (sym != XK_Return && !IsModifierKey( sym )) emit activity(); break; case ButtonPress: emit activity(); /* fall through */ case ButtonRelease: // Hack to let the RMB work as LMB if (ev->xbutton.button == 3) ev->xbutton.button = 1; /* fall through */ case MotionNotify: if (ev->xbutton.state & Button3Mask) ev->xbutton.state = (ev->xbutton.state & ~Button3Mask) | Button1Mask; break; } return false; } extern bool kde_have_kipc; extern "C" { static int xIOErr( Display * ) { exit( EX_RESERVER_DPY ); } void kg_main( const char *argv0 ) { static char *argv[] = { (char *)"kdmgreet", 0 }; KCmdLineArgs::init( 1, argv, *argv, 0, 0, 0, true ); kde_have_kipc = false; KApplication::disableAutoDcopRegistration(); KCrash::setSafer( true ); GreeterApp app; XSetIOErrorHandler( xIOErr ); Display *dpy = qt_xdisplay(); if (!_GUIStyle.isEmpty()) app.setStyle( _GUIStyle ); _colorScheme = locate( "data", "kdisplay/color-schemes/" + _colorScheme + ".kcsrc" ); if (!_colorScheme.isEmpty()) { KSimpleConfig config( _colorScheme, true ); config.setGroup( "Color Scheme" ); app.setPalette( app.createApplicationPalette( &config, 7 ) ); } app.setFont( _normalFont ); setup_modifiers( dpy, _numLockStatus ); SecureDisplay( dpy ); KProcess *proc = 0; if (!_grabServer) { if (_useBackground) { proc = new KProcess; *proc << QCString( argv0, strrchr( argv0, '/' ) - argv0 + 2 ) + "krootimage"; *proc << _backgroundCfg; proc->start(); } GSendInt( G_SetupDpy ); GRecvInt(); } GSendInt( G_Ready ); setCursor( dpy, app.desktop()->winId(), XC_left_ptr ); for (;;) { int rslt, cmd = GRecvInt(); if (cmd == G_ConfShutdown) { int how = GRecvInt(), uid = GRecvInt(); char *os = GRecvStr(); KDMSlimShutdown::externShutdown( how, os, uid ); if (os) free( os ); GSendInt( G_Ready ); _autoLoginDelay = 0; continue; } if (cmd == G_ErrorGreet) { if (KGVerify::handleFailVerify( qApp->desktop()->screen( _greeterScreen ) )) break; _autoLoginDelay = 0; cmd = G_Greet; } KProcess *proc2 = 0; app.setOverrideCursor( Qt::WaitCursor ); FDialog *dialog; #ifdef XDMCP if (cmd == G_Choose) { dialog = new ChooserDlg; GSendInt( G_Ready ); /* tell chooser to go into async mode */ GRecvInt(); /* ack */ } else #endif { if ((cmd != G_GreetTimed && !_autoLoginAgain) || _autoLoginUser.isEmpty()) _autoLoginDelay = 0; if (_useTheme && !_theme.isEmpty()) { KThemedGreeter *tgrt; dialog = tgrt = new KThemedGreeter; if (!tgrt->isOK()) { delete tgrt; dialog = new KStdGreeter; } } else dialog = new KStdGreeter; if (*_preloader) { proc2 = new KProcess; *proc2 << _preloader; proc2->start(); } } app.restoreOverrideCursor(); Debug( "entering event loop\n" ); rslt = dialog->exec(); Debug( "left event loop\n" ); delete dialog; delete proc2; #ifdef XDMCP switch (rslt) { case ex_greet: GSendInt( G_DGreet ); continue; case ex_choose: GSendInt( G_DChoose ); continue; default: break; } #endif break; } KGVerify::done(); delete proc; UnsecureDisplay( dpy ); restore_modifiers(); XSetInputFocus( qt_xdisplay(), PointerRoot, PointerRoot, CurrentTime ); } } // extern "C" #include "kgapp.moc"
iegor/kdebase
kdm/kfrontend/kgapp.cpp
C++
gpl-2.0
5,569
[ 30522, 1013, 1008, 17021, 2121, 11336, 2005, 1060, 22117, 9385, 1006, 1039, 1007, 2722, 1010, 2687, 26261, 18032, 13328, 1026, 13328, 1030, 1047, 3207, 1012, 8917, 1028, 9385, 1006, 1039, 1007, 2456, 1011, 2494, 17411, 13007, 4181, 3270, 69...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.md_5.cascade; import com.avaje.ebean.config.ServerConfig; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import org.bukkit.GameMode; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.Warning.WarningState; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.command.CommandException; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.help.HelpMap; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.map.MapView; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.ServicesManager; import org.bukkit.plugin.messaging.Messenger; import org.bukkit.scheduler.BukkitScheduler; public class CascadeServer implements Server { @Override public String getName() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getVersion() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getBukkitVersion() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Player[] getOnlinePlayers() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getMaxPlayers() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getPort() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getViewDistance() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getIp() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getServerName() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getServerId() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getWorldType() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean getGenerateStructures() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean getAllowEnd() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean getAllowNether() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasWhitelist() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setWhitelist(boolean value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<OfflinePlayer> getWhitelistedPlayers() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void reloadWhitelist() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int broadcastMessage(String message) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getUpdateFolder() { throw new UnsupportedOperationException("Not supported yet."); } @Override public File getUpdateFolderFile() { throw new UnsupportedOperationException("Not supported yet."); } @Override public long getConnectionThrottle() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getTicksPerAnimalSpawns() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getTicksPerMonsterSpawns() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Player getPlayer(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Player getPlayerExact(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Player> matchPlayer(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public PluginManager getPluginManager() { throw new UnsupportedOperationException("Not supported yet."); } @Override public BukkitScheduler getScheduler() { throw new UnsupportedOperationException("Not supported yet."); } @Override public ServicesManager getServicesManager() { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<World> getWorlds() { throw new UnsupportedOperationException("Not supported yet."); } @Override public World createWorld(WorldCreator creator) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean unloadWorld(String name, boolean save) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean unloadWorld(World world, boolean save) { throw new UnsupportedOperationException("Not supported yet."); } @Override public World getWorld(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public World getWorld(UUID uid) { throw new UnsupportedOperationException("Not supported yet."); } @Override public MapView getMap(short id) { throw new UnsupportedOperationException("Not supported yet."); } @Override public MapView createMap(World world) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void reload() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Logger getLogger() { throw new UnsupportedOperationException("Not supported yet."); } @Override public PluginCommand getPluginCommand(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void savePlayers() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean dispatchCommand(CommandSender sender, String commandLine) throws CommandException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void configureDbConfig(ServerConfig config) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean addRecipe(Recipe recipe) { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Recipe> getRecipesFor(ItemStack result) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Iterator<Recipe> recipeIterator() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void clearRecipes() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void resetRecipes() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Map<String, String[]> getCommandAliases() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getSpawnRadius() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setSpawnRadius(int value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean getOnlineMode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean getAllowFlight() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean useExactLoginLocation() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void shutdown() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int broadcast(String message, String permission) { throw new UnsupportedOperationException("Not supported yet."); } @Override public OfflinePlayer getOfflinePlayer(String name) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<String> getIPBans() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void banIP(String address) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void unbanIP(String address) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<OfflinePlayer> getBannedPlayers() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<OfflinePlayer> getOperators() { throw new UnsupportedOperationException("Not supported yet."); } @Override public GameMode getDefaultGameMode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setDefaultGameMode(GameMode mode) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ConsoleCommandSender getConsoleSender() { throw new UnsupportedOperationException("Not supported yet."); } @Override public File getWorldContainer() { throw new UnsupportedOperationException("Not supported yet."); } @Override public OfflinePlayer[] getOfflinePlayers() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Messenger getMessenger() { throw new UnsupportedOperationException("Not supported yet."); } @Override public HelpMap getHelpMap() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Inventory createInventory(InventoryHolder owner, InventoryType type) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Inventory createInventory(InventoryHolder owner, int size) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Inventory createInventory(InventoryHolder owner, int size, String title) { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getMonsterSpawnLimit() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getAnimalSpawnLimit() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int getWaterAnimalSpawnLimit() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isPrimaryThread() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getMotd() { throw new UnsupportedOperationException("Not supported yet."); } @Override public WarningState getWarningState() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void sendPluginMessage(Plugin source, String channel, byte[] message) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<String> getListeningPluginChannels() { throw new UnsupportedOperationException("Not supported yet."); } }
BukkitDevTeam/Cascade
src/main/java/com/md_5/cascade/CascadeServer.java
Java
bsd-3-clause
12,248
[ 30522, 7427, 4012, 1012, 9108, 1035, 1019, 1012, 16690, 1025, 12324, 4012, 1012, 10927, 6460, 1012, 1041, 4783, 2319, 1012, 9530, 8873, 2290, 1012, 8241, 8663, 8873, 2290, 1025, 12324, 9262, 1012, 22834, 1012, 5371, 1025, 12324, 9262, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * User: shenzhe * Date: 13-6-17 * config配置处理 */ namespace ZPHP\Core; use ZPHP\Common\Dir; use ZPHP\Protocol\Request; class Config { private static $config; private static $nextCheckTime = 0; private static $lastModifyTime = []; private static $configPath; private static $reloadPath; public static function load($configPath) { $files = Dir::tree($configPath, "/.php$/"); $config = array(); if (!empty($files)) { foreach ($files as $file) { if (Request::isLongServer() && function_exists("opcache_invalidate")) { \opcache_invalidate($file); } $config += include "{$file}"; } } self::$config = $config; self::$configPath = $configPath; if (!empty(self::$config['project']['auto_reload']) && !empty(self::$config['project']['reload_path']) ) { self::mergePath(self::$config['project']['reload_path']); } return self::$config; } public static function loadFiles(array $files) { $config = array(); foreach ($files as $file) { $config += include "{$file}"; } self::$config = $config; return $config; } public static function mergePath($path) { $files = Dir::tree($path, "/.php$/"); if (!empty($files)) { $config = array(); foreach ($files as $file) { if (Request::isLongServer() && function_exists("opcache_invalidate")) { \opcache_invalidate($file); } $config += include "{$file}"; } self::$config = array_merge(self::$config, $config); } if (Request::isLongServer()) { self::$reloadPath[$path] = $path; self::$nextCheckTime = time() + empty($config['project']['config_check_time']) ? 5 : $config['project']['config_check_time']; self::$lastModifyTime[$path] = \filectime($path); } } public static function mergeFile($file) { $tmp = include "{$file}"; if (empty($tmp)) { return false; } self::$config = array_merge(self::$config, $tmp); return true; } public static function get($key, $default = null, $throw = false) { self::checkTime(); $result = isset(self::$config[$key]) ? self::$config[$key] : $default; if ($throw && is_null($result)) { throw new \Exception("{key} config empty"); } return $result; } public static function set($key, $value, $set = true) { if ($set) { self::$config[$key] = $value; } else { if (empty(self::$config[$key])) { self::$config[$key] = $value; } } return true; } public static function getField($key, $field, $default = null, $throw = false) { self::checkTime(); $result = isset(self::$config[$key][$field]) ? self::$config[$key][$field] : $default; if ($throw && is_null($result)) { throw new \Exception("{key} config empty"); } return $result; } public static function setField($key, $field, $value, $set = true) { if ($set) { self::$config[$key][$field] = $value; } else { if (empty(self::$config[$key][$field])) { self::$config[$key][$field] = $value; } } return true; } public static function all() { return self::$config; } public static function checkTime() { if (Request::isLongServer()) { if (self::$nextCheckTime < time() && !empty(self::$reloadPath)) { foreach (self::$reloadPath as $path) { if (!is_dir($path)) { continue; } \clearstatcache($path); if (self::$lastModifyTime[$path] < \filectime($path)) { self::mergePath($path); } } } } return; } }
shenzhe/zphp
ZPHP/Core/Config.php
PHP
apache-2.0
4,269
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 5310, 1024, 21882, 27922, 2063, 1008, 3058, 1024, 2410, 1011, 1020, 1011, 2459, 1008, 9530, 8873, 2290, 100, 100, 100, 100, 1008, 1013, 3415, 15327, 1062, 8458, 2361, 1032, 4563, 1025, 222...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<h3>Edit Guru</h3> <div class="isikanan"><!--Awal class isi kanan--> <div class="judulisikanan"> <div class="menuhorisontalaktif-ujung"><a href="guru_staff.php">Guru</a></div> <div class="menuhorisontal"><a href="staff.php">Staff</a></div> <div class="menuhorisontal"><a href="jabatan.php">Jabatan</a></div> </div> <table class="isian"> <form method='POST' <?php echo "action='$database?pilih=guru&untukdi=edit'";?> name='editguru' id='editguru' enctype="multipart/form-data"> <?php $edit=mysql_query("SELECT * FROM sh_guru_staff, sh_mapel WHERE sh_guru_staff.id_mapel=sh_mapel.id_mapel AND id_gurustaff='$_GET[id]'"); $r=mysql_fetch_array($edit); echo "<input type='hidden' name='id' value='$r[id_gurustaff]'"; ?> <tr><td class="isiankanan" width="175px">Nama Guru</td><td class="isian"><input type="text" name="nama_guru" class="maksimal" value="<?php echo"$r[nama_gurustaff]";?>"></td></tr> <tr><td class="isiankanan" width="175px">NIP</td><td class="isian"><input type="text" name="nip" class="pendek" value="<?php echo"$r[nip]";?>"></td></tr> <tr><td class="isiankanan" width="175px">Password</td><td class="isian"> <a href="javascript:void(0)"onclick="window.open('<?php echo "aplikasi/guru_password.php?id=$r[id_gurustaff]"; ?>','linkname','height=315, width=500,scrollbars=yes')"><b><u>Ganti Password</u></b></a></td></tr> <tr><td class="isiankanan" width="175px">Foto</td><td class="isian"><img src="../images/foto/guru/<?php echo "$r[foto]";?>" width="200px"> <?php if ($r[foto] !='no_photo.jpg'){?> <br><br> <a href="<?php echo "$database?pilih=guru&untukdi=hapusgambar&id=$r[id_gurustaff]";?>"><b><u>Hapus gambar</u></b></a> <?php }?> </td></tr> <tr><td class="isiankanan" width="175px">Ganti Foto</td><td class="isian"><input type="file" name="fupload"></td></tr> <tr><td class="isiankanan" width="175px">Jenis Kelamin</td> <td class="isian"> <?php if ($r[jenkel]=='L'){ ?> <input type="radio" name="jk" value="L" checked/>Laki-laki&nbsp; <input type="radio" name="jk" value="P"/>Perempuan <?php } else { ?> <input type="radio" name="jk" value="L"/>Laki-laki&nbsp; <input type="radio" name="jk" value="P" checked/>Perempuan <?php } ?> </td></tr> <tr><td class="isiankanan" width="175px">Tempat, Tanggal Lahir</td><td class="isian"> <input type="text" name="tempat_lahir" class="pendek" value="<?php echo"$r[tempat_lahir]";?>">, <input type="text" id="tanggal" name="tanggal_lahir" class="pendek" style="width:20%" value="<?php echo"$r[tanggal_lahir]";?>"></td></tr> <tr><td class="isiankanan" width="175px">Mengajar</td> <td class="isian"> <select name="mata_pelajaran"> <option value="<?php echo "$r[id_mapel]";?>" selected><?php echo "$r[nama_mapel]";?></option> <?php $mapel=mysql_query("SELECT * FROM sh_mapel ORDER BY nama_mapel ASC"); while ($m=mysql_fetch_array($mapel)){ echo "<option value='$m[id_mapel]'>$m[nama_mapel]</option>"; } ?> </select> </td></tr> <tr><td class="isiankanan" width="175px">Alamat</td><td class="isian"><textarea name="alamat" style="height: 100px"><?php echo"$r[alamat]";?></textarea></td></tr> <tr><td class="isiankanan" width="175px">Pendidikan Terakhir</td> <td class="isian"> <select name="pendidikan"> <option value="<?php echo "$r[pendidikan_terakhir]";?>" selected><?php echo "$r[pendidikan_terakhir]";?></option> <option value="SMA sederajat">SMA sederajat</option> <option value="Diploma 1 (D1)">Diploma 1 (D1)</option> <option value="Diploma 2 (D2)">Diploma 2 (D2)</option> <option value="Diploma 3 (D3)">Diploma 3 (D3)</option> <option value="Strata 1 (S1)">Strata 1 (S1)</option> <option value="Magister (S2)">Magister (S2)</option> <option value="Doktor (S3)">Doktor (S3)</option> </select> </td></tr> <tr><td class="isiankanan" width="175px">Tahun Masuk</td><td class="isian"> <?php $thn_skrg=date("Y"); echo "<select name=tahun_masuk> <option value='$r[tahun_masuk]' selected>$r[tahun_masuk]</option>"; for ($thn=1990;$thn<=$thn_skrg;$thn++){ echo "<option value=$thn>$thn</option>"; } echo "</select>"; ?> </td></tr> <tr><td class="isiankanan" width="175px">Status Perkawinan</td> <td class="isian"> <select name="status_kawin"> <option value="<?php echo "$r[status_kawin]";?>" selected><?php echo "$r[status_kawin]";?></option> <option value="Menikah">Menikah</option> <option value="Belum Menikah">Belum menikah</option> <option value="Duda">Duda</option> <option value="Janda">Janda</option> </select> </td></tr> <tr><td class="isiankanan" width="175px">Email</td><td class="isian"><input type="text" name="email" class="pendek" value="<?php echo"$r[email]";?>"></td></tr> <tr><td class="isiankanan" width="175px">Telepon/ HP</td><td class="isian"><input type="text" name="telepon" class="pendek" value="<?php echo"$r[telepon]";?>"></td></tr> <tr><td class="isian" colspan="2"> <input type="submit" class="pencet" value="Update"> <input type="button" class="hapus" value="Batal" onclick="self.history.back()"> </td></tr> </form> <script language="JavaScript" type="text/javascript" xml:space="preserve"> //<![CDATA[ var frmvalidator = new Validator("editguru"); frmvalidator.addValidation("nama_guru","req","Nama guru harus diisi"); frmvalidator.addValidation("nama_guru","maxlen=30","Nama guru maksimal 30 karakter"); frmvalidator.addValidation("nama_guru","minlen=3","Nama guru minimal 3 karakter"); frmvalidator.addValidation("nip","req","NIP guru harus diisi"); frmvalidator.addValidation("nip","maxlen=18","NIP guru maksimal 18 karakter"); frmvalidator.addValidation("nip","minlen=9","NIP guru minimal 9 karakter"); frmvalidator.addValidation("nip","numeric","NIP ditulis dengan angka"); frmvalidator.addValidation("fupload","file_extn=jpg;gif;png","Jenis file yang diterima untuk gambar adalah : jpg, gif, png"); frmvalidator.addValidation("mata_pelajaran","req","Anda belum memilih mata pelajaran"); frmvalidator.addValidation("pendidikan","req","Anda belum memilih pendidikan terakhir"); frmvalidator.addValidation("status_kawin","req","Anda belum memilih status perkawinan"); frmvalidator.addValidation("tahun_masuk","req","Tahun masuk harus diisi"); frmvalidator.addValidation("tempat_lahir","req","Tempat lahir harus diisi"); frmvalidator.addValidation("tanggal_lahir","req","Tanggal lahir harus diisi"); frmvalidator.addValidation("email","email","Format email salah"); //]]> </script> </table> </div><!--Akhir class isi kanan-->
zuhzwan/synp02
adminpanel/aplikasi/guru_edit.php
PHP
gpl-2.0
6,763
[ 30522, 1026, 1044, 2509, 1028, 10086, 11972, 1026, 1013, 1044, 2509, 30524, 7556, 7229, 1000, 1028, 1026, 4487, 2615, 2465, 1027, 1000, 12183, 16368, 10929, 9080, 4817, 3775, 2546, 1011, 1057, 19792, 2290, 1000, 1028, 1026, 1037, 17850, 128...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch11/11.4/11.4.1/11.4.1-5-a-27-s.js * @description Strict Mode - TypeError is thrown after deleting a property, calling preventExtensions, and attempting to reassign the property * @onlyStrict */ function testcase() { "use strict"; var a = {x:0, get y() { return 0;}}; delete a.x; Object.preventExtensions(a); try { a.x = 1; return false; } catch (e) { return e instanceof TypeError; } } runTestCase(testcase);
Oceanswave/NiL.JS
Tests/tests/sputnik/ch11/11.4/11.4.1/11.4.1-5-a-27-s.js
JavaScript
bsd-3-clause
587
[ 30522, 1013, 1013, 1013, 9385, 1006, 1039, 1007, 2262, 14925, 2863, 2248, 1012, 2035, 2916, 9235, 1012, 1013, 1008, 1008, 1008, 1030, 4130, 10381, 14526, 1013, 2340, 1012, 1018, 1013, 2340, 1012, 1018, 1012, 1015, 1013, 2340, 1012, 1018, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* This file is part of the YAZ toolkit. * Copyright (C) 1995-2013 Index Data. * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Index Data nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file mutex.h * \brief Header for Mutex functions */ #ifndef YAZ_MUTEX_H #define YAZ_MUTEX_H #include <stddef.h> #include <time.h> #include <yaz/yconfig.h> YAZ_BEGIN_CDECL /** \brief YAZ MUTEX opaque pointer */ typedef struct yaz_mutex *YAZ_MUTEX; /** \brief YAZ condition opaque pointer */ typedef struct yaz_cond *YAZ_COND; /** \brief create MUTEX \param mutexp is pointer to MUTEX handle (*mutexp must be NULL) It is important that *mutexp is NULL. If not, yaz_mutex_create will not modify the handle (assumes it is already created!) */ YAZ_EXPORT void yaz_mutex_create(YAZ_MUTEX *mutexp); /** \brief enter critical section / AKA lock \param mutex MUTEX handle */ YAZ_EXPORT void yaz_mutex_enter(YAZ_MUTEX mutex); /** \brief leave critical section / AKA unlock \param mutex MUTEX handle */ YAZ_EXPORT void yaz_mutex_leave(YAZ_MUTEX mutex); /** \brief destroy MUTEX \param mutexp pointer to MUTEX handle If *mutexp is NULL, then this function does nothing. */ YAZ_EXPORT void yaz_mutex_destroy(YAZ_MUTEX *mutexp); /** \brief sets name of MUTEX for debugging purposes \param mutex MUTEX handle \param log_level YAZ log level \param name user-given name associated with MUTEX If log_level != 0 and name != 0 this function will make yaz_mutex_enter and yaz_mutex_leave print information for each invocation using yaz_log with the level given. In particular when YAZ is compiled with pthreads, yaz_mutex_enter will inform if a lock is not immediately acquired. This function should be called after a MUTEX is created but before it is used for locking. */ YAZ_EXPORT void yaz_mutex_set_name(YAZ_MUTEX mutex, int log_level, const char *name); /** \brief creates condition variable \param p reference to condition handle Upon successful completion *p holds the condition handle; *p = 0 on error. */ YAZ_EXPORT void yaz_cond_create(YAZ_COND *p); /** \brief destroys condition variable \param p reference to condition handle Upon completion *p holds 0. */ YAZ_EXPORT void yaz_cond_destroy(YAZ_COND *p); struct timeval; /** \brief waits for condition \param p condition variable handle \param m mutex \param abstime wait until this time; 0 for indefinite wait Semantics like pthread_cond_wait. */ YAZ_EXPORT int yaz_cond_wait(YAZ_COND p, YAZ_MUTEX m, const struct timeval *abstime); /** \brief unblock one thread waiting for block \param p condition variable handle */ YAZ_EXPORT int yaz_cond_signal(YAZ_COND p); /** \brief unblock all threads waiting for block \param p condition variable handle */ YAZ_EXPORT int yaz_cond_broadcast(YAZ_COND p); YAZ_END_CDECL #endif /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
nla/yaz
include/yaz/mutex.h
C
bsd-3-clause
4,473
[ 30522, 1013, 1008, 2023, 5371, 2003, 2112, 1997, 1996, 8038, 2480, 6994, 23615, 1012, 1008, 9385, 1006, 1039, 1007, 2786, 1011, 2286, 5950, 2951, 1012, 1008, 2035, 2916, 9235, 1012, 1008, 25707, 1998, 2224, 1999, 3120, 1998, 12441, 3596, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Package govalidator is package of validators and sanitizers for strings, structs and collections. package govalidator import ( "encoding/json" "fmt" "net" "net/url" "reflect" "regexp" "sort" "strings" "unicode" "unicode/utf8" ) var fieldsRequiredByDefault bool // SetFieldsRequiredByDefault causes validation to fail when struct fields // do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). // This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): // type exampleStruct struct { // Name string `` // Email string `valid:"email"` // This, however, will only fail when Email is empty or an invalid email address: // type exampleStruct2 struct { // Name string `valid:"-"` // Email string `valid:"email"` // Lastly, this will only fail when Email is an invalid email address but not when it's empty: // type exampleStruct2 struct { // Name string `valid:"-"` // Email string `valid:"email,optional"` func SetFieldsRequiredByDefault(value bool) { fieldsRequiredByDefault = value } // IsEmail check if the string is an email. func IsEmail(str string) bool { // TODO uppercase letters are not supported return rxEmail.MatchString(str) } // IsURL check if the string is an URL. func IsURL(str string) bool { if str == "" || len(str) >= 2083 || len(str) <= 3 || strings.HasPrefix(str, ".") { return false } u, err := url.Parse(str) if err != nil { return false } if strings.HasPrefix(u.Host, ".") { return false } if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { return false } return rxURL.MatchString(str) } // IsRequestURL check if the string rawurl, assuming // it was recieved in an HTTP request, is a valid // URL confirm to RFC 3986 func IsRequestURL(rawurl string) bool { url, err := url.ParseRequestURI(rawurl) if err != nil { return false //Couldn't even parse the rawurl } if len(url.Scheme) == 0 { return false //No Scheme found } return true } // IsRequestURI check if the string rawurl, assuming // it was recieved in an HTTP request, is an // absolute URI or an absolute path. func IsRequestURI(rawurl string) bool { _, err := url.ParseRequestURI(rawurl) return err == nil } // IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid. func IsAlpha(str string) bool { if IsNull(str) { return true } return rxAlpha.MatchString(str) } //IsUTFLetter check if the string contains only unicode letter characters. //Similar to IsAlpha but for all languages. Empty string is valid. func IsUTFLetter(str string) bool { if IsNull(str) { return true } for _, c := range str { if !unicode.IsLetter(c) { return false } } return true } // IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid. func IsAlphanumeric(str string) bool { if IsNull(str) { return true } return rxAlphanumeric.MatchString(str) } // IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid. func IsUTFLetterNumeric(str string) bool { if IsNull(str) { return true } for _, c := range str { if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok return false } } return true } // IsNumeric check if the string contains only numbers. Empty string is valid. func IsNumeric(str string) bool { if IsNull(str) { return true } return rxNumeric.MatchString(str) } // IsUTFNumeric check if the string contains only unicode numbers of any kind. // Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. func IsUTFNumeric(str string) bool { if IsNull(str) { return true } if strings.IndexAny(str, "+-") > 0 { return false } if len(str) > 1 { str = strings.TrimPrefix(str, "-") str = strings.TrimPrefix(str, "+") } for _, c := range str { if unicode.IsNumber(c) == false { //numbers && minus sign are ok return false } } return true } // IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid. func IsUTFDigit(str string) bool { if IsNull(str) { return true } if strings.IndexAny(str, "+-") > 0 { return false } if len(str) > 1 { str = strings.TrimPrefix(str, "-") str = strings.TrimPrefix(str, "+") } for _, c := range str { if !unicode.IsDigit(c) { //digits && minus sign are ok return false } } return true } // IsHexadecimal check if the string is a hexadecimal number. func IsHexadecimal(str string) bool { return rxHexadecimal.MatchString(str) } // IsHexcolor check if the string is a hexadecimal color. func IsHexcolor(str string) bool { return rxHexcolor.MatchString(str) } // IsRGBcolor check if the string is a valid RGB color in form rgb(RRR, GGG, BBB). func IsRGBcolor(str string) bool { return rxRGBcolor.MatchString(str) } // IsLowerCase check if the string is lowercase. Empty string is valid. func IsLowerCase(str string) bool { if IsNull(str) { return true } return str == strings.ToLower(str) } // IsUpperCase check if the string is uppercase. Empty string is valid. func IsUpperCase(str string) bool { if IsNull(str) { return true } return str == strings.ToUpper(str) } // IsInt check if the string is an integer. Empty string is valid. func IsInt(str string) bool { if IsNull(str) { return true } return rxInt.MatchString(str) } // IsFloat check if the string is a float. func IsFloat(str string) bool { return str != "" && rxFloat.MatchString(str) } // IsDivisibleBy check if the string is a number that's divisible by another. // If second argument is not valid integer or zero, it's return false. // Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). func IsDivisibleBy(str, num string) bool { f, _ := ToFloat(str) p := int64(f) q, _ := ToInt(num) if q == 0 { return false } return (p == 0) || (p%q == 0) } // IsNull check if the string is null. func IsNull(str string) bool { return len(str) == 0 } // IsByteLength check if the string's length (in bytes) falls in a range. func IsByteLength(str string, min, max int) bool { return len(str) >= min && len(str) <= max } // IsUUIDv3 check if the string is a UUID version 3. func IsUUIDv3(str string) bool { return rxUUID3.MatchString(str) } // IsUUIDv4 check if the string is a UUID version 4. func IsUUIDv4(str string) bool { return rxUUID4.MatchString(str) } // IsUUIDv5 check if the string is a UUID version 5. func IsUUIDv5(str string) bool { return rxUUID5.MatchString(str) } // IsUUID check if the string is a UUID (version 3, 4 or 5). func IsUUID(str string) bool { return rxUUID.MatchString(str) } // IsCreditCard check if the string is a credit card. func IsCreditCard(str string) bool { r, _ := regexp.Compile("[^0-9]+") sanitized := r.ReplaceAll([]byte(str), []byte("")) if !rxCreditCard.MatchString(string(sanitized)) { return false } var sum int64 var digit string var tmpNum int64 var shouldDouble bool for i := len(sanitized) - 1; i >= 0; i-- { digit = string(sanitized[i:(i + 1)]) tmpNum, _ = ToInt(digit) if shouldDouble { tmpNum *= 2 if tmpNum >= 10 { sum += ((tmpNum % 10) + 1) } else { sum += tmpNum } } else { sum += tmpNum } shouldDouble = !shouldDouble } if sum%10 == 0 { return true } return false } // IsISBN10 check if the string is an ISBN version 10. func IsISBN10(str string) bool { return IsISBN(str, 10) } // IsISBN13 check if the string is an ISBN version 13. func IsISBN13(str string) bool { return IsISBN(str, 13) } // IsISBN check if the string is an ISBN (version 10 or 13). // If version value is not equal to 10 or 13, it will be check both variants. func IsISBN(str string, version int) bool { r, _ := regexp.Compile("[\\s-]+") sanitized := r.ReplaceAll([]byte(str), []byte("")) var checksum int32 var i int32 if version == 10 { if !rxISBN10.MatchString(string(sanitized)) { return false } for i = 0; i < 9; i++ { checksum += (i + 1) * int32(sanitized[i]-'0') } if sanitized[9] == 'X' { checksum += 10 * 10 } else { checksum += 10 * int32(sanitized[9]-'0') } if checksum%11 == 0 { return true } return false } else if version == 13 { if !rxISBN13.MatchString(string(sanitized)) { return false } factor := []int32{1, 3} for i = 0; i < 12; i++ { checksum += factor[i%2] * int32(sanitized[i]-'0') } if (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 { return true } return false } return IsISBN(str, 10) || IsISBN(str, 13) } // IsJSON check if the string is valid JSON (note: uses json.Unmarshal). func IsJSON(str string) bool { var js json.RawMessage return json.Unmarshal([]byte(str), &js) == nil } // IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid. func IsMultibyte(str string) bool { if IsNull(str) { return true } return rxMultibyte.MatchString(str) } // IsASCII check if the string contains ASCII chars only. Empty string is valid. func IsASCII(str string) bool { if IsNull(str) { return true } return rxASCII.MatchString(str) } // IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid. func IsPrintableASCII(str string) bool { if IsNull(str) { return true } return rxPrintableASCII.MatchString(str) } // IsFullWidth check if the string contains any full-width chars. Empty string is valid. func IsFullWidth(str string) bool { if IsNull(str) { return true } return rxFullWidth.MatchString(str) } // IsHalfWidth check if the string contains any half-width chars. Empty string is valid. func IsHalfWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) } // IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid. func IsVariableWidth(str string) bool { if IsNull(str) { return true } return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) } // IsBase64 check if a string is base64 encoded. func IsBase64(str string) bool { return rxBase64.MatchString(str) } // IsFilePath check is a string is Win or Unix file path and returns it's type. func IsFilePath(str string) (bool, int) { if rxWinPath.MatchString(str) { //check windows path limit see: // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath if len(str[3:]) > 32767 { return false, Win } return true, Win } else if rxUnixPath.MatchString(str) { return true, Unix } return false, Unknown } // IsDataURI checks if a string is base64 encoded data URI such as an image func IsDataURI(str string) bool { dataURI := strings.Split(str, ",") if !rxDataURI.MatchString(dataURI[0]) { return false } return IsBase64(dataURI[1]) } // IsISO3166Alpha2 checks if a string is valid two-letter country code func IsISO3166Alpha2(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha2Code { return true } } return false } // IsISO3166Alpha3 checks if a string is valid three-letter country code func IsISO3166Alpha3(str string) bool { for _, entry := range ISO3166List { if str == entry.Alpha3Code { return true } } return false } // IsIP checks if a string is either IP version 4 or 6. func IsIP(str string) bool { return net.ParseIP(str) != nil } // IsIPv4 check if the string is an IP version 4. func IsIPv4(str string) bool { ip := net.ParseIP(str) return ip != nil && strings.Contains(str, ".") } // IsIPv6 check if the string is an IP version 6. func IsIPv6(str string) bool { ip := net.ParseIP(str) return ip != nil && strings.Contains(str, ":") } // IsMAC check if a string is valid MAC address. // Possible MAC formats: // 01:23:45:67:89:ab // 01:23:45:67:89:ab:cd:ef // 01-23-45-67-89-ab // 01-23-45-67-89-ab-cd-ef // 0123.4567.89ab // 0123.4567.89ab.cdef func IsMAC(str string) bool { _, err := net.ParseMAC(str) return err == nil } // IsMongoID check if the string is a valid hex-encoded representation of a MongoDB ObjectId. func IsMongoID(str string) bool { return rxHexadecimal.MatchString(str) && (len(str) == 24) } // IsLatitude check if a string is valid latitude. func IsLatitude(str string) bool { return rxLatitude.MatchString(str) } // IsLongitude check if a string is valid longitude. func IsLongitude(str string) bool { return rxLongitude.MatchString(str) } // ValidateStruct use tags for fields func ValidateStruct(s interface{}) (bool, error) { if s == nil { return true, nil } result := true var err error val := reflect.ValueOf(s) if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { val = val.Elem() } // we only accept structs if val.Kind() != reflect.Struct { return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) } var errs Errors for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) if typeField.PkgPath != "" { continue // Private field } resultField, err := typeCheck(valueField, typeField) if err != nil { errs = append(errs, err) } result = result && resultField } if len(errs) > 0 { err = errs } return result, err } // parseTag splits a struct field's tag into its // comma-separated options. func parseTag(tag string) tagOptions { split := strings.SplitN(tag, ",", -1) return tagOptions(split) } func isValidTag(s string) bool { if s == "" { return false } for _, c := range s { switch { case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): // Backslash and quote chars are reserved, but // otherwise any punctuation chars are allowed // in a tag name. default: if !unicode.IsLetter(c) && !unicode.IsDigit(c) { return false } } } return true } // IsSSN will validate the given string as a U.S. Social Security Number func IsSSN(str string) bool { if str == "" || len(str) != 11 { return false } return rxSSN.MatchString(str) } // ByteLength check string's length func ByteLength(str string, params ...string) bool { if len(params) == 2 { min, _ := ToInt(params[0]) max, _ := ToInt(params[1]) return len(str) >= int(min) && len(str) <= int(max) } return false } // StringMatches checks if a string matches a given pattern. func StringMatches(s string, params ...string) bool { if len(params) == 1 { pattern := params[0] return Matches(s, pattern) } return false } // StringLength check string's length (including multi byte strings) func StringLength(str string, params ...string) bool { if len(params) == 2 { strLength := utf8.RuneCountInString(str) min, _ := ToInt(params[0]) max, _ := ToInt(params[1]) return strLength >= int(min) && strLength <= int(max) } return false } // Contains returns whether checks that a comma-separated list of options // contains a particular substr flag. substr must be surrounded by a // string boundary or commas. func (opts tagOptions) contains(optionName string) bool { for i := range opts { tagOpt := opts[i] if tagOpt == optionName { return true } } return false } func checkRequired(v reflect.Value, t reflect.StructField, options tagOptions) (bool, error) { if options.contains("required") { err := fmt.Errorf("non zero value required") return false, Error{t.Name, err} } else if fieldsRequiredByDefault && !options.contains("optional") { err := fmt.Errorf("All fields are required to at least have one validation defined") return false, Error{t.Name, err} } // not required and empty is valid return true, nil } func typeCheck(v reflect.Value, t reflect.StructField) (bool, error) { if !v.IsValid() { return false, nil } tag := t.Tag.Get(tagName) // Check if the field should be ignored switch tag { case "": if !fieldsRequiredByDefault { return true, nil } err := fmt.Errorf("All fields are required to at least have one validation defined") return false, Error{t.Name, err} case "-": return true, nil } options := parseTag(tag) for i := range options { tagOpt := options[i] if ok := isValidTag(tagOpt); !ok { continue } if validatefunc, ok := CustomTypeTagMap[tagOpt]; ok { options = append(options[:i], options[i+1:]...) // we found our custom validator, so remove it from the options if result := validatefunc(v.Interface()); !result { return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), tagOpt)} } return true, nil } } if isEmptyValue(v) { // an empty value is not validated, check only required return checkRequired(v, t, options) } switch v.Kind() { case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.String: // for each tag option check the map of validator functions for i := range options { tagOpt := options[i] negate := false // Check wether the tag looks like '!something' or 'something' if len(tagOpt) > 0 && tagOpt[0] == '!' { tagOpt = string(tagOpt[1:]) negate = true } if ok := isValidTag(tagOpt); !ok { err := fmt.Errorf("Unknown Validator %s", tagOpt) return false, Error{t.Name, err} } // Check for param validators for key, value := range ParamTagRegexMap { ps := value.FindStringSubmatch(tagOpt) if len(ps) > 0 { if validatefunc, ok := ParamTagMap[key]; ok { switch v.Kind() { case reflect.String: field := fmt.Sprint(v) // make value into string, then validate with regex if result := validatefunc(field, ps[1:]...); !result && !negate || result && negate { var err error if !negate { err = fmt.Errorf("%s does not validate as %s", field, tagOpt) } else { err = fmt.Errorf("%s does validate as %s", field, tagOpt) } return false, Error{t.Name, err} } default: //Not Yet Supported Types (Fail here!) err := fmt.Errorf("Validator %s doesn't support kind %s", tagOpt, v.Kind()) return false, Error{t.Name, err} } } } } if validatefunc, ok := TagMap[tagOpt]; ok { switch v.Kind() { case reflect.String: field := fmt.Sprint(v) // make value into string, then validate with regex if result := validatefunc(field); !result && !negate || result && negate { var err error if !negate { err = fmt.Errorf("%s does not validate as %s", field, tagOpt) } else { err = fmt.Errorf("%s does validate as %s", field, tagOpt) } return false, Error{t.Name, err} } default: //Not Yet Supported Types (Fail here!) err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", tagOpt, v.Kind(), v) return false, Error{t.Name, err} } } } return true, nil case reflect.Map: if v.Type().Key().Kind() != reflect.String { return false, &UnsupportedTypeError{v.Type()} } var sv stringValues sv = v.MapKeys() sort.Sort(sv) result := true for _, k := range sv { resultItem, err := ValidateStruct(v.MapIndex(k).Interface()) if err != nil { return false, err } result = result && resultItem } return result, nil case reflect.Slice: result := true for i := 0; i < v.Len(); i++ { var resultItem bool var err error if v.Index(i).Kind() != reflect.Struct { resultItem, err = typeCheck(v.Index(i), t) if err != nil { return false, err } } else { resultItem, err = ValidateStruct(v.Index(i).Interface()) if err != nil { return false, err } } result = result && resultItem } return result, nil case reflect.Array: result := true for i := 0; i < v.Len(); i++ { var resultItem bool var err error if v.Index(i).Kind() != reflect.Struct { resultItem, err = typeCheck(v.Index(i), t) if err != nil { return false, err } } else { resultItem, err = ValidateStruct(v.Index(i).Interface()) if err != nil { return false, err } } result = result && resultItem } return result, nil case reflect.Interface: // If the value is an interface then encode its element if v.IsNil() { return true, nil } return ValidateStruct(v.Interface()) case reflect.Ptr: // If the value is a pointer then check its element if v.IsNil() { return true, nil } return typeCheck(v.Elem(), t) case reflect.Struct: return ValidateStruct(v.Interface()) default: return false, &UnsupportedTypeError{v.Type()} } } func isEmptyValue(v reflect.Value) bool { switch v.Kind() { case reflect.String, reflect.Array: return v.Len() == 0 case reflect.Map, reflect.Slice: return v.Len() == 0 || v.IsNil() case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: return v.IsNil() } return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) } // ErrorByField returns error for specified field of the struct // validated by ValidateStruct or empty string if there are no errors // or this field doesn't exists or doesn't have any errors. func ErrorByField(e error, field string) string { if e == nil { return "" } return ErrorsByField(e)[field] } // ErrorsByField returns map of errors of the struct validated // by ValidateStruct or empty map if there are no errors. func ErrorsByField(e error) map[string]string { m := make(map[string]string) if e == nil { return m } // prototype for ValidateStruct switch e.(type) { case Error: m[e.(Error).Name] = e.(Error).Err.Error() case Errors: for _, item := range e.(Errors).Errors() { m[item.(Error).Name] = item.(Error).Err.Error() } } return m } // Error returns string equivalent for reflect.Type func (e *UnsupportedTypeError) Error() string { return "validator: unsupported type: " + e.Type.String() } func (sv stringValues) Len() int { return len(sv) } func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } func (sv stringValues) get(i int) string { return sv[i].String() }
aleksandr-vin/go-swagger
vendor/github.com/asaskevich/govalidator/validator.go
GO
apache-2.0
22,585
[ 30522, 1013, 1013, 7427, 18079, 11475, 2850, 4263, 2003, 7427, 1997, 9398, 18926, 1998, 2624, 25090, 16750, 2005, 7817, 1010, 2358, 6820, 16649, 1998, 6407, 1012, 7427, 18079, 11475, 2850, 4263, 12324, 1006, 1000, 17181, 1013, 1046, 3385, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
{$Header} <main role="main" class="main" contenteditable="false"> <aside id="notifications"> <!-- Notifications --> {if !empty($error)}<div class="notification-error">{$error}</div>{/if} {if !empty($success)}<div class="notification-success">{$success}</div>{/if} </aside> <section class="frame"> <header> <section class="box entry-title"> <form method="GET"> <input class="" type="text" name="q" value="{$keyword}" placeholder="Keyword..." /> </form> </section> </header> <section class="entry-container" id="google-trend"> {$GoogleTrendScript} </section> </section> </main>
duyetdev/ypCore
apps/admin/view/simple/module/News/Setting.GoogleTrend.php
PHP
apache-2.0
655
[ 30522, 1063, 1002, 20346, 1065, 1026, 2364, 2535, 1027, 1000, 2364, 1000, 2465, 1027, 1000, 2364, 1000, 4180, 2098, 6590, 3468, 1027, 1000, 6270, 1000, 1028, 1026, 4998, 8909, 1027, 1000, 26828, 2015, 1000, 1028, 1026, 999, 1011, 1011, 26...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * nodeinfo.c: Helper routines for OS specific node information * * Copyright (C) 2006-2008, 2010-2013 Red Hat, Inc. * Copyright (C) 2006 Daniel P. Berrange * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. * * Author: Daniel P. Berrange <berrange@redhat.com> */ #include <config.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <errno.h> #include <dirent.h> #include <sys/utsname.h> #include <sched.h> #include "conf/domain_conf.h" #if WITH_NUMACTL # define NUMA_VERSION1_COMPATIBILITY 1 # include <numa.h> #endif #ifdef __FreeBSD__ # include <sys/types.h> # include <sys/sysctl.h> #endif #include "c-ctype.h" #include "viralloc.h" #include "nodeinfo.h" #include "physmem.h" #include "virlog.h" #include "virerror.h" #include "count-one-bits.h" #include "intprops.h" #include "virarch.h" #include "virfile.h" #include "virtypedparam.h" #include "virstring.h" #define VIR_FROM_THIS VIR_FROM_NONE #ifdef __FreeBSD__ static int freebsdNodeGetCPUCount(void) { int ncpu_mib[2] = { CTL_HW, HW_NCPU }; unsigned long ncpu; size_t ncpu_len = sizeof(ncpu); if (sysctl(ncpu_mib, 2, &ncpu, &ncpu_len, NULL, 0) == -1) { virReportSystemError(errno, "%s", _("Cannot obtain CPU count")); return -1; } return ncpu; } #endif #ifdef __linux__ # define CPUINFO_PATH "/proc/cpuinfo" # define SYSFS_SYSTEM_PATH "/sys/devices/system" # define SYSFS_CPU_PATH SYSFS_SYSTEM_PATH"/cpu" # define PROCSTAT_PATH "/proc/stat" # define MEMINFO_PATH "/proc/meminfo" # define SYSFS_MEMORY_SHARED_PATH "/sys/kernel/mm/ksm" # define SYSFS_THREAD_SIBLINGS_LIST_LENGTH_MAX 1024 # define LINUX_NB_CPU_STATS 4 # define LINUX_NB_MEMORY_STATS_ALL 4 # define LINUX_NB_MEMORY_STATS_CELL 2 /* NB, this is not static as we need to call it from the testsuite */ int linuxNodeInfoCPUPopulate(FILE *cpuinfo, const char *sysfs_dir, virNodeInfoPtr nodeinfo); static int linuxNodeGetCPUStats(FILE *procstat, int cpuNum, virNodeCPUStatsPtr params, int *nparams); static int linuxNodeGetMemoryStats(FILE *meminfo, int cellNum, virNodeMemoryStatsPtr params, int *nparams); /* Return the positive decimal contents of the given * DIR/cpu%u/FILE, or -1 on error. If DEFAULT_VALUE is non-negative * and the file could not be found, return that instead of an error; * this is useful for machines that cannot hot-unplug cpu0, or where * hot-unplugging is disabled, or where the kernel is too old * to support NUMA cells, etc. */ static int virNodeGetCpuValue(const char *dir, unsigned int cpu, const char *file, int default_value) { char *path; FILE *pathfp; int value = -1; char value_str[INT_BUFSIZE_BOUND(value)]; char *tmp; if (virAsprintf(&path, "%s/cpu%u/%s", dir, cpu, file) < 0) return -1; pathfp = fopen(path, "r"); if (pathfp == NULL) { if (default_value >= 0 && errno == ENOENT) value = default_value; else virReportSystemError(errno, _("cannot open %s"), path); goto cleanup; } if (fgets(value_str, sizeof(value_str), pathfp) == NULL) { virReportSystemError(errno, _("cannot read from %s"), path); goto cleanup; } if (virStrToLong_i(value_str, &tmp, 10, &value) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("could not convert '%s' to an integer"), value_str); goto cleanup; } cleanup: VIR_FORCE_FCLOSE(pathfp); VIR_FREE(path); return value; } static unsigned long virNodeCountThreadSiblings(const char *dir, unsigned int cpu) { unsigned long ret = 0; char *path; FILE *pathfp; char str[1024]; size_t i; if (virAsprintf(&path, "%s/cpu%u/topology/thread_siblings", dir, cpu) < 0) return 0; pathfp = fopen(path, "r"); if (pathfp == NULL) { /* If file doesn't exist, then pretend our only * sibling is ourself */ if (errno == ENOENT) { VIR_FREE(path); return 1; } virReportSystemError(errno, _("cannot open %s"), path); VIR_FREE(path); return 0; } if (fgets(str, sizeof(str), pathfp) == NULL) { virReportSystemError(errno, _("cannot read from %s"), path); goto cleanup; } i = 0; while (str[i] != '\0') { if (c_isdigit(str[i])) ret += count_one_bits(str[i] - '0'); else if (str[i] >= 'A' && str[i] <= 'F') ret += count_one_bits(str[i] - 'A' + 10); else if (str[i] >= 'a' && str[i] <= 'f') ret += count_one_bits(str[i] - 'a' + 10); i++; } cleanup: VIR_FORCE_FCLOSE(pathfp); VIR_FREE(path); return ret; } static int virNodeParseSocket(const char *dir, unsigned int cpu) { int ret = virNodeGetCpuValue(dir, cpu, "topology/physical_package_id", 0); # if defined(__powerpc__) || \ defined(__powerpc64__) || \ defined(__s390__) || \ defined(__s390x__) /* ppc and s390(x) has -1 */ if (ret < 0) ret = 0; # endif return ret; } # ifndef CPU_COUNT static int CPU_COUNT(cpu_set_t *set) { size_t i, count = 0; for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, set)) count++; return count; } # endif /* !CPU_COUNT */ /* parses a node entry, returning number of processors in the node and * filling arguments */ static int ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5) virNodeParseNode(const char *node, int *sockets, int *cores, int *threads, int *offline) { int ret = -1; int processors = 0; DIR *cpudir = NULL; struct dirent *cpudirent = NULL; int sock_max = 0; cpu_set_t sock_map; int sock; cpu_set_t *core_maps = NULL; int core; size_t i; int siblings; unsigned int cpu; int online; *threads = 0; *cores = 0; *sockets = 0; if (!(cpudir = opendir(node))) { virReportSystemError(errno, _("cannot opendir %s"), node); goto cleanup; } /* enumerate sockets in the node */ CPU_ZERO(&sock_map); errno = 0; while ((cpudirent = readdir(cpudir))) { if (sscanf(cpudirent->d_name, "cpu%u", &cpu) != 1) continue; if ((online = virNodeGetCpuValue(node, cpu, "online", 1)) < 0) goto cleanup; if (!online) continue; /* Parse socket */ if ((sock = virNodeParseSocket(node, cpu)) < 0) goto cleanup; CPU_SET(sock, &sock_map); if (sock > sock_max) sock_max = sock; errno = 0; } if (errno) { virReportSystemError(errno, _("problem reading %s"), node); goto cleanup; } sock_max++; /* allocate cpu maps for each socket */ if (VIR_ALLOC_N(core_maps, sock_max) < 0) goto cleanup; for (i = 0; i < sock_max; i++) CPU_ZERO(&core_maps[i]); /* iterate over all CPU's in the node */ rewinddir(cpudir); errno = 0; while ((cpudirent = readdir(cpudir))) { if (sscanf(cpudirent->d_name, "cpu%u", &cpu) != 1) continue; if ((online = virNodeGetCpuValue(node, cpu, "online", 1)) < 0) goto cleanup; if (!online) { (*offline)++; continue; } processors++; /* Parse socket */ if ((sock = virNodeParseSocket(node, cpu)) < 0) goto cleanup; if (!CPU_ISSET(sock, &sock_map)) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("CPU socket topology has changed")); goto cleanup; } /* Parse core */ # if defined(__s390__) || \ defined(__s390x__) /* logical cpu is equivalent to a core on s390 */ core = cpu; # else core = virNodeGetCpuValue(node, cpu, "topology/core_id", 0); # endif CPU_SET(core, &core_maps[sock]); if (!(siblings = virNodeCountThreadSiblings(node, cpu))) goto cleanup; if (siblings > *threads) *threads = siblings; errno = 0; } if (errno) { virReportSystemError(errno, _("problem reading %s"), node); goto cleanup; } /* finalize the returned data */ *sockets = CPU_COUNT(&sock_map); for (i = 0; i < sock_max; i++) { if (!CPU_ISSET(i, &sock_map)) continue; core = CPU_COUNT(&core_maps[i]); if (core > *cores) *cores = core; } ret = processors; cleanup: /* don't shadow a more serious error */ if (cpudir && closedir(cpudir) < 0 && ret >= 0) { virReportSystemError(errno, _("problem closing %s"), node); ret = -1; } VIR_FREE(core_maps); return ret; } int linuxNodeInfoCPUPopulate(FILE *cpuinfo, const char *sysfs_dir, virNodeInfoPtr nodeinfo) { char line[1024]; DIR *nodedir = NULL; struct dirent *nodedirent = NULL; int cpus, cores, socks, threads, offline = 0; unsigned int node; int ret = -1; char *sysfs_nodedir = NULL; char *sysfs_cpudir = NULL; /* Start with parsing CPU clock speed from /proc/cpuinfo */ while (fgets(line, sizeof(line), cpuinfo) != NULL) { # if defined(__x86_64__) || \ defined(__amd64__) || \ defined(__i386__) char *buf = line; if (STRPREFIX(buf, "cpu MHz")) { char *p; unsigned int ui; buf += 7; while (*buf && c_isspace(*buf)) buf++; if (*buf != ':' || !buf[1]) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing cpu MHz from cpuinfo")); goto cleanup; } if (virStrToLong_ui(buf+1, &p, 10, &ui) == 0 && /* Accept trailing fractional part. */ (*p == '\0' || *p == '.' || c_isspace(*p))) nodeinfo->mhz = ui; } # elif defined(__powerpc__) || \ defined(__powerpc64__) char *buf = line; if (STRPREFIX(buf, "clock")) { char *p; unsigned int ui; buf += 5; while (*buf && c_isspace(*buf)) buf++; if (*buf != ':' || !buf[1]) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing cpu MHz from cpuinfo")); goto cleanup; } if (virStrToLong_ui(buf+1, &p, 10, &ui) == 0 && /* Accept trailing fractional part. */ (*p == '\0' || *p == '.' || c_isspace(*p))) nodeinfo->mhz = ui; /* No other interesting infos are available in /proc/cpuinfo. * However, there is a line identifying processor's version, * identification and machine, but we don't want it to be caught * and parsed in next iteration, because it is not in expected * format and thus lead to error. */ } # elif defined(__arm__) char *buf = line; if (STRPREFIX(buf, "BogoMIPS")) { char *p; unsigned int ui; buf += 8; while (*buf && c_isspace(*buf)) buf++; if (*buf != ':' || !buf[1]) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing cpu MHz from cpuinfo")); goto cleanup; } if (virStrToLong_ui(buf+1, &p, 10, &ui) == 0 /* Accept trailing fractional part. */ && (*p == '\0' || *p == '.' || c_isspace(*p))) nodeinfo->mhz = ui; } # elif defined(__s390__) || \ defined(__s390x__) /* s390x has no realistic value for CPU speed, * assign a value of zero to signify this */ nodeinfo->mhz = 0; # else # warning Parser for /proc/cpuinfo needs to be adapted for your architecture # endif } /* OK, we've parsed clock speed out of /proc/cpuinfo. Get the * core, node, socket, thread and topology information from /sys */ if (virAsprintf(&sysfs_nodedir, "%s/node", sysfs_dir) < 0) goto cleanup; if (!(nodedir = opendir(sysfs_nodedir))) { /* the host isn't probably running a NUMA architecture */ goto fallback; } errno = 0; while ((nodedirent = readdir(nodedir))) { if (sscanf(nodedirent->d_name, "node%u", &node) != 1) continue; nodeinfo->nodes++; if (virAsprintf(&sysfs_cpudir, "%s/node/%s", sysfs_dir, nodedirent->d_name) < 0) goto cleanup; if ((cpus = virNodeParseNode(sysfs_cpudir, &socks, &cores, &threads, &offline)) < 0) goto cleanup; VIR_FREE(sysfs_cpudir); nodeinfo->cpus += cpus; if (socks > nodeinfo->sockets) nodeinfo->sockets = socks; if (cores > nodeinfo->cores) nodeinfo->cores = cores; if (threads > nodeinfo->threads) nodeinfo->threads = threads; errno = 0; } if (errno) { virReportSystemError(errno, _("problem reading %s"), sysfs_nodedir); goto cleanup; } if (nodeinfo->cpus && nodeinfo->nodes) goto done; fallback: VIR_FREE(sysfs_cpudir); if (virAsprintf(&sysfs_cpudir, "%s/cpu", sysfs_dir) < 0) goto cleanup; if ((cpus = virNodeParseNode(sysfs_cpudir, &socks, &cores, &threads, &offline)) < 0) goto cleanup; nodeinfo->nodes = 1; nodeinfo->cpus = cpus; nodeinfo->sockets = socks; nodeinfo->cores = cores; nodeinfo->threads = threads; done: /* There should always be at least one cpu, socket, node, and thread. */ if (nodeinfo->cpus == 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no CPUs found")); goto cleanup; } if (nodeinfo->sockets == 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no sockets found")); goto cleanup; } if (nodeinfo->threads == 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no threads found")); goto cleanup; } /* Now check if the topology makes sense. There are machines that don't * expose their real number of nodes or for example the AMD Bulldozer * architecture that exposes their Clustered integer core modules as both * threads and cores. This approach throws off our detection. Unfortunately * the nodeinfo structure isn't designed to carry the full topology so * we're going to lie about the detected topology to notify the user * to check the host capabilities for the actual topology. */ if ((nodeinfo->nodes * nodeinfo->sockets * nodeinfo->cores * nodeinfo->threads) != (nodeinfo->cpus + offline)) { nodeinfo->nodes = 1; nodeinfo->sockets = 1; nodeinfo->cores = nodeinfo->cpus + offline; nodeinfo->threads = 1; } ret = 0; cleanup: /* don't shadow a more serious error */ if (nodedir && closedir(nodedir) < 0 && ret >= 0) { virReportSystemError(errno, _("problem closing %s"), sysfs_nodedir); ret = -1; } VIR_FREE(sysfs_nodedir); VIR_FREE(sysfs_cpudir); return ret; } # define TICK_TO_NSEC (1000ull * 1000ull * 1000ull / sysconf(_SC_CLK_TCK)) int linuxNodeGetCPUStats(FILE *procstat, int cpuNum, virNodeCPUStatsPtr params, int *nparams) { int ret = -1; char line[1024]; unsigned long long usr, ni, sys, idle, iowait; unsigned long long irq, softirq, steal, guest, guest_nice; char cpu_header[3 + INT_BUFSIZE_BOUND(cpuNum)]; if ((*nparams) == 0) { /* Current number of cpu stats supported by linux */ *nparams = LINUX_NB_CPU_STATS; ret = 0; goto cleanup; } if ((*nparams) != LINUX_NB_CPU_STATS) { virReportInvalidArg(*nparams, _("nparams in %s must be equal to %d"), __FUNCTION__, LINUX_NB_CPU_STATS); goto cleanup; } if (cpuNum == VIR_NODE_CPU_STATS_ALL_CPUS) { strcpy(cpu_header, "cpu"); } else { snprintf(cpu_header, sizeof(cpu_header), "cpu%d", cpuNum); } while (fgets(line, sizeof(line), procstat) != NULL) { char *buf = line; if (STRPREFIX(buf, cpu_header)) { /* aka logical CPU time */ size_t i; if (sscanf(buf, "%*s %llu %llu %llu %llu %llu" // user ~ iowait "%llu %llu %llu %llu %llu", // irq ~ guest_nice &usr, &ni, &sys, &idle, &iowait, &irq, &softirq, &steal, &guest, &guest_nice) < 4) { continue; } for (i = 0; i < *nparams; i++) { virNodeCPUStatsPtr param = &params[i]; switch (i) { case 0: /* fill kernel cpu time here */ if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_KERNEL) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Field kernel cpu time too long for destination")); goto cleanup; } param->value = (sys + irq + softirq) * TICK_TO_NSEC; break; case 1: /* fill user cpu time here */ if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_USER) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Field kernel cpu time too long for destination")); goto cleanup; } param->value = (usr + ni) * TICK_TO_NSEC; break; case 2: /* fill idle cpu time here */ if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_IDLE) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Field kernel cpu time too long for destination")); goto cleanup; } param->value = idle * TICK_TO_NSEC; break; case 3: /* fill iowait cpu time here */ if (virStrcpyStatic(param->field, VIR_NODE_CPU_STATS_IOWAIT) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Field kernel cpu time too long for destination")); goto cleanup; } param->value = iowait * TICK_TO_NSEC; break; default: break; /* should not hit here */ } } ret = 0; goto cleanup; } } virReportInvalidArg(cpuNum, _("Invalid cpuNum in %s"), __FUNCTION__); cleanup: return ret; } int linuxNodeGetMemoryStats(FILE *meminfo, int cellNum, virNodeMemoryStatsPtr params, int *nparams) { int ret = -1; size_t i = 0, j = 0, k = 0; int found = 0; int nr_param; char line[1024]; char meminfo_hdr[VIR_NODE_MEMORY_STATS_FIELD_LENGTH]; unsigned long val; struct field_conv { const char *meminfo_hdr; // meminfo header const char *field; // MemoryStats field name } field_conv[] = { {"MemTotal:", VIR_NODE_MEMORY_STATS_TOTAL}, {"MemFree:", VIR_NODE_MEMORY_STATS_FREE}, {"Buffers:", VIR_NODE_MEMORY_STATS_BUFFERS}, {"Cached:", VIR_NODE_MEMORY_STATS_CACHED}, {NULL, NULL} }; if (cellNum == VIR_NODE_MEMORY_STATS_ALL_CELLS) { nr_param = LINUX_NB_MEMORY_STATS_ALL; } else { nr_param = LINUX_NB_MEMORY_STATS_CELL; } if ((*nparams) == 0) { /* Current number of memory stats supported by linux */ *nparams = nr_param; ret = 0; goto cleanup; } if ((*nparams) != nr_param) { virReportInvalidArg(nparams, _("nparams in %s must be %d"), __FUNCTION__, nr_param); goto cleanup; } while (fgets(line, sizeof(line), meminfo) != NULL) { char *buf = line; if (STRPREFIX(buf, "Node ")) { /* * /sys/devices/system/node/nodeX/meminfo format is below. * So, skip prefix "Node XX ". * * Node 0 MemTotal: 8386980 kB * Node 0 MemFree: 5300920 kB * : */ char *p; p = buf; for (i = 0; i < 2; i++) { p = strchr(p, ' '); if (p == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no prefix found")); goto cleanup; } p++; } buf = p; } if (sscanf(buf, "%s %lu kB", meminfo_hdr, &val) < 2) continue; for (j = 0; field_conv[j].meminfo_hdr != NULL; j++) { struct field_conv *convp = &field_conv[j]; if (STREQ(meminfo_hdr, convp->meminfo_hdr)) { virNodeMemoryStatsPtr param = &params[k++]; if (virStrcpyStatic(param->field, convp->field) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Field kernel memory too long for destination")); goto cleanup; } param->value = val; found++; break; } } if (found >= nr_param) break; } if (found == 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("no available memory line found")); goto cleanup; } ret = 0; cleanup: return ret; } /* Determine the maximum cpu id from a Linux sysfs cpu/present file. */ static int linuxParseCPUmax(const char *path) { char *str = NULL; char *tmp; int ret = -1; if (virFileReadAll(path, 5 * VIR_DOMAIN_CPUMASK_LEN, &str) < 0) goto cleanup; tmp = str; do { if (virStrToLong_i(tmp, &tmp, 10, &ret) < 0 || !strchr(",-\n", *tmp)) { virReportError(VIR_ERR_NO_SUPPORT, _("failed to parse %s"), path); ret = -1; goto cleanup; } } while (*tmp++ != '\n'); ret++; cleanup: VIR_FREE(str); return ret; } /* * Linux maintains cpu bit map under cpu/online. For example, if * cpuid=5's flag is not set and max cpu is 7, the map file shows * 0-4,6-7. This function parses it and returns cpumap. */ static virBitmapPtr linuxParseCPUmap(int max_cpuid, const char *path) { virBitmapPtr map = NULL; char *str = NULL; if (virFileReadAll(path, 5 * VIR_DOMAIN_CPUMASK_LEN, &str) < 0) goto error; if (virBitmapParse(str, 0, &map, max_cpuid) < 0) goto error; VIR_FREE(str); return map; error: VIR_FREE(str); virBitmapFree(map); return NULL; } #endif int nodeGetInfo(virNodeInfoPtr nodeinfo) { virArch hostarch = virArchFromHost(); memset(nodeinfo, 0, sizeof(*nodeinfo)); if (virStrcpyStatic(nodeinfo->model, virArchToString(hostarch)) == NULL) return -1; #ifdef __linux__ { int ret = -1; FILE *cpuinfo = fopen(CPUINFO_PATH, "r"); if (!cpuinfo) { virReportSystemError(errno, _("cannot open %s"), CPUINFO_PATH); return -1; } ret = linuxNodeInfoCPUPopulate(cpuinfo, SYSFS_SYSTEM_PATH, nodeinfo); if (ret < 0) goto cleanup; /* Convert to KB. */ nodeinfo->memory = physmem_total() / 1024; cleanup: VIR_FORCE_FCLOSE(cpuinfo); return ret; } #elif defined(__FreeBSD__) { nodeinfo->nodes = 1; nodeinfo->sockets = 1; nodeinfo->threads = 1; nodeinfo->cpus = freebsdNodeGetCPUCount(); if (nodeinfo->cpus == -1) return -1; nodeinfo->cores = nodeinfo->cpus; unsigned long cpu_freq; size_t cpu_freq_len = sizeof(cpu_freq); if (sysctlbyname("dev.cpu.0.freq", &cpu_freq, &cpu_freq_len, NULL, 0) < 0) { virReportSystemError(errno, "%s", _("cannot obtain CPU freq")); return -1; } nodeinfo->mhz = cpu_freq; /* get memory information */ int mib[2] = { CTL_HW, HW_PHYSMEM }; unsigned long physmem; size_t len = sizeof(physmem); if (sysctl(mib, 2, &physmem, &len, NULL, 0) == -1) { virReportSystemError(errno, "%s", _("cannot obtain memory size")); return -1; } nodeinfo->memory = (unsigned long)(physmem / 1024); return 0; } #else /* XXX Solaris will need an impl later if they port QEMU driver */ virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node info not implemented on this platform")); return -1; #endif } int nodeGetCPUStats(int cpuNum ATTRIBUTE_UNUSED, virNodeCPUStatsPtr params ATTRIBUTE_UNUSED, int *nparams ATTRIBUTE_UNUSED, unsigned int flags) { virCheckFlags(0, -1); #ifdef __linux__ { int ret; FILE *procstat = fopen(PROCSTAT_PATH, "r"); if (!procstat) { virReportSystemError(errno, _("cannot open %s"), PROCSTAT_PATH); return -1; } ret = linuxNodeGetCPUStats(procstat, cpuNum, params, nparams); VIR_FORCE_FCLOSE(procstat); return ret; } #else virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node CPU stats not implemented on this platform")); return -1; #endif } int nodeGetMemoryStats(int cellNum ATTRIBUTE_UNUSED, virNodeMemoryStatsPtr params ATTRIBUTE_UNUSED, int *nparams ATTRIBUTE_UNUSED, unsigned int flags) { virCheckFlags(0, -1); #ifdef __linux__ { int ret; char *meminfo_path = NULL; FILE *meminfo; if (cellNum == VIR_NODE_MEMORY_STATS_ALL_CELLS) { if (VIR_STRDUP(meminfo_path, MEMINFO_PATH) < 0) return -1; } else { # if WITH_NUMACTL if (numa_available() < 0) { # endif virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("NUMA not supported on this host")); return -1; # if WITH_NUMACTL } # endif # if WITH_NUMACTL if (cellNum > numa_max_node()) { virReportInvalidArg(cellNum, _("cellNum in %s must be less than or equal to %d"), __FUNCTION__, numa_max_node()); return -1; } # endif if (virAsprintf(&meminfo_path, "%s/node/node%d/meminfo", SYSFS_SYSTEM_PATH, cellNum) < 0) return -1; } meminfo = fopen(meminfo_path, "r"); if (!meminfo) { virReportSystemError(errno, _("cannot open %s"), meminfo_path); VIR_FREE(meminfo_path); return -1; } ret = linuxNodeGetMemoryStats(meminfo, cellNum, params, nparams); VIR_FORCE_FCLOSE(meminfo); VIR_FREE(meminfo_path); return ret; } #else virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node memory stats not implemented on this platform")); return -1; #endif } int nodeGetCPUCount(void) { #if defined(__linux__) /* To support older kernels that lack cpu/present, such as 2.6.18 * in RHEL5, we fall back to count cpu/cpuNN entries; this assumes * that such kernels also lack hotplug, and therefore cpu/cpuNN * will be consecutive. */ char *cpupath = NULL; int ncpu; if (virFileExists(SYSFS_SYSTEM_PATH "/cpu/present")) { ncpu = linuxParseCPUmax(SYSFS_SYSTEM_PATH "/cpu/present"); } else if (virFileExists(SYSFS_SYSTEM_PATH "/cpu/cpu0")) { ncpu = 0; do { ncpu++; VIR_FREE(cpupath); if (virAsprintf(&cpupath, "%s/cpu/cpu%d", SYSFS_SYSTEM_PATH, ncpu) < 0) return -1; } while (virFileExists(cpupath)); } else { /* no cpu/cpu0: we give up */ virReportError(VIR_ERR_NO_SUPPORT, "%s", _("host cpu counting not supported on this node")); return -1; } VIR_FREE(cpupath); return ncpu; #elif defined(__FreeBSD__) return freebsdNodeGetCPUCount(); #else virReportError(VIR_ERR_NO_SUPPORT, "%s", _("host cpu counting not implemented on this platform")); return -1; #endif } virBitmapPtr nodeGetCPUBitmap(int *max_id ATTRIBUTE_UNUSED) { #ifdef __linux__ virBitmapPtr cpumap; int present; present = nodeGetCPUCount(); if (present < 0) return NULL; if (virFileExists(SYSFS_SYSTEM_PATH "/cpu/online")) { cpumap = linuxParseCPUmap(present, SYSFS_SYSTEM_PATH "/cpu/online"); } else { size_t i; cpumap = virBitmapNew(present); if (!cpumap) return NULL; for (i = 0; i < present; i++) { int online = virNodeGetCpuValue(SYSFS_SYSTEM_PATH, i, "online", 1); if (online < 0) { virBitmapFree(cpumap); return NULL; } if (online) ignore_value(virBitmapSetBit(cpumap, i)); } } if (max_id && cpumap) *max_id = present; return cpumap; #else virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node cpumap not implemented on this platform")); return NULL; #endif } #ifdef __linux__ static int nodeSetMemoryParameterValue(virTypedParameterPtr param) { char *path = NULL; char *strval = NULL; int ret = -1; int rc = -1; char *field = strchr(param->field, '_'); sa_assert(field); field++; if (virAsprintf(&path, "%s/%s", SYSFS_MEMORY_SHARED_PATH, field) < 0) { ret = -2; goto cleanup; } if (virAsprintf(&strval, "%u", param->value.ui) == -1) { ret = -2; goto cleanup; } if ((rc = virFileWriteStr(path, strval, 0)) < 0) { virReportSystemError(-rc, _("failed to set %s"), param->field); goto cleanup; } ret = 0; cleanup: VIR_FREE(path); VIR_FREE(strval); return ret; } static bool nodeMemoryParametersIsAllSupported(virTypedParameterPtr params, int nparams) { char *path = NULL; size_t i; for (i = 0; i < nparams; i++) { virTypedParameterPtr param = &params[i]; char *field = strchr(param->field, '_'); sa_assert(field); field++; if (virAsprintf(&path, "%s/%s", SYSFS_MEMORY_SHARED_PATH, field) < 0) return false; if (!virFileExists(path)) { virReportError(VIR_ERR_OPERATION_INVALID, _("Parameter '%s' is not supported by " "this kernel"), param->field); VIR_FREE(path); return false; } VIR_FREE(path); } return true; } #endif int nodeSetMemoryParameters(virTypedParameterPtr params ATTRIBUTE_UNUSED, int nparams ATTRIBUTE_UNUSED, unsigned int flags) { virCheckFlags(0, -1); #ifdef __linux__ size_t i; int rc; if (virTypedParamsValidate(params, nparams, VIR_NODE_MEMORY_SHARED_PAGES_TO_SCAN, VIR_TYPED_PARAM_UINT, VIR_NODE_MEMORY_SHARED_SLEEP_MILLISECS, VIR_TYPED_PARAM_UINT, VIR_NODE_MEMORY_SHARED_MERGE_ACROSS_NODES, VIR_TYPED_PARAM_UINT, NULL) < 0) return -1; if (!nodeMemoryParametersIsAllSupported(params, nparams)) return -1; for (i = 0; i < nparams; i++) { rc = nodeSetMemoryParameterValue(&params[i]); /* Out of memory */ if (rc == -2) return -1; } return 0; #else virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node set memory parameters not implemented" " on this platform")); return -1; #endif } #ifdef __linux__ static int nodeGetMemoryParameterValue(const char *field, void *value) { char *path = NULL; char *buf = NULL; char *tmp = NULL; int ret = -1; int rc = -1; if (virAsprintf(&path, "%s/%s", SYSFS_MEMORY_SHARED_PATH, field) < 0) goto cleanup; if (!virFileExists(path)) { ret = -2; goto cleanup; } if (virFileReadAll(path, 1024, &buf) < 0) goto cleanup; if ((tmp = strchr(buf, '\n'))) *tmp = '\0'; if (STREQ(field, "pages_to_scan") || STREQ(field, "sleep_millisecs") || STREQ(field, "merge_across_nodes")) rc = virStrToLong_ui(buf, NULL, 10, (unsigned int *)value); else if (STREQ(field, "pages_shared") || STREQ(field, "pages_sharing") || STREQ(field, "pages_unshared") || STREQ(field, "pages_volatile") || STREQ(field, "full_scans")) rc = virStrToLong_ull(buf, NULL, 10, (unsigned long long *)value); if (rc < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("failed to parse %s"), field); goto cleanup; } ret = 0; cleanup: VIR_FREE(path); VIR_FREE(buf); return ret; } #endif #define NODE_MEMORY_PARAMETERS_NUM 8 int nodeGetMemoryParameters(virTypedParameterPtr params ATTRIBUTE_UNUSED, int *nparams ATTRIBUTE_UNUSED, unsigned int flags) { virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1); #ifdef __linux__ unsigned int pages_to_scan; unsigned int sleep_millisecs; unsigned int merge_across_nodes; unsigned long long pages_shared; unsigned long long pages_sharing; unsigned long long pages_unshared; unsigned long long pages_volatile; unsigned long long full_scans = 0; size_t i; int ret; if ((*nparams) == 0) { *nparams = NODE_MEMORY_PARAMETERS_NUM; return 0; } for (i = 0; i < *nparams && i < NODE_MEMORY_PARAMETERS_NUM; i++) { virTypedParameterPtr param = &params[i]; switch (i) { case 0: ret = nodeGetMemoryParameterValue("pages_to_scan", &pages_to_scan); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_PAGES_TO_SCAN, VIR_TYPED_PARAM_UINT, pages_to_scan) < 0) return -1; break; case 1: ret = nodeGetMemoryParameterValue("sleep_millisecs", &sleep_millisecs); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_SLEEP_MILLISECS, VIR_TYPED_PARAM_UINT, sleep_millisecs) < 0) return -1; break; case 2: ret = nodeGetMemoryParameterValue("pages_shared", &pages_shared); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_PAGES_SHARED, VIR_TYPED_PARAM_ULLONG, pages_shared) < 0) return -1; break; case 3: ret = nodeGetMemoryParameterValue("pages_sharing", &pages_sharing); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_PAGES_SHARING, VIR_TYPED_PARAM_ULLONG, pages_sharing) < 0) return -1; break; case 4: ret = nodeGetMemoryParameterValue("pages_unshared", &pages_unshared); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_PAGES_UNSHARED, VIR_TYPED_PARAM_ULLONG, pages_unshared) < 0) return -1; break; case 5: ret = nodeGetMemoryParameterValue("pages_volatile", &pages_volatile); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_PAGES_VOLATILE, VIR_TYPED_PARAM_ULLONG, pages_volatile) < 0) return -1; break; case 6: ret = nodeGetMemoryParameterValue("full_scans", &full_scans); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_FULL_SCANS, VIR_TYPED_PARAM_ULLONG, full_scans) < 0) return -1; break; case 7: ret = nodeGetMemoryParameterValue("merge_across_nodes", &merge_across_nodes); if (ret == -2) continue; else if (ret == -1) return -1; if (virTypedParameterAssign(param, VIR_NODE_MEMORY_SHARED_MERGE_ACROSS_NODES, VIR_TYPED_PARAM_UINT, merge_across_nodes) < 0) return -1; break; /* coverity[dead_error_begin] */ default: break; } } return 0; #else virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node get memory parameters not implemented" " on this platform")); return -1; #endif } int nodeGetCPUMap(unsigned char **cpumap, unsigned int *online, unsigned int flags) { virBitmapPtr cpus = NULL; int maxpresent; int ret = -1; int dummy; virCheckFlags(0, -1); if (!cpumap && !online) return nodeGetCPUCount(); if (!(cpus = nodeGetCPUBitmap(&maxpresent))) goto cleanup; if (cpumap && virBitmapToData(cpus, cpumap, &dummy) < 0) goto cleanup; if (online) *online = virBitmapCountBits(cpus); ret = maxpresent; cleanup: if (ret < 0 && cpumap) VIR_FREE(*cpumap); virBitmapFree(cpus); return ret; } static int nodeCapsInitNUMAFake(virCapsPtr caps ATTRIBUTE_UNUSED) { virNodeInfo nodeinfo; virCapsHostNUMACellCPUPtr cpus; int ncpus; int s, c, t; int id; if (nodeGetInfo(&nodeinfo) < 0) return -1; ncpus = VIR_NODEINFO_MAXCPUS(nodeinfo); if (VIR_ALLOC_N(cpus, ncpus) < 0) return -1; id = 0; for (s = 0; s < nodeinfo.sockets; s++) { for (c = 0; c < nodeinfo.cores; c++) { for (t = 0; t < nodeinfo.threads; t++) { cpus[id].id = id; cpus[id].socket_id = s; cpus[id].core_id = c; if (!(cpus[id].siblings = virBitmapNew(ncpus))) goto error; ignore_value(virBitmapSetBit(cpus[id].siblings, id)); id++; } } } if (virCapabilitiesAddHostNUMACell(caps, 0, ncpus, nodeinfo.memory, cpus) < 0) goto error; return 0; error: for (; id >= 0; id--) virBitmapFree(cpus[id].siblings); VIR_FREE(cpus); return -1; } static int nodeGetCellsFreeMemoryFake(unsigned long long *freeMems, int startCell, int maxCells ATTRIBUTE_UNUSED) { double avail = physmem_available(); if (startCell != 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("start cell %d out of range (0-%d)"), startCell, 0); return -1; } freeMems[0] = (unsigned long long)avail; if (!freeMems[0]) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Cannot determine free memory")); return -1; } return 1; } static unsigned long long nodeGetFreeMemoryFake(void) { double avail = physmem_available(); unsigned long long ret; if (!(ret = (unsigned long long)avail)) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Cannot determine free memory")); return 0; } return ret; } #if WITH_NUMACTL # if LIBNUMA_API_VERSION <= 1 # define NUMA_MAX_N_CPUS 4096 # else # define NUMA_MAX_N_CPUS (numa_all_cpus_ptr->size) # endif # define n_bits(var) (8 * sizeof(var)) # define MASK_CPU_ISSET(mask, cpu) \ (((mask)[((cpu) / n_bits(*(mask)))] >> ((cpu) % n_bits(*(mask)))) & 1) static unsigned long long nodeGetCellMemory(int cell); static virBitmapPtr virNodeGetSiblingsList(const char *dir, int cpu_id) { char *path = NULL; char *buf = NULL; virBitmapPtr ret = NULL; if (virAsprintf(&path, "%s/cpu%u/topology/thread_siblings_list", dir, cpu_id) < 0) goto cleanup; if (virFileReadAll(path, SYSFS_THREAD_SIBLINGS_LIST_LENGTH_MAX, &buf) < 0) goto cleanup; if (virBitmapParse(buf, 0, &ret, NUMA_MAX_N_CPUS) < 0) goto cleanup; cleanup: VIR_FREE(buf); VIR_FREE(path); return ret; } /* returns 1 on success, 0 if the detection failed and -1 on hard error */ static int virNodeCapsFillCPUInfo(int cpu_id, virCapsHostNUMACellCPUPtr cpu) { int tmp; cpu->id = cpu_id; if ((tmp = virNodeGetCpuValue(SYSFS_CPU_PATH, cpu_id, "topology/physical_package_id", -1)) < 0) return 0; cpu->socket_id = tmp; if ((tmp = virNodeGetCpuValue(SYSFS_CPU_PATH, cpu_id, "topology/core_id", -1)) < 0) return 0; cpu->core_id = tmp; if (!(cpu->siblings = virNodeGetSiblingsList(SYSFS_CPU_PATH, cpu_id))) return -1; return 0; } int nodeCapsInitNUMA(virCapsPtr caps) { int n; unsigned long *mask = NULL; unsigned long *allonesmask = NULL; unsigned long long memory; virCapsHostNUMACellCPUPtr cpus = NULL; int ret = -1; int max_n_cpus = NUMA_MAX_N_CPUS; int ncpus = 0; bool topology_failed = false; if (numa_available() < 0) return nodeCapsInitNUMAFake(caps); int mask_n_bytes = max_n_cpus / 8; if (VIR_ALLOC_N(mask, mask_n_bytes / sizeof(*mask)) < 0) goto cleanup; if (VIR_ALLOC_N(allonesmask, mask_n_bytes / sizeof(*mask)) < 0) goto cleanup; memset(allonesmask, 0xff, mask_n_bytes); for (n = 0; n <= numa_max_node(); n++) { size_t i; /* The first time this returns -1, ENOENT if node doesn't exist... */ if (numa_node_to_cpus(n, mask, mask_n_bytes) < 0) { VIR_WARN("NUMA topology for cell %d of %d not available, ignoring", n, numa_max_node()+1); continue; } /* second, third... times it returns an all-1's mask */ if (memcmp(mask, allonesmask, mask_n_bytes) == 0) { VIR_DEBUG("NUMA topology for cell %d of %d is all ones, ignoring", n, numa_max_node()+1); continue; } /* Detect the amount of memory in the numa cell */ memory = nodeGetCellMemory(n); for (ncpus = 0, i = 0; i < max_n_cpus; i++) if (MASK_CPU_ISSET(mask, i)) ncpus++; if (VIR_ALLOC_N(cpus, ncpus) < 0) goto cleanup; for (ncpus = 0, i = 0; i < max_n_cpus; i++) { if (MASK_CPU_ISSET(mask, i)) { if (virNodeCapsFillCPUInfo(i, cpus + ncpus++) < 0) { topology_failed = true; virResetLastError(); } } } if (virCapabilitiesAddHostNUMACell(caps, n, ncpus, memory, cpus) < 0) goto cleanup; } ret = 0; cleanup: if (topology_failed || ret < 0) virCapabilitiesClearHostNUMACellCPUTopology(cpus, ncpus); if (ret < 0) VIR_FREE(cpus); VIR_FREE(mask); VIR_FREE(allonesmask); return ret; } int nodeGetCellsFreeMemory(unsigned long long *freeMems, int startCell, int maxCells) { int n, lastCell, numCells; int ret = -1; int maxCell; if (numa_available() < 0) return nodeGetCellsFreeMemoryFake(freeMems, startCell, maxCells); maxCell = numa_max_node(); if (startCell > maxCell) { virReportError(VIR_ERR_INTERNAL_ERROR, _("start cell %d out of range (0-%d)"), startCell, maxCell); goto cleanup; } lastCell = startCell + maxCells - 1; if (lastCell > maxCell) lastCell = maxCell; for (numCells = 0, n = startCell; n <= lastCell; n++) { long long mem; if (numa_node_size64(n, &mem) < 0) mem = 0; freeMems[numCells++] = mem; } ret = numCells; cleanup: return ret; } unsigned long long nodeGetFreeMemory(void) { unsigned long long freeMem = 0; int n; if (numa_available() < 0) return nodeGetFreeMemoryFake(); for (n = 0; n <= numa_max_node(); n++) { long long mem; if (numa_node_size64(n, &mem) < 0) continue; freeMem += mem; } return freeMem; } /** * nodeGetCellMemory * @cell: The number of the numa cell to get memory info for. * * Will call the numa_node_size64() function from libnuma to get * the amount of total memory in bytes. It is then converted to * KiB and returned. * * Returns 0 if unavailable, amount of memory in KiB on success. */ static unsigned long long nodeGetCellMemory(int cell) { long long mem; unsigned long long memKiB = 0; int maxCell; /* Make sure the provided cell number is valid. */ maxCell = numa_max_node(); if (cell > maxCell) { virReportError(VIR_ERR_INTERNAL_ERROR, _("cell %d out of range (0-%d)"), cell, maxCell); goto cleanup; } /* Get the amount of memory(bytes) in the node */ mem = numa_node_size64(cell, NULL); if (mem < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Failed to query NUMA total memory for node: %d"), cell); goto cleanup; } /* Convert the memory from bytes to KiB */ memKiB = mem >> 10; cleanup: return memKiB; } #else int nodeCapsInitNUMA(virCapsPtr caps) { return nodeCapsInitNUMAFake(caps); } int nodeGetCellsFreeMemory(unsigned long long *freeMems, int startCell, int maxCells) { return nodeGetCellsFreeMemoryFake(freeMems, startCell, maxCells); } unsigned long long nodeGetFreeMemory(void) { return nodeGetFreeMemoryFake(); } #endif
hw-claudio/libvirt
src/nodeinfo.c
C
gpl-2.0
49,254
[ 30522, 1013, 1008, 1008, 13045, 2378, 14876, 1012, 1039, 1024, 2393, 2121, 23964, 2005, 9808, 3563, 13045, 2592, 1008, 1008, 9385, 1006, 1039, 1007, 2294, 1011, 2263, 1010, 2230, 1011, 2286, 2417, 6045, 1010, 4297, 1012, 1008, 9385, 1006, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright 2013 David Axmark Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.mosync.pim; import static com.mosync.internal.android.MoSyncHelpers.DebugPrint; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_BUFFER_INVALID; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_FIELD_COUNT_MAX; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_FIELD_EMPTY; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_FIELD_READ_ONLY; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_FIELD_WRITE_ONLY; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_INDEX_INVALID; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_NONE; import static com.mosync.internal.generated.IX_PIM.MA_PIM_ERR_NO_LABEL; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.provider.ContactsContract.Data; import com.mosync.api.Pointer; import com.mosync.internal.android.MoSyncError; import com.mosync.internal.android.MoSyncThread; import com.mosync.internal.android.extensions.StringType; abstract class PIMField { protected static final String DUMMY = Data.DATA15; protected int MAX_SIZE; enum State { NONE, ADDED, UPDATED } enum Permission { FULL, READ_ONLY, WRITE_ONLY } int mType; String mStrType; int mDataType; Permission mPermission; String[] mNames; ArrayList<String[]> mValues; ArrayList<State> mStates; ArrayList<Long> mDeletedValues; Map<Integer, Integer> mAttributes; PIMField() { MAX_SIZE = Integer.MAX_VALUE; mValues = new ArrayList<String[]>(); mStates = new ArrayList<State>(); mDeletedValues = new ArrayList<Long>(); mAttributes = new HashMap<Integer, Integer>(); mPermission = Permission.FULL; createMaps(); } abstract void createMaps(); /** * @param errorCode * The error code returned by the syscall. * @param panicCode * The panic code for this error. * @param panicText * The panic text for this error. * @return */ public int throwError(int errorCode, int panicCode, String panicText) { return MoSyncError.getSingletonObject().error(errorCode, panicCode, panicText); } /** * Read field * @param cr * @param contactId */ void read(ContentResolver cr, String contactId) { DebugPrint("PIMField.read(" + cr + ", " + contactId + ")"); Cursor cursor = cr.query(Data.CONTENT_URI, mNames, Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "=?", new String[] { String.valueOf(contactId), mStrType }, null); while (cursor.moveToNext()) { String[] val = new String[mNames.length]; for (int i = 0; i < mNames.length; i++) { if (!mNames[i].equals(DUMMY)) { int index = cursor.getColumnIndex(mNames[i]); if (index >= 0) { val[i] = cursor.getString(index); } } if (val[i] == null) { val[i] = new String(""); } } mValues.add(val); mStates.add(State.NONE); } cursor.close(); cursor = null; preProcessData(); print(); } void preProcessData() { } abstract void print(); boolean isEmpty() { return ((length() == 0) ? true : false); } int getType() { return mType; } int length() { return mValues.size(); } /** * Get field's attributes. */ int getAttributes(int index) { if (isEmpty()) { return throwError(MA_PIM_ERR_FIELD_EMPTY, PIMError.PANIC_FIELD_EMPTY, PIMError.sStrFieldEmpty); } if ((index < 0) || (index >= length())) { return throwError(MA_PIM_ERR_INDEX_INVALID, PIMError.PANIC_INDEX_INVALID, PIMError.sStrIndexInvalid); } int attr = getAndroidAttribute(index); if (attr < 0) { return 0; } int ret = ((Integer) PIMUtil.getKeyFromValue(mAttributes, attr)) .intValue(); ret |= checkForPreferredAttribute(index); return ret; } abstract int checkForPreferredAttribute(int index); /** * Gets the field attribute. */ abstract int getAndroidAttribute(int index); /** * Gets the custom label of the specified field. */ int getLabel(int index, int buffPointer, int buffSize) { if (isEmpty()) { return throwError(MA_PIM_ERR_FIELD_EMPTY, PIMError.PANIC_FIELD_EMPTY, PIMError.sStrFieldEmpty); } if ((index < 0) || (index >= length())) { return throwError(MA_PIM_ERR_INDEX_INVALID, PIMError.PANIC_INDEX_INVALID, PIMError.sStrIndexInvalid); } if (!hasCustomLabel(index)) { return MA_PIM_ERR_NO_LABEL; } char[] buffer = getLabel(index); if (buffer.length > (buffSize >> 1)) return (buffer.length << 1); StringType.marshalWString(buffPointer, new String(buffer), buffer.length); return buffer.length; } /** * Gets the field's custom label. * @param index * @return */ abstract char[] getLabel(int index); /** * Sets the custom label of the specified field. */ int setLabel(int index, int buffPointer, int buffSize) { DebugPrint("PIMField.setLabel(" + index + ", " + buffPointer + ", " + buffSize + ")"); if (isEmpty()) { return throwError(MA_PIM_ERR_FIELD_EMPTY, PIMError.PANIC_FIELD_EMPTY, PIMError.sStrFieldEmpty); } if ((index < 0) || (index >= length())) { return throwError(MA_PIM_ERR_INDEX_INVALID, PIMError.PANIC_INDEX_INVALID, PIMError.sStrIndexInvalid); } if (isReadOnly()) { return MA_PIM_ERR_FIELD_READ_ONLY; } if (!hasCustomLabel(index)) { return MA_PIM_ERR_NO_LABEL; } String str = StringType.unmarshalWString(buffPointer, buffSize); setLabel(index, str); return MA_PIM_ERR_NONE; } /** * Gets the field's custom label. * @param index * @return */ abstract void setLabel(int index, String label); /** * Checks to see if the given field has a custom label. * @param index */ abstract boolean hasCustomLabel(int index); /** * Gets the value of the specified field. */ int getValue(int index, int buffAddr, int buffSize) { if (isEmpty()) { return throwError(MA_PIM_ERR_FIELD_EMPTY, PIMError.PANIC_FIELD_EMPTY, PIMError.sStrFieldEmpty); } if ((index < 0) || (index >= length())) { return throwError(MA_PIM_ERR_INDEX_INVALID, PIMError.PANIC_INDEX_INVALID, PIMError.sStrIndexInvalid); } if (isWriteOnly()) { return MA_PIM_ERR_FIELD_WRITE_ONLY; } byte[] data = getData(index); if (data.length <= buffSize) { ByteBuffer outputBuffer = MoSyncThread.getInstance().getMemorySlice(buffAddr, buffSize); outputBuffer.put(data); } return data.length; } abstract byte[] getData(int index); /** * Sets the value of the specified field. */ int setValue(int index, int buffAddr, int buffSize, int attributes) { if (isReadOnly()) { return MA_PIM_ERR_FIELD_READ_ONLY; } if (isEmpty()) { return throwError(MA_PIM_ERR_FIELD_EMPTY, PIMError.PANIC_FIELD_EMPTY, PIMError.sStrFieldEmpty); } if ((index < 0) || (index >= length())) { return throwError(MA_PIM_ERR_INDEX_INVALID, PIMError.PANIC_INDEX_INVALID, PIMError.sStrIndexInvalid); } Pointer<Void> buffPtr = Pointer.createRawPointer(buffAddr); if (buffPtr.isNull()) { return MA_PIM_ERR_BUFFER_INVALID; } setData(index, buffPtr); if (mStates.get(index) != State.ADDED) { DebugPrint("set state to UPDATED"); mStates.set(index, State.UPDATED); } return setAttribute(index, attributes); } abstract void setData(int index, Pointer<Void> buffer); /** * Sets the value of the specified field. */ int addValue(int buffAddr, int buffSize, int attributes) { if (isReadOnly()) { return MA_PIM_ERR_FIELD_READ_ONLY; } if (length() >= MAX_SIZE) { return MA_PIM_ERR_FIELD_COUNT_MAX; } Pointer<Void> buffPtr = Pointer.createRawPointer(buffAddr); if (buffPtr.isNull()) { return MA_PIM_ERR_BUFFER_INVALID; } String[] val = new String[mNames.length]; int index = mValues.size(); mValues.add(val); mStates.add(State.ADDED); setData(index, buffPtr); int err = MA_PIM_ERR_NONE; if ((err = setAttribute(index, attributes)) != MA_PIM_ERR_NONE) { return err; } print(); return index; } abstract int setAttribute(int index, int attribute); /** * Removes the value of the specified field. */ int removeValue(int index) { if (isReadOnly()) { return MA_PIM_ERR_FIELD_READ_ONLY; } if (isEmpty()) { return throwError(MA_PIM_ERR_FIELD_EMPTY, PIMError.PANIC_FIELD_EMPTY, PIMError.sStrFieldEmpty); } if ((index < 0) || (index >= length())) { return throwError(MA_PIM_ERR_INDEX_INVALID, PIMError.PANIC_INDEX_INVALID, PIMError.sStrIndexInvalid); } if (mStates.get(index) != State.ADDED) { mDeletedValues.add(Long.parseLong(mValues.get(index)[0])); } mValues.remove(index); mStates.remove(index); return MA_PIM_ERR_NONE; } int getDataType() { return mDataType; } boolean isWriteOnly() { return (mPermission == Permission.WRITE_ONLY); } boolean isReadOnly() { return (mPermission == Permission.READ_ONLY); } boolean isSupported() { return true; } /** * Gets the field's value corresponding to the given column name. * @param index * @param name * @return */ String getColumnValue(int index, String name) { String[] val = mValues.get(index); for (int i = 0; i < mNames.length; i++) { if (mNames[i].equals(name)) { return val[i]; } } return null; } /** * Sets the field's value corresponding to the given column name. * @param index * @param name * @return */ void setColumnValue(int index, String name, String value) { String[] val = mValues.get(index); for (int i = 0; i < mNames.length; i++) { if (mNames[i].equals(name)) { val[i] = value; mValues.set(index, val); break; } } } void postProcessData() { } void add(ArrayList<ContentProviderOperation> ops, int contactId) { if (isReadOnly()) { return; } DebugPrint("ADD " + mStrType); print(); postProcessData(); for (int i = 0; i < mValues.size(); i++) { addToDisk(ops, contactId, mNames, mValues.get(i)); } } void update(ContentResolver cr, ArrayList<ContentProviderOperation> ops, int contactId) { if (isReadOnly()) { return; } postProcessData(); for (int i = 0; i < mValues.size(); i++) { if (mStates.get(i) == State.ADDED) { addToDisk(ops, contactId, mNames, mValues.get(i)); } else if (mStates.get(i) == State.UPDATED) { updateToDisk(ops, contactId, mNames, mValues.get(i)); } } for (int i = 0; i < mDeletedValues.size(); i++) { deleteFromDisk(ops, contactId, mDeletedValues.get(i)); } } void addToDisk(ArrayList<ContentProviderOperation> ops, int rawContactInsertIndex, String[] names, String[] values) { ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Data.CONTENT_URI) .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(Data.MIMETYPE, mStrType); for (int i = 0; i < names.length; i++) { if ((values[i] != null) && (!names[i].equals(DUMMY))) { builder = builder.withValue(names[i], values[i]); } } ops.add(builder.build()); } void updateToDisk(ArrayList<ContentProviderOperation> ops, int rawContactId, String[] names, String[] values) { DebugPrint("UPDATE"); ContentProviderOperation.Builder builder = ContentProviderOperation .newUpdate(Data.CONTENT_URI).withSelection( Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "=?" + " AND " + Data._ID + "=?", new String[] { Integer.toString(rawContactId), mStrType, values[0] }); for (int i = 1; i < names.length; i++) { if ((values[i] != null) && (!names[i].equals(DUMMY))) { builder = builder.withValue(names[i], values[i]); } } ops.add(builder.build()); } void deleteFromDisk(ArrayList<ContentProviderOperation> ops, int rawContactId, long id) { DebugPrint("DELETE"); ops.add(ContentProviderOperation .newDelete(Data.CONTENT_URI) .withSelection( Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "=?" + " AND " + Data._ID + "=?", new String[] { Integer.toString(rawContactId), mStrType, Long.toString(id) }).build()); } void close() { } }
tybor/MoSync
runtimes/java/platforms/androidJNI/AndroidProject/src/com/mosync/pim/PIMField.java
Java
gpl-2.0
12,737
[ 30522, 1013, 1008, 9385, 2286, 2585, 22260, 10665, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12646, 2007, 1996, 6105, 1012, 2017, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目&nbsp;</b></th><td class="std2">窩停主人</td></tr> <tr><th class="std1"><b>注音&nbsp;</b></th><td class="std2">ㄨㄛ ㄊ|ㄥ<sup class="subfont">ˊ</sup> ㄓㄨ<sup class="subfont">ˇ</sup> ㄖㄣ<sup class="subfont">ˊ</sup></td></tr> <tr><th class="std1"><b>漢語拼音&nbsp;</b></th><td class="std2"><font class="english_word">wō tíng zhǔ rén</font></td></tr> <tr><th class="std1"><b>釋義&nbsp;</b></th><td class="std2">藏匿罪犯或贓物的人。宋˙洪邁˙夷堅支志癸˙卷二˙李五郎:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>為盜有求不愜,誣為窩停主人,訴于郡,不見察,故陷黨中。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center></td></tr> <tr><th class="std1"><b><font class="fltypefont">附錄</font>&nbsp;</b></th><td class="std2">修訂本參考資料</td></tr> </td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
BuzzAcademy/idioms-moe-unformatted-data
all-data/13000-13999/13895-22.html
HTML
mit
1,388
[ 30522, 1026, 2795, 9381, 1027, 1000, 3938, 1003, 1000, 3675, 1027, 1000, 1014, 1000, 1028, 1026, 19817, 1028, 1026, 14595, 1028, 1026, 5896, 1028, 3853, 2330, 8873, 2571, 1006, 24471, 2140, 1007, 1063, 2440, 10105, 1027, 3332, 1012, 2330, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "swganh_core/gamesystems/gamesystems_service_binding.h" BOOST_PYTHON_MODULE(py_gamesystems) { docstring_options local_docstring_options(true, true, false); exportGameSystemsService(); }
anhstudios/swganh
src/swganh_core/GameSystems/GameSystems_service_binding.cc
C++
mit
332
[ 30522, 1013, 1013, 2023, 5371, 2003, 2112, 1997, 25430, 5289, 2232, 2029, 2003, 2207, 2104, 1996, 10210, 6105, 1012, 1013, 1013, 2156, 5371, 6105, 2030, 2175, 2000, 8299, 1024, 1013, 1013, 25430, 5289, 2232, 1012, 4012, 1013, 6105, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :playlist do title "Test" description "Test" group_id nil youtube_playlist_id nil end end
Archdiocese-of-New-Orleans/ano_gallery
spec/factories/playlists.rb
Ruby
mit
210
[ 30522, 1001, 3191, 2055, 11123, 2012, 16770, 1024, 1013, 1013, 21025, 2705, 12083, 1012, 4012, 1013, 2245, 18384, 1013, 4713, 1035, 2611, 4713, 15239, 1012, 9375, 2079, 4713, 1024, 2377, 9863, 2079, 2516, 1000, 3231, 1000, 6412, 1000, 3231,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.zarroboogs.weibo.widget.galleryview; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.FloatMath; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.VelocityTracker; import android.view.ViewConfiguration; public abstract class VersionedGestureDetector { static final String LOG_TAG = "VersionedGestureDetector"; OnGestureListener mListener; public static VersionedGestureDetector newInstance(Context context, OnGestureListener listener) { final int sdkVersion = Build.VERSION.SDK_INT; VersionedGestureDetector detector = null; if (sdkVersion < Build.VERSION_CODES.ECLAIR) { detector = new CupcakeDetector(context); } else if (sdkVersion < Build.VERSION_CODES.FROYO) { detector = new EclairDetector(context); } else { detector = new FroyoDetector(context); } detector.mListener = listener; return detector; } public abstract boolean onTouchEvent(MotionEvent ev); public abstract boolean isScaling(); public static interface OnGestureListener { public void onDrag(float dx, float dy); public void onFling(float startX, float startY, float velocityX, float velocityY); public void onScale(float scaleFactor, float focusX, float focusY); } private static class CupcakeDetector extends VersionedGestureDetector { float mLastTouchX; float mLastTouchY; final float mTouchSlop; final float mMinimumVelocity; public CupcakeDetector(Context context) { final ViewConfiguration configuration = ViewConfiguration.get(context); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mTouchSlop = configuration.getScaledTouchSlop(); } private VelocityTracker mVelocityTracker; private boolean mIsDragging; float getActiveX(MotionEvent ev) { return ev.getX(); } float getActiveY(MotionEvent ev) { return ev.getY(); } public boolean isScaling() { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); mIsDragging = false; break; } case MotionEvent.ACTION_MOVE: { final float x = getActiveX(ev); final float y = getActiveY(ev); final float dx = x - mLastTouchX, dy = y - mLastTouchY; if (!mIsDragging) { // Use Pythagoras to see if drag length is larger than // touch slop mIsDragging = FloatMath.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop; } if (mIsDragging) { mListener.onDrag(dx, dy); mLastTouchX = x; mLastTouchY = y; if (null != mVelocityTracker) { mVelocityTracker.addMovement(ev); } } break; } case MotionEvent.ACTION_CANCEL: { // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } case MotionEvent.ACTION_UP: { if (mIsDragging) { if (null != mVelocityTracker) { mLastTouchX = getActiveX(ev); mLastTouchY = getActiveY(ev); // Compute velocity within the last 1000ms mVelocityTracker.addMovement(ev); mVelocityTracker.computeCurrentVelocity(1000); final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker.getYVelocity(); // If the velocity is greater than minVelocity, call // listener if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) { mListener.onFling(mLastTouchX, mLastTouchY, -vX, -vY); } } } // Recycle Velocity Tracker if (null != mVelocityTracker) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; } } return true; } } @TargetApi(5) private static class EclairDetector extends CupcakeDetector { private static final int INVALID_POINTER_ID = -1; private int mActivePointerId = INVALID_POINTER_ID; private int mActivePointerIndex = 0; public EclairDetector(Context context) { super(context); } @Override float getActiveX(MotionEvent ev) { try { return ev.getX(mActivePointerIndex); } catch (Exception e) { return ev.getX(); } } @Override float getActiveY(MotionEvent ev) { try { return ev.getY(mActivePointerIndex); } catch (Exception e) { return ev.getY(); } } @Override public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mActivePointerId = ev.getPointerId(0); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mActivePointerId = INVALID_POINTER_ID; break; case MotionEvent.ACTION_POINTER_UP: final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = ev.getPointerId(newPointerIndex); mLastTouchX = ev.getX(newPointerIndex); mLastTouchY = ev.getY(newPointerIndex); } break; } mActivePointerIndex = ev.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId : 0); return super.onTouchEvent(ev); } } @TargetApi(8) private static class FroyoDetector extends EclairDetector { private final ScaleGestureDetector mDetector; // Needs to be an inner class so that we don't hit // VerifyError's on API 4. private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { mListener.onScale(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY()); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { // NO-OP } }; public FroyoDetector(Context context) { super(context); mDetector = new ScaleGestureDetector(context, mScaleListener); } @Override public boolean isScaling() { return mDetector.isInProgress(); } @Override public boolean onTouchEvent(MotionEvent ev) { mDetector.onTouchEvent(ev); return super.onTouchEvent(ev); } } }
MehmetNuri/Beebo
app/src/main/java/org/zarroboogs/weibo/widget/galleryview/VersionedGestureDetector.java
Java
gpl-3.0
8,826
[ 30522, 7427, 8917, 1012, 23564, 18933, 5092, 8649, 2015, 1012, 11417, 5092, 1012, 15536, 24291, 1012, 3916, 8584, 1025, 12324, 11924, 1012, 5754, 17287, 3508, 30524, 14257, 18900, 2232, 1025, 12324, 11924, 1012, 3193, 1012, 4367, 18697, 3372,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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. * */ #ifndef SHERLOCK_TATTOO_WIDGET_FILES_H #define SHERLOCK_TATTOO_WIDGET_FILES_H #include "common/scummsys.h" #include "sherlock/tattoo/widget_base.h" #include "sherlock/saveload.h" namespace Sherlock { class SherlockEngine; namespace Tattoo { enum FilesRenderMode { RENDER_ALL, RENDER_NAMES, RENDER_NAMES_AND_SCROLLBAR }; class WidgetFiles: public WidgetBase, public SaveManager { private: SherlockEngine *_vm; SaveMode _fileMode; int _selector, _oldSelector; /** * Render the dialog */ void render(FilesRenderMode mode); /** * Show the ScummVM Save Game dialog */ void showScummVMSaveDialog(); /** * Show the ScummVM Load Game dialog */ void showScummVMRestoreDialog(); /** * Prompt the user for a savegame name in the currently selected slot */ bool getFilename(); /** * Return the area of a widget that the scrollbar will be drawn in */ virtual Common::Rect getScrollBarBounds() const; public: WidgetFiles(SherlockEngine *vm, const Common::String &target); /** * Prompt the user whether to quit */ void show(SaveMode mode); /** * Handle event processing */ virtual void handleEvents(); }; } // End of namespace Tattoo } // End of namespace Sherlock #endif
alexbevi/scummvm
engines/sherlock/tattoo/widget_files.h
C
gpl-2.0
2,168
[ 30522, 1013, 1008, 8040, 2819, 2213, 2615, 2213, 1011, 8425, 6172, 3194, 1008, 1008, 8040, 2819, 2213, 2615, 2213, 2003, 1996, 3423, 3200, 1997, 2049, 9797, 1010, 3005, 3415, 1008, 2024, 2205, 3365, 2000, 2862, 2182, 1012, 3531, 6523, 200...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
 namespace BlogApp.Shared { public class MetaTagViewModel { public string Tag { get; set; } public int Count { get; set; } } }
tburnett80/blogApp
BlogApp/BlogApp.Shared/MetaTagViewModel.cs
C#
mit
159
[ 30522, 3415, 15327, 9927, 29098, 1012, 4207, 1063, 2270, 2465, 18804, 15900, 8584, 5302, 9247, 1063, 2270, 5164, 6415, 1063, 2131, 1025, 2275, 1025, 1065, 2270, 20014, 4175, 1063, 2131, 1025, 2275, 1025, 1065, 1065, 1065, 102, 0, 0, 0, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
A Scala implementation of [Handlebars](http://handlebarsjs.com/), an extension to and superset of the [Mustache](http://mustache.github.com/) templating language. Currently implements version [1.0.0](https://github.com/wycats/handlebars.js/tree/1.0.0) of the JavaScript version. This project began as an attempt to learn Scala and to experiment with Scala's [Parser Combinators](http://www.scala-lang.org/api/current/index.html#scala.util.parsing.combinator.Parsers) in an attempt to get handlebars.js templates working in Scala. ## Installation If you're using SBT you can add this line to your build.sbt file. libraryDependencies += "com.gilt" %% "handlebars-scala" % "2.0.1" ## Usage Given a template: val template = """ <p>Hello, my name is {{name}}. I am from {{hometown}}. I have {{kids.length}} kids:</p> <ul> {{#kids}}<li>{{name}} is {{age}}</li>{{/kids}} </ul> """ And an arbitrary Scala object: object Guy { val name = "Alan" val hometown = "Somewhere, TX" val kids = Seq(Map( "name" -> "Jimmy", "age" -> "12" ), Map( "name" -> "Sally", "age" -> "4" )) } Pass those into Handlebars like so: scala> import com.gilt.handlebars.scala.binding.dynamic._ import com.gilt.handlebars.scala.binding.dynamic._ scala> import com.gilt.handlebars.scala.Handlebars import com.gilt.handlebars.scala.Handlebars scala> val t = Handlebars(template) t: com.gilt.handlebars.scala.Handlebars = com.gilt.handlebars.scala.Handlebars@496d864e scala> t(Guy) res0: String = " <p>Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:</p> <ul> <li>Jimmy is 12</li><li>Sally is 4</li> </ul> " Handlebars.scala will work just fine for [Mustache](http://mustache.github.com/mustache.5.html) templates, but includes features such as Paths and Helpers. The example above demonstrates the `apply` method of a `Handlebars` instance, which should be familiar to Scala-fans. `apply` takes additional optional arguments: + `data` additional custom data to be referenced by @variable private variables. + `partials` custom partials in addition to the globally defined ones. These partials will override the globally provided ones. + `helpers` custom helpers in addition to the globally defined ones. These helpers will override the globally provided ones. The signature for apply looks like this: def apply[T](context: T, data: Map[String, Binding[T]] = Map.empty, partials: Map[String, Handlebars[T]] = Map.empty, helpers: Map[String, Helper[T]] = Map.empty): String ## Bindings In order to facilitate multiple ways of interacting with data, Handlebars provides a data-binding facility. Handlebars ships with a default binding strategy, DynamicBinding, which uses Scala reflection to work with scala standard-library data structures and primitives. You can implement your own Binding strategies by implementing the following traits: - `com.gilt.handlebars.scala.binding.FullBinding` - `com.gilt.handlebars.scala.binding.BindingFactory` Provide the implicit BindingFactory which uses your new binding. If you need an example, see the source code in `binding/dynamic/DynamicBinding.scala`. ### Binding Interface + `def get: T` - Retrieve the contents of the binding. Throws runtime exception if in the void. + `def getOrElse(default: => T): T` - Get the contents of the binding if full; else is VoidBinding return default + `def toOption: Option[T]` - Similar to the Option constructor, returns Some(value) where value is defined + `def render: String` - Returns a string representation for the object, returning empty string where value is not defined. + `def traverse(key: String, args: List[Binding[T]] = List.empty): Binding[T]` For dictionaries / objects, traverse into named key, returning a binding for the matched value, VoidBinding if key is not declared. Important! Take note of the difference here: ```scala val binding = DynamicBinding(Map("a" -> null)) binding.traverse("a") // => DynamicBinding(null) binding.traverse("b") // => VoidBinding ``` + `def isTruthy: Boolean` - Returns whether the bound value evaluate to truth in handlebars if expressions? + `def isCollection: Boolean` - Returns whether the bound value is an iterable (and not a dictionary) + `def isDictionary: Boolean` - Returns whether the bound value is a dictionary + `def isPrimitive` - Returns whether bound value is neither collection or dictionary + `def asOption: Option[Binding[T]]` - If value is defined, returns Some(this), else None + `def asCollection: Iterable[Binding[T]]` - Returns List of bindings if isCollection; else empty List + `def asDictionaryCollection: Iterable[(String, Binding[T])]` - returns List of key-value tuples if isDictionary; else empty list ### `Unit` vs `null` vs `None` vs `VoidBinding` In order to preserve the signal of "a value was defined in your model", vs., "you traversed outside the space covered by your model", bindings are monadic and capture whether they've a value from your model or not: a `FullBinding` if bound against a value from your model, a `VoidBinding` is you traversed outside the space of your model. If the model contained a `null`, `Unit`, or `None` `isDefined` is `true` if the bound value is within the space of the model, and it evaluates to some value other than . `VoidBinding` is, naturally, never defined, and always returns `isDefined` as `false`. ### Pattern matching value extraction You can extract the bound value by matching `FullBinding`, like so: ```scala DynamicBinding(1) match { case FullBinding(value) => value case VoidBinding => Unit } ``` ## Helpers The trait for a helper looks like this: trait Helper[Any] { def apply(binding: Binding[Any], options: HelperOptions[Any]): String } + `binding` the binding for the model in the context from which the helper was called. + `options` provides helper functions to interact with the context and evaluate the body of the helper, if present. You can define a new helper by extending the trait above, or you can use companion obejct apply method to define one on the fly: val fullNameHelper = Helper[Any] { (binding, options) => "%s %s".format(options.lookup("firstName").renderString, options.lookup("lastName").renderString) } If you know that the information you need is on `binding`, you can do the same thing by accessing first and last name on the data directly. However, you will be responsible for casting model to the correct type. val fullNameHelper = Helper[Any] { (binding, options) => val person = binding.get.asInstanceOf[Person] "%s %s".format(person.firstName, person.lastName) } ### HelperOptions The `HelperOption[T]` object gives you the tools you need to get things done in your helper. The primary methods are: + `def argument(index: Int): Binding[T]` Retrieve an argument from the list provided to the helper by its index. + `def data(key: String): Binding[T]` Retrieve data provided to the Handlebars template by its key. + `def visit(binding: Binding[T]): String` Evaluates the body of the helper using a context with the provided binding. + `def inverse(binding: Binding[T]): String` Evaluate the inverse of body of the helper using the provided model as a context. + `def lookup(path: String): Binding[T]` Look up a value for a path in the the current context. The one in which the helper was called. ## Caveats when using DynamicBinding **Implicit conversions will not work in a template**. Because Handlebars.scala makes heavy use of reflection. Bummer, I know. This leads me too... **Handlebars.scala makes heavy use of reflection**. This means that there could be unexpected behavior. Method overloading will behave in bizarre ways. There is likely a performance penalty. I'm not sophisticated enough in the arts of the JVM to know the implications of this. **Not everything from the JavaScript handlebars is supported**. See [NOTSUPPORTED](NOTSUPPORTED.md) for a list of the unsupported features. There are some things JavaScript can do that simply does not make sense to do in Scala. ### Alternatives to DynamicBinding If you wish for more type-safety, you can consider binding to an AST such as that provided by a popular Json library. [handlebars-play-json](https://github.com/SpinGo/handlebars-play-json) provides a binding strategy that works directly with the PlayJson AST, and provides similar truthy / collection / traversal behavior as you would find using JavaScript values in handlebars-js. ## Thanks Special thanks to the fine folks working on [Scalate](http://scalate.fusesource.org/) whose Mustache parser was my primary source of inspiration. Tom Dale and Yehuda Katz who inceptioned the idea of writing a Handlebars implementation for the JVM. The UI team at Gilt who insisted on using Handlebars and not Mustache for client-side templating. And finally, the denizens of the Scala 2.9.1 chat room at Gilt for answering my questions with enthusiastic aplomb. ## Build The project uses [sbt](https://github.com/harrah/xsbt/wiki). Assuming you have sbt you can clone the repo, and run: sbt test [![Build Status](https://secure.travis-ci.org/mwunsch/handlebars.scala.png?branch=master)](http://travis-ci.org/mwunsch/handlebars.scala) ## Copyright and License Copyright 2014 Mark Wunsch and Gilt Groupe, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
QiaoBuTang/handlebars.scala
README.md
Markdown
apache-2.0
10,057
[ 30522, 1037, 26743, 7375, 1997, 1031, 5047, 8237, 2015, 1033, 1006, 8299, 1024, 1013, 1013, 5047, 8237, 2015, 22578, 1012, 4012, 1013, 1007, 1010, 2019, 5331, 2000, 1998, 3565, 13462, 1997, 1996, 1031, 28786, 1033, 1006, 8299, 1024, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) 2014 Actuate Corporation */ package com.actuate.aces.idapi; import com.actuate.aces.idapi.control.ActuateException; import com.actuate.schemas.*; import org.apache.axis.attachments.AttachmentPart; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.rpc.ServiceException; import javax.xml.soap.SOAPException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.rmi.RemoteException; import java.util.Iterator; public class InformationObjectExecuter extends BaseController { public InformationObjectExecuter(BaseController controller) { super(controller); } public InformationObjectExecuter(String host, String authenticationId) throws MalformedURLException, ServiceException { super(host, authenticationId); } public InformationObjectExecuter(String host, String username, String password, String volume) throws ServiceException, ActuateException, MalformedURLException { super(host, username, password, volume); } public InformationObjectExecuter(String host, String username, String password, String volume, byte[] extendedCredentials) throws ServiceException, ActuateException, MalformedURLException { super(host, username, password, volume, extendedCredentials); } public InputStream getXmlStream(String infoObjectName) { ExecuteQueryResponse executeQueryResponse = getExecuteQueryId(infoObjectName); if (executeQueryResponse == null) return null; setConnectionHandle(executeQueryResponse.getConnectionHandle()); ObjectIdentifier objectIdentifier = new ObjectIdentifier(); objectIdentifier.setId(executeQueryResponse.getObjectId()); ViewParameter viewParameter = new ViewParameter(); viewParameter.setFormat("XMLData"); ComponentType componentType = new ComponentType(); componentType.setId("0"); GetContent getContent = new GetContent(); getContent.setObject(objectIdentifier); getContent.setViewParameter(viewParameter); getContent.setComponent(componentType); getContent.setDownloadEmbedded(false); GetContentResponse getContentResponse; try { getContentResponse = acxControl.proxy.getContent(getContent); } catch (RemoteException e) { e.printStackTrace(); return null; } try { Iterator iter = acxControl.actuateAPI.getCall().getMessageContext().getResponseMessage().getAttachments(); while (iter.hasNext()) { AttachmentPart attachmentPart = (AttachmentPart) iter.next(); return attachmentPart.getDataHandler().getInputStream(); } } catch (IOException e) { e.printStackTrace(); } catch (SOAPException e) { e.printStackTrace(); } return null; } public Document getDocument(String infoObjectName) throws ParserConfigurationException, IOException, SAXException { InputStream inputStream = getXmlStream(infoObjectName); if (inputStream == null) return null; Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); inputStream.close(); return document; } public String getXml(String infoObjectName) throws IOException { InputStream inputStream = getXmlStream(infoObjectName); if (inputStream == null) return null; StringBuffer stringBuffer = new StringBuffer(); byte[] buf = new byte[1024]; int len = 0; while ((len = inputStream.read(buf)) > 0) { stringBuffer.append(new String(buf, 0, len)); } inputStream.close(); return stringBuffer.toString(); } private ExecuteQueryResponse getExecuteQueryId(String infoObjectName) { ArrayOfColumnDefinition arrayOfColumnDefinition = getAvailableColumns(infoObjectName); if (arrayOfColumnDefinition == null) return null; Query query = new Query(); query.setAvailableColumnList(arrayOfColumnDefinition); query.setSelectColumnList(getSelectColumnList(arrayOfColumnDefinition)); query.setSuppressDetailRows(false); query.setOutputDistinctRowsOnly(false); query.setSupportedQueryFeatures(SupportedQueryFeatures.UI_Version_2); ExecuteQuery executeQuery = new ExecuteQuery(); executeQuery.setInputFileName(infoObjectName); executeQuery.setJobName("$$$TRANSIENT_JOB$$$"); executeQuery.setSaveOutputFile(false); executeQuery.setProgressiveViewing(false); executeQuery.setRunLatestVersion(true); executeQuery.setWaitTime(300); executeQuery.setQuery(query); ExecuteQueryResponse executeQueryResponse; try { executeQueryResponse = acxControl.proxy.executeQuery(executeQuery); } catch (RemoteException e) { e.printStackTrace(); return null; } return executeQueryResponse; } private ArrayOfColumnDefinition getAvailableColumns(String infoObjectName) { GetQuery getQuery = new GetQuery(); getQuery.setQueryFileName(infoObjectName); GetQueryResponse getQueryResponse; try { getQueryResponse = acxControl.proxy.getQuery(getQuery); } catch (RemoteException e) { e.printStackTrace(); return null; } if (getQueryResponse == null || getQueryResponse.getQuery() == null) return null; return getQueryResponse.getQuery().getAvailableColumnList(); } private ArrayOfString getSelectColumnList(ArrayOfColumnDefinition arrayOfColumnDefinition) { ColumnDefinition[] columnDefinitions = arrayOfColumnDefinition.getColumnDefinition(); String[] columnList = new String[columnDefinitions.length]; for (int i = 0; i < columnDefinitions.length; i++) { columnList[i] = columnDefinitions[i].getName(); } return new ArrayOfString(columnList); } }
puckpuck/idapi-wrapper
idapi-wrapper/src/com/actuate/aces/idapi/InformationObjectExecuter.java
Java
epl-1.0
5,575
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2297, 2552, 20598, 3840, 1008, 1013, 7427, 4012, 1012, 2552, 20598, 1012, 20232, 1012, 16096, 8197, 1025, 12324, 4012, 1012, 2552, 20598, 1012, 20232, 1012, 16096, 8197, 1012, 2491, 1012, 255...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Configuration handling. * * @package PhpMyAdmin */ if (! defined('PHPMYADMIN')) { exit; } /** * Load vendor configuration. */ require_once './libraries/vendor_config.php'; /** * Configuration class * * @package PhpMyAdmin */ class PMA_Config { /** * @var string default config source */ var $default_source = './libraries/config.default.php'; /** * @var array default configuration settings */ var $default = array(); /** * @var array configuration settings */ var $settings = array(); /** * @var string config source */ var $source = ''; /** * @var int source modification time */ var $source_mtime = 0; var $default_source_mtime = 0; var $set_mtime = 0; /** * @var boolean */ var $error_config_file = false; /** * @var boolean */ var $error_config_default_file = false; /** * @var boolean */ var $error_pma_uri = false; /** * @var array */ var $default_server = array(); /** * @var boolean whether init is done or not * set this to false to force some initial checks * like checking for required functions */ var $done = false; /** * constructor * * @param string $source source to read config from */ function __construct($source = null) { $this->settings = array(); // functions need to refresh in case of config file changed goes in // PMA_Config::load() $this->load($source); // other settings, independent from config file, comes in $this->checkSystem(); $this->checkIsHttps(); } /** * sets system and application settings * * @return void */ function checkSystem() { $this->set('PMA_VERSION', '4.0.10.19'); /** * @deprecated */ $this->set('PMA_THEME_VERSION', 2); /** * @deprecated */ $this->set('PMA_THEME_GENERATION', 2); $this->checkPhpVersion(); $this->checkWebServerOs(); $this->checkWebServer(); $this->checkGd2(); $this->checkClient(); $this->checkUpload(); $this->checkUploadSize(); $this->checkOutputCompression(); } /** * whether to use gzip output compression or not * * @return void */ function checkOutputCompression() { // If zlib output compression is set in the php configuration file, no // output buffering should be run if (@ini_get('zlib.output_compression')) { $this->set('OBGzip', false); } // disable output-buffering (if set to 'auto') for IE6, else enable it. if (strtolower($this->get('OBGzip')) == 'auto') { if ($this->get('PMA_USR_BROWSER_AGENT') == 'IE' && $this->get('PMA_USR_BROWSER_VER') >= 6 && $this->get('PMA_USR_BROWSER_VER') < 7 ) { $this->set('OBGzip', false); } else { $this->set('OBGzip', true); } } } /** * Determines platform (OS), browser and version of the user * Based on a phpBuilder article: * * @see http://www.phpbuilder.net/columns/tim20000821.php * * @return void */ function checkClient() { if (PMA_getenv('HTTP_USER_AGENT')) { $HTTP_USER_AGENT = PMA_getenv('HTTP_USER_AGENT'); } else { $HTTP_USER_AGENT = ''; } // 1. Platform if (strstr($HTTP_USER_AGENT, 'Win')) { $this->set('PMA_USR_OS', 'Win'); } elseif (strstr($HTTP_USER_AGENT, 'Mac')) { $this->set('PMA_USR_OS', 'Mac'); } elseif (strstr($HTTP_USER_AGENT, 'Linux')) { $this->set('PMA_USR_OS', 'Linux'); } elseif (strstr($HTTP_USER_AGENT, 'Unix')) { $this->set('PMA_USR_OS', 'Unix'); } elseif (strstr($HTTP_USER_AGENT, 'OS/2')) { $this->set('PMA_USR_OS', 'OS/2'); } else { $this->set('PMA_USR_OS', 'Other'); } // 2. browser and version // (must check everything else before Mozilla) if (preg_match( '@Opera(/| )([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version )) { $this->set('PMA_USR_BROWSER_VER', $log_version[2]); $this->set('PMA_USR_BROWSER_AGENT', 'OPERA'); } elseif (preg_match( '@MSIE ([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version )) { $this->set('PMA_USR_BROWSER_VER', $log_version[1]); $this->set('PMA_USR_BROWSER_AGENT', 'IE'); } elseif (preg_match( '@OmniWeb/([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version )) { $this->set('PMA_USR_BROWSER_VER', $log_version[1]); $this->set('PMA_USR_BROWSER_AGENT', 'OMNIWEB'); // Konqueror 2.2.2 says Konqueror/2.2.2 // Konqueror 3.0.3 says Konqueror/3 } elseif (preg_match( '@(Konqueror/)(.*)(;)@', $HTTP_USER_AGENT, $log_version )) { $this->set('PMA_USR_BROWSER_VER', $log_version[2]); $this->set('PMA_USR_BROWSER_AGENT', 'KONQUEROR'); // must check Chrome before Safari } elseif (preg_match( '@Mozilla/([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version) && preg_match('@Chrome/([0-9]*)@', $HTTP_USER_AGENT, $log_version2) ) { $this->set('PMA_USR_BROWSER_VER', $log_version[1] . '.' . $log_version2[1]); $this->set('PMA_USR_BROWSER_AGENT', 'CHROME'); // newer Safari } elseif (preg_match( '@Mozilla/([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version) && preg_match('@Version/(.*) Safari@', $HTTP_USER_AGENT, $log_version2) ) { $this->set( 'PMA_USR_BROWSER_VER', $log_version2[1] ); $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI'); // older Safari } elseif (preg_match( '@Mozilla/([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version) && preg_match('@Safari/([0-9]*)@', $HTTP_USER_AGENT, $log_version2) ) { $this->set( 'PMA_USR_BROWSER_VER', $log_version[1] . '.' . $log_version2[1] ); $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI'); } elseif (preg_match('@rv:1.9(.*)Gecko@', $HTTP_USER_AGENT)) { $this->set('PMA_USR_BROWSER_VER', '1.9'); $this->set('PMA_USR_BROWSER_AGENT', 'GECKO'); } elseif (preg_match('@Mozilla/([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version)) { $this->set('PMA_USR_BROWSER_VER', $log_version[1]); $this->set('PMA_USR_BROWSER_AGENT', 'MOZILLA'); } else { $this->set('PMA_USR_BROWSER_VER', 0); $this->set('PMA_USR_BROWSER_AGENT', 'OTHER'); } } /** * Whether GD2 is present * * @return void */ function checkGd2() { if ($this->get('GD2Available') == 'yes') { $this->set('PMA_IS_GD2', 1); } elseif ($this->get('GD2Available') == 'no') { $this->set('PMA_IS_GD2', 0); } else { if (!@function_exists('imagecreatetruecolor')) { $this->set('PMA_IS_GD2', 0); } else { if (@function_exists('gd_info')) { $gd_nfo = gd_info(); if (strstr($gd_nfo["GD Version"], '2.')) { $this->set('PMA_IS_GD2', 1); } else { $this->set('PMA_IS_GD2', 0); } } else { $this->set('PMA_IS_GD2', 0); } } } } /** * Whether the Web server php is running on is IIS * * @return void */ function checkWebServer() { // some versions return Microsoft-IIS, some Microsoft/IIS // we could use a preg_match() but it's slower if (PMA_getenv('SERVER_SOFTWARE') && stristr(PMA_getenv('SERVER_SOFTWARE'), 'Microsoft') && stristr(PMA_getenv('SERVER_SOFTWARE'), 'IIS') ) { $this->set('PMA_IS_IIS', 1); } else { $this->set('PMA_IS_IIS', 0); } } /** * Whether the os php is running on is windows or not * * @return void */ function checkWebServerOs() { // Default to Unix or Equiv $this->set('PMA_IS_WINDOWS', 0); // If PHP_OS is defined then continue if (defined('PHP_OS')) { if (stristr(PHP_OS, 'win')) { // Is it some version of Windows $this->set('PMA_IS_WINDOWS', 1); } elseif (stristr(PHP_OS, 'OS/2')) { // Is it OS/2 (No file permissions like Windows) $this->set('PMA_IS_WINDOWS', 1); } } } /** * detects PHP version * * @return void */ function checkPhpVersion() { $match = array(); if (! preg_match( '@([0-9]{1,2}).([0-9]{1,2}).([0-9]{1,2})@', phpversion(), $match )) { preg_match( '@([0-9]{1,2}).([0-9]{1,2})@', phpversion(), $match ); } if (isset($match) && ! empty($match[1])) { if (! isset($match[2])) { $match[2] = 0; } if (! isset($match[3])) { $match[3] = 0; } $this->set( 'PMA_PHP_INT_VERSION', (int) sprintf('%d%02d%02d', $match[1], $match[2], $match[3]) ); } else { $this->set('PMA_PHP_INT_VERSION', 0); } $this->set('PMA_PHP_STR_VERSION', phpversion()); } /** * detects if Git revision * * @return boolean */ function isGitRevision() { // caching if (isset($_SESSION['is_git_revision'])) { if ($_SESSION['is_git_revision']) { $this->set('PMA_VERSION_GIT', 1); } return $_SESSION['is_git_revision']; } // find out if there is a .git folder $git_folder = '.git'; if (! @file_exists($git_folder) || ! @file_exists($git_folder . '/config') ) { $_SESSION['is_git_revision'] = false; return false; } $_SESSION['is_git_revision'] = true; return true; } /** * detects Git revision, if running inside repo * * @return void */ function checkGitRevision() { // find out if there is a .git folder $git_folder = '.git'; if (! $this->isGitRevision()) { return; } if (! $ref_head = @file_get_contents($git_folder . '/HEAD')) { return; } $branch = false; // are we on any branch? if (strstr($ref_head, '/')) { $ref_head = substr(trim($ref_head), 5); if (substr($ref_head, 0, 11) === 'refs/heads/') { $branch = substr($ref_head, 11); } else { $branch = basename($ref_head); } $ref_file = $git_folder . '/' . $ref_head; if (@file_exists($ref_file)) { if (! $hash = @file_get_contents($ref_file)) { return; } $hash = trim($hash); } else { // deal with packed refs if (! $packed_refs = @file_get_contents($git_folder . '/packed-refs')) { return; } // split file to lines $ref_lines = explode("\n", $packed_refs); foreach ($ref_lines as $line) { // skip comments if ($line[0] == '#') { continue; } // parse line $parts = explode(' ', $line); // care only about named refs if (count($parts) != 2) { continue; } // have found our ref? if ($parts[1] == $ref_head) { $hash = $parts[0]; break; } } if (! isset($hash)) { // Could not find ref return; } } } else { $hash = trim($ref_head); } $commit = false; if ( !isset($_SESSION['PMA_VERSION_COMMITDATA_' . $hash])) { $git_file_name = $git_folder . '/objects/' . substr($hash, 0, 2) . '/' . substr($hash, 2); if (file_exists($git_file_name) ) { if (! $commit = @file_get_contents($git_file_name)) { return; } $commit = explode("\0", gzuncompress($commit), 2); $commit = explode("\n", $commit[1]); $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit; } else { $pack_names = array(); // work with packed data if ($packs = @file_get_contents($git_folder . '/objects/info/packs')) { // File exists. Read it, parse the file to get the names of the // packs. (to look for them in .git/object/pack directory later) foreach (explode("\n", $packs) as $line) { // skip blank lines if (strlen(trim($line)) == 0) { continue; } // skip non pack lines if ($line[0] != 'P') { continue; } // parse names $pack_names[] = substr($line, 2); } } else { // '.git/objects/info/packs' file can be missing // (atlease in mysGit) // File missing. May be we can look in the .git/object/pack // directory for all the .pack files and use that list of // files instead $it = new DirectoryIterator($git_folder . '/objects/pack'); foreach ($it as $file_info) { $file_name = $file_info->getFilename(); // if this is a .pack file if ($file_info->isFile() && substr($file_name, -5) == '.pack' ) { $pack_names[] = $file_name; } } } $hash = strtolower($hash); foreach ($pack_names as $pack_name) { $index_name = str_replace('.pack', '.idx', $pack_name); // load index if (! $index_data = @file_get_contents($git_folder . '/objects/pack/' . $index_name)) { continue; } // check format if (substr($index_data, 0, 4) != "\377tOc") { continue; } // check version $version = unpack('N', substr($index_data, 4, 4)); if ($version[1] != 2) { continue; } // parse fanout table $fanout = unpack("N*", substr($index_data, 8, 256 * 4)); // find where we should search $firstbyte = intval(substr($hash, 0, 2), 16); // array is indexed from 1 and we need to get // previous entry for start if ($firstbyte == 0) { $start = 0; } else { $start = $fanout[$firstbyte]; } $end = $fanout[$firstbyte + 1]; // stupid linear search for our sha $position = $start; $found = false; $offset = 8 + (256 * 4); for ($position = $start; $position < $end; $position++) { $sha = strtolower( bin2hex( substr( $index_data, $offset + ($position * 20), 20 ) ) ); if ($sha == $hash) { $found = true; break; } } if (! $found) { continue; } // read pack offset $offset = 8 + (256 * 4) + (24 * $fanout[256]); $pack_offset = unpack( 'N', substr($index_data, $offset + ($position * 4), 4) ); $pack_offset = $pack_offset[1]; // open pack file $pack_file = fopen( $git_folder . '/objects/pack/' . $pack_name, 'rb' ); if ($pack_file === false) { continue; } // seek to start fseek($pack_file, $pack_offset); // parse header $header = ord(fread($pack_file, 1)); $type = ($header >> 4) & 7; $hasnext = ($header & 128) >> 7; $size = $header & 0xf; $offset = 4; while ($hasnext) { $byte = ord(fread($pack_file, 1)); $size |= ($byte & 0x7f) << $offset; $hasnext = ($byte & 128) >> 7; $offset += 7; } // we care only about commit objects if ($type != 1) { continue; } // read data $commit = fread($pack_file, $size); $commit = gzuncompress($commit); $commit = explode("\n", $commit); $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit; fclose($pack_file); } } } else { $commit = $_SESSION['PMA_VERSION_COMMITDATA_' . $hash]; } // check if commit exists in Github $is_remote_commit = false; if ($commit !== false && isset($_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash]) ) { $is_remote_commit = $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash]; } else { $link = 'https://api.github.com/repos/phpmyadmin/phpmyadmin/git/commits/' . $hash; $is_found = $this->checkHTTP($link, !$commit); switch($is_found) { case false: $is_remote_commit = false; $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = false; break; case null: // no remote link for now, but don't cache this as Github is down $is_remote_commit = false; break; default: $is_remote_commit = true; $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = true; if ($commit === false) { // if no local commit data, try loading from Github $commit_json = json_decode($is_found); } break; } } $is_remote_branch = false; if ($is_remote_commit && $branch !== false) { // check if branch exists in Github if (isset($_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash])) { $is_remote_branch = $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash]; } else { $link = 'https://api.github.com/repos/phpmyadmin/phpmyadmin' . '/git/trees/' . $branch; $is_found = $this->checkHTTP($link); switch($is_found) { case true: $is_remote_branch = true; $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = true; break; case false: $is_remote_branch = false; $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = false; break; case null: // no remote link for now, but don't cache this as Github is down $is_remote_branch = false; break; } } } if ($commit !== false) { $author = array('name' => '', 'email' => '', 'date' => ''); $committer = array('name' => '', 'email' => '', 'date' => ''); do { $dataline = array_shift($commit); $datalinearr = explode(' ', $dataline, 2); $linetype = $datalinearr[0]; if (in_array($linetype, array('author', 'committer'))) { $user = $datalinearr[1]; preg_match('/([^<]+)<([^>]+)> ([0-9]+)( [^ ]+)?/', $user, $user); $user2 = array( 'name' => trim($user[1]), 'email' => trim($user[2]), 'date' => date('Y-m-d H:i:s', $user[3])); if (isset($user[4])) { $user2['date'] .= $user[4]; } $$linetype = $user2; } } while ($dataline != ''); $message = trim(implode(' ', $commit)); } elseif (isset($commit_json)) { $author = array( 'name' => $commit_json->author->name, 'email' => $commit_json->author->email, 'date' => $commit_json->author->date); $committer = array( 'name' => $commit_json->committer->name, 'email' => $commit_json->committer->email, 'date' => $commit_json->committer->date); $message = trim($commit_json->message); } else { return; } $this->set('PMA_VERSION_GIT', 1); $this->set('PMA_VERSION_GIT_COMMITHASH', $hash); $this->set('PMA_VERSION_GIT_BRANCH', $branch); $this->set('PMA_VERSION_GIT_MESSAGE', $message); $this->set('PMA_VERSION_GIT_AUTHOR', $author); $this->set('PMA_VERSION_GIT_COMMITTER', $committer); $this->set('PMA_VERSION_GIT_ISREMOTECOMMIT', $is_remote_commit); $this->set('PMA_VERSION_GIT_ISREMOTEBRANCH', $is_remote_branch); } /** * Checks if given URL is 200 or 404, optionally returns data * * @param mixed $link curl link * @param boolean $get_body whether to retrieve body of document * * @return test result or data */ function checkHTTP($link, $get_body = false) { if (! function_exists('curl_init')) { return null; } $ch = curl_init($link); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_USERAGENT, 'phpMyAdmin/' . PMA_VERSION); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $data = @curl_exec($ch); if ($data === false) { return null; } $ok = 'HTTP/1.1 200 OK'; $notfound = 'HTTP/1.1 404 Not Found'; if (substr($data, 0, strlen($ok)) === $ok) { return $get_body ? substr($data, strpos($data, "\r\n\r\n") + 4) : true; } elseif (substr($data, 0, strlen($notfound)) === $notfound) { return false; } return null; } /** * loads default values from default source * * @return boolean success */ function loadDefaults() { $cfg = array(); if (! file_exists($this->default_source)) { $this->error_config_default_file = true; return false; } include $this->default_source; $this->default_source_mtime = filemtime($this->default_source); $this->default_server = $cfg['Servers'][1]; unset($cfg['Servers']); $this->default = $cfg; $this->settings = PMA_arrayMergeRecursive($this->settings, $cfg); $this->error_config_default_file = false; return true; } /** * loads configuration from $source, usally the config file * should be called on object creation * * @param string $source config file * * @return bool */ function load($source = null) { $this->loadDefaults(); if (null !== $source) { $this->setSource($source); } if (! $this->checkConfigSource()) { return false; } $cfg = array(); /** * Parses the configuration file, the eval is used here to avoid * problems with trailing whitespace, what is often a problem. */ $old_error_reporting = error_reporting(0); $eval_result = eval('?' . '>' . trim(file_get_contents($this->getSource()))); error_reporting($old_error_reporting); if ($eval_result === false) { $this->error_config_file = true; } else { $this->error_config_file = false; $this->source_mtime = filemtime($this->getSource()); } /** * Backward compatibility code */ if (!empty($cfg['DefaultTabTable'])) { $cfg['DefaultTabTable'] = str_replace( '_properties', '', str_replace( 'tbl_properties.php', 'tbl_sql.php', $cfg['DefaultTabTable'] ) ); } if (!empty($cfg['DefaultTabDatabase'])) { $cfg['DefaultTabDatabase'] = str_replace( '_details', '', str_replace( 'db_details.php', 'db_sql.php', $cfg['DefaultTabDatabase'] ) ); } $this->settings = PMA_arrayMergeRecursive($this->settings, $cfg); $this->checkPmaAbsoluteUri(); $this->checkFontsize(); // Handling of the collation must be done after merging of $cfg // (from config.inc.php) so that $cfg['DefaultConnectionCollation'] // can have an effect. Note that the presence of collation // information in a cookie has priority over what is defined // in the default or user's config files. /** * @todo check validity of $_COOKIE['pma_collation_connection'] */ if (! empty($_COOKIE['pma_collation_connection'])) { $this->set( 'collation_connection', strip_tags($_COOKIE['pma_collation_connection']) ); } else { $this->set( 'collation_connection', $this->get('DefaultConnectionCollation') ); } // Now, a collation information could come from REQUEST // (an example of this: the collation selector in index.php) // so the following handles the setting of collation_connection // and later, in common.inc.php, the cookie will be set // according to this. $this->checkCollationConnection(); return true; } /** * Loads user preferences and merges them with current config * must be called after control connection has been estabilished * * @return boolean */ function loadUserPreferences() { // index.php should load these settings, so that phpmyadmin.css.php // will have everything avaiable in session cache $server = isset($GLOBALS['server']) ? $GLOBALS['server'] : (!empty($GLOBALS['cfg']['ServerDefault']) ? $GLOBALS['cfg']['ServerDefault'] : 0); $cache_key = 'server_' . $server; if ($server > 0 && !defined('PMA_MINIMUM_COMMON')) { $config_mtime = max($this->default_source_mtime, $this->source_mtime); // cache user preferences, use database only when needed if (! isset($_SESSION['cache'][$cache_key]['userprefs']) || $_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime ) { // load required libraries include_once './libraries/user_preferences.lib.php'; $prefs = PMA_loadUserprefs(); $_SESSION['cache'][$cache_key]['userprefs'] = PMA_applyUserprefs($prefs['config_data']); $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime']; $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type']; $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime; } } elseif ($server == 0 || ! isset($_SESSION['cache'][$cache_key]['userprefs']) ) { $this->set('user_preferences', false); return; } $config_data = $_SESSION['cache'][$cache_key]['userprefs']; // type is 'db' or 'session' $this->set( 'user_preferences', $_SESSION['cache'][$cache_key]['userprefs_type'] ); $this->set( 'user_preferences_mtime', $_SESSION['cache'][$cache_key]['userprefs_mtime'] ); // backup some settings $org_fontsize = ''; if (isset($this->settings['fontsize'])) { $org_fontsize = $this->settings['fontsize']; } // load config array $this->settings = PMA_arrayMergeRecursive($this->settings, $config_data); $GLOBALS['cfg'] = PMA_arrayMergeRecursive($GLOBALS['cfg'], $config_data); if (defined('PMA_MINIMUM_COMMON')) { return; } // settings below start really working on next page load, but // changes are made only in index.php so everything is set when // in frames // save theme $tmanager = $_SESSION['PMA_Theme_Manager']; if ($tmanager->getThemeCookie() || isset($_REQUEST['set_theme'])) { if ((! isset($config_data['ThemeDefault']) && $tmanager->theme->getId() != 'original') || isset($config_data['ThemeDefault']) && $config_data['ThemeDefault'] != $tmanager->theme->getId() ) { // new theme was set in common.inc.php $this->setUserValue( null, 'ThemeDefault', $tmanager->theme->getId(), 'original' ); } } else { // no cookie - read default from settings if ($this->settings['ThemeDefault'] != $tmanager->theme->getId() && $tmanager->checkTheme($this->settings['ThemeDefault']) ) { $tmanager->setActiveTheme($this->settings['ThemeDefault']); $tmanager->setThemeCookie(); } } // save font size if ((! isset($config_data['fontsize']) && $org_fontsize != '82%') || isset($config_data['fontsize']) && $org_fontsize != $config_data['fontsize'] ) { $this->setUserValue(null, 'fontsize', $org_fontsize, '82%'); } // save language if (isset($_COOKIE['pma_lang']) || isset($_POST['lang'])) { if ((! isset($config_data['lang']) && $GLOBALS['lang'] != 'en') || isset($config_data['lang']) && $GLOBALS['lang'] != $config_data['lang'] ) { $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en'); } } else { // read language from settings if (isset($config_data['lang']) && PMA_langSet($config_data['lang'])) { $this->setCookie('pma_lang', $GLOBALS['lang']); } } // save connection collation if (isset($_COOKIE['pma_collation_connection']) || isset($_POST['collation_connection']) ) { if ((! isset($config_data['collation_connection']) && $GLOBALS['collation_connection'] != 'utf8_general_ci') || isset($config_data['collation_connection']) && $GLOBALS['collation_connection'] != $config_data['collation_connection'] ) { $this->setUserValue( null, 'collation_connection', $GLOBALS['collation_connection'], 'utf8_general_ci' ); } } else { // read collation from settings if (isset($config_data['collation_connection'])) { $GLOBALS['collation_connection'] = $config_data['collation_connection']; $this->setCookie( 'pma_collation_connection', $GLOBALS['collation_connection'] ); } } } /** * Sets config value which is stored in user preferences (if available) * or in a cookie. * * If user preferences are not yet initialized, option is applied to * global config and added to a update queue, which is processed * by {@link loadUserPreferences()} * * @param string $cookie_name can be null * @param string $cfg_path configuration path * @param mixed $new_cfg_value new value * @param mixed $default_value default value * * @return void */ function setUserValue($cookie_name, $cfg_path, $new_cfg_value, $default_value = null ) { // use permanent user preferences if possible $prefs_type = $this->get('user_preferences'); if ($prefs_type) { include_once './libraries/user_preferences.lib.php'; if ($default_value === null) { $default_value = PMA_arrayRead($cfg_path, $this->default); } PMA_persistOption($cfg_path, $new_cfg_value, $default_value); } if ($prefs_type != 'db' && $cookie_name) { // fall back to cookies if ($default_value === null) { $default_value = PMA_arrayRead($cfg_path, $this->settings); } $this->setCookie($cookie_name, $new_cfg_value, $default_value); } PMA_arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value); PMA_arrayWrite($cfg_path, $this->settings, $new_cfg_value); } /** * Reads value stored by {@link setUserValue()} * * @param string $cookie_name cookie name * @param mixed $cfg_value config value * * @return mixed */ function getUserValue($cookie_name, $cfg_value) { $cookie_exists = isset($_COOKIE) && !empty($_COOKIE[$cookie_name]); $prefs_type = $this->get('user_preferences'); if ($prefs_type == 'db') { // permanent user preferences value exists, remove cookie if ($cookie_exists) { $this->removeCookie($cookie_name); } } else if ($cookie_exists) { return $_COOKIE[$cookie_name]; } // return value from $cfg array return $cfg_value; } /** * set source * * @param string $source source * * @return void */ function setSource($source) { $this->source = trim($source); } /** * check config source * * @return boolean whether source is valid or not */ function checkConfigSource() { if (! $this->getSource()) { // no configuration file set at all return false; } if (! file_exists($this->getSource())) { $this->source_mtime = 0; return false; } if (! is_readable($this->getSource())) { // manually check if file is readable // might be bug #3059806 Supporting running from CIFS/Samba shares $contents = false; $handle = @fopen($this->getSource(), 'r'); if ($handle !== false) { $contents = @fread($handle, 1); // reading 1 byte is enough to test @fclose($handle); } if ($contents === false) { $this->source_mtime = 0; PMA_fatalError( sprintf( function_exists('__') ? __('Existing configuration file (%s) is not readable.') : 'Existing configuration file (%s) is not readable.', $this->getSource() ) ); return false; } } return true; } /** * verifies the permissions on config file (if asked by configuration) * (must be called after config.inc.php has been merged) * * @return void */ function checkPermissions() { // Check for permissions (on platforms that support it): if ($this->get('CheckConfigurationPermissions')) { $perms = @fileperms($this->getSource()); if (!($perms === false) && ($perms & 2)) { // This check is normally done after loading configuration $this->checkWebServerOs(); if ($this->get('PMA_IS_WINDOWS') == 0) { $this->source_mtime = 0; /* Gettext is possibly still not loaded */ if (function_exists('__')) { $msg = __('Wrong permissions on configuration file, should not be world writable!'); } else { $msg = 'Wrong permissions on configuration file, should not be world writable!'; } PMA_fatalError($msg); } } } } /** * returns specific config setting * * @param string $setting config setting * * @return mixed value */ function get($setting) { if (isset($this->settings[$setting])) { return $this->settings[$setting]; } return null; } /** * sets configuration variable * * @param string $setting configuration option * @param string $value new value for configuration option * * @return void */ function set($setting, $value) { if (! isset($this->settings[$setting]) || $this->settings[$setting] != $value ) { $this->settings[$setting] = $value; $this->set_mtime = time(); } } /** * returns source for current config * * @return string config source */ function getSource() { return $this->source; } /** * returns a unique value to force a CSS reload if either the config * or the theme changes * must also check the pma_fontsize cookie in case there is no * config file * * @return int Summary of unix timestamps and fontsize, * to be unique on theme parameters change */ function getThemeUniqueValue() { if (null !== $this->get('fontsize')) { $fontsize = intval($this->get('fontsize')); } elseif (isset($_COOKIE['pma_fontsize'])) { $fontsize = intval($_COOKIE['pma_fontsize']); } else { $fontsize = 0; } return ( $fontsize + $this->source_mtime + $this->default_source_mtime + $this->get('user_preferences_mtime') + $_SESSION['PMA_Theme']->mtime_info + $_SESSION['PMA_Theme']->filesize_info); } /** * $cfg['PmaAbsoluteUri'] is a required directive else cookies won't be * set properly and, depending on browsers, inserting or updating a * record might fail * * @return bool */ function checkPmaAbsoluteUri() { // Setup a default value to let the people and lazy sysadmins work anyway, // they'll get an error if the autodetect code doesn't work $pma_absolute_uri = $this->get('PmaAbsoluteUri'); $is_https = $this->detectHttps(); if (strlen($pma_absolute_uri) < 5) { $url = array(); // If we don't have scheme, we didn't have full URL so we need to // dig deeper if (empty($url['scheme'])) { // Scheme if ($is_https) { $url['scheme'] = 'https'; } else { $url['scheme'] = 'http'; } // Host and port if (PMA_getenv('HTTP_HOST')) { // Prepend the scheme before using parse_url() since this // is not part of the RFC2616 Host request-header $parsed_url = parse_url( $url['scheme'] . '://' . PMA_getenv('HTTP_HOST') ); if (!empty($parsed_url['host'])) { $url = $parsed_url; } else { $url['host'] = PMA_getenv('HTTP_HOST'); } } elseif (PMA_getenv('SERVER_NAME')) { $url['host'] = PMA_getenv('SERVER_NAME'); } else { $this->error_pma_uri = true; return false; } // If we didn't set port yet... if (empty($url['port']) && PMA_getenv('SERVER_PORT')) { $url['port'] = PMA_getenv('SERVER_PORT'); } // And finally the path could be already set from REQUEST_URI if (empty($url['path'])) { // we got a case with nginx + php-fpm where PHP_SELF // was not set, so PMA_PHP_SELF was not set as well if (isset($GLOBALS['PMA_PHP_SELF'])) { $path = parse_url($GLOBALS['PMA_PHP_SELF']); } else { $path = parse_url(PMA_getenv('REQUEST_URI')); } $url['path'] = $path['path']; } } // Make url from parts we have $pma_absolute_uri = $url['scheme'] . '://'; // Was there user information? if (!empty($url['user'])) { $pma_absolute_uri .= $url['user']; if (!empty($url['pass'])) { $pma_absolute_uri .= ':' . $url['pass']; } $pma_absolute_uri .= '@'; } // Add hostname $pma_absolute_uri .= urlencode($url['host']); // Add port, if it not the default one if (! empty($url['port']) && (($url['scheme'] == 'http' && $url['port'] != 80) || ($url['scheme'] == 'https' && $url['port'] != 443)) ) { $pma_absolute_uri .= ':' . $url['port']; } // And finally path, without script name, the 'a' is there not to // strip our directory, when path is only /pmadir/ without filename. // Backslashes returned by Windows have to be changed. // Only replace backslashes by forward slashes if on Windows, // as the backslash could be valid on a non-Windows system. $this->checkWebServerOs(); if ($this->get('PMA_IS_WINDOWS') == 1) { $path = str_replace("\\", "/", dirname($url['path'] . 'a')); } else { $path = dirname($url['path'] . 'a'); } // To work correctly within transformations overview: if (defined('PMA_PATH_TO_BASEDIR') && PMA_PATH_TO_BASEDIR == '../../') { if ($this->get('PMA_IS_WINDOWS') == 1) { $path = str_replace("\\", "/", dirname(dirname($path))); } else { $path = dirname(dirname($path)); } } // PHP's dirname function would have returned a dot // when $path contains no slash if ($path == '.') { $path = ''; } // in vhost situations, there could be already an ending slash if (substr($path, -1) != '/') { $path .= '/'; } $pma_absolute_uri .= $path; // This is to handle the case of a reverse proxy if ($this->get('ForceSSL')) { $this->set('PmaAbsoluteUri', $pma_absolute_uri); $pma_absolute_uri = $this->getSSLUri(); $this->checkIsHttps(); } // We used to display a warning if PmaAbsoluteUri wasn't set, but now // the autodetect code works well enough that we don't display the // warning at all. The user can still set PmaAbsoluteUri manually. } else { // The URI is specified, however users do often specify this // wrongly, so we try to fix this. // Adds a trailing slash et the end of the phpMyAdmin uri if it // does not exist. if (substr($pma_absolute_uri, -1) != '/') { $pma_absolute_uri .= '/'; } // If URI doesn't start with http:// or https://, we will add // this. if (substr($pma_absolute_uri, 0, 7) != 'http://' && substr($pma_absolute_uri, 0, 8) != 'https://' ) { $pma_absolute_uri = ($is_https ? 'https' : 'http') . ':' . (substr($pma_absolute_uri, 0, 2) == '//' ? '' : '//') . $pma_absolute_uri; } } $this->set('PmaAbsoluteUri', $pma_absolute_uri); } /** * Converts currently used PmaAbsoluteUri to SSL based variant. * * @return String witch adjusted URI */ function getSSLUri() { // grab current URL $url = $this->get('PmaAbsoluteUri'); // Parse current URL $parsed = parse_url($url); // In case parsing has failed do stupid string replacement if ($parsed === false) { // Replace http protocol return preg_replace('@^http:@', 'https:', $url); } // Reconstruct URL using parsed parts return 'https://' . $parsed['host'] . ':443' . $parsed['path']; } /** * check selected collation_connection * * @todo check validity of $_REQUEST['collation_connection'] * * @return void */ function checkCollationConnection() { if (! empty($_REQUEST['collation_connection'])) { $this->set( 'collation_connection', strip_tags($_REQUEST['collation_connection']) ); } } /** * checks for font size configuration, and sets font size as requested by user * * @return void */ function checkFontsize() { $new_fontsize = ''; if (isset($_GET['set_fontsize'])) { $new_fontsize = $_GET['set_fontsize']; } elseif (isset($_POST['set_fontsize'])) { $new_fontsize = $_POST['set_fontsize']; } elseif (isset($_COOKIE['pma_fontsize'])) { $new_fontsize = $_COOKIE['pma_fontsize']; } if (preg_match('/^[0-9.]+(px|em|pt|\%)$/', $new_fontsize)) { $this->set('fontsize', $new_fontsize); } elseif (! $this->get('fontsize')) { // 80% would correspond to the default browser font size // of 16, but use 82% to help read the monoface font $this->set('fontsize', '82%'); } $this->setCookie('pma_fontsize', $this->get('fontsize'), '82%'); } /** * checks if upload is enabled * * @return void */ function checkUpload() { if (ini_get('file_uploads')) { $this->set('enable_upload', true); // if set "php_admin_value file_uploads Off" in httpd.conf // ini_get() also returns the string "Off" in this case: if ('off' == strtolower(ini_get('file_uploads'))) { $this->set('enable_upload', false); } } else { $this->set('enable_upload', false); } } /** * Maximum upload size as limited by PHP * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas * * this section generates $max_upload_size in bytes * * @return void */ function checkUploadSize() { if (! $filesize = ini_get('upload_max_filesize')) { $filesize = "5M"; } if ($postsize = ini_get('post_max_size')) { $this->set( 'max_upload_size', min(PMA_getRealSize($filesize), PMA_getRealSize($postsize)) ); } else { $this->set('max_upload_size', PMA_getRealSize($filesize)); } } /** * check for https * * @return void */ function checkIsHttps() { $this->set('is_https', $this->isHttps()); } /** * Checks if protocol is https * * This function checks if the https protocol is used in the PmaAbsoluteUri * configuration setting, as opposed to detectHttps() which checks if the * https protocol is used on the active connection. * * @return bool */ public function isHttps() { static $is_https = null; if (null !== $is_https) { return $is_https; } $url = parse_url($this->get('PmaAbsoluteUri')); if (isset($url['scheme']) && $url['scheme'] == 'https') { $is_https = true; } else { $is_https = false; } return $is_https; } /** * Detects whether https appears to be used. * * This function checks if the https protocol is used in the current connection * with the webserver, based on environment variables. * Please note that this just detects what we see, so * it completely ignores things like reverse proxies. * * @return bool */ function detectHttps() { $is_https = false; $url = array(); // At first we try to parse REQUEST_URI, it might contain full URL, if (PMA_getenv('REQUEST_URI')) { // produces E_WARNING if it cannot get parsed, e.g. '/foobar:/' $url = @parse_url(PMA_getenv('REQUEST_URI')); if ($url === false) { $url = array(); } } // If we don't have scheme, we didn't have full URL so we need to // dig deeper if (empty($url['scheme'])) { // Scheme if (PMA_getenv('HTTP_SCHEME')) { $url['scheme'] = PMA_getenv('HTTP_SCHEME'); } elseif (PMA_getenv('HTTPS') && strtolower(PMA_getenv('HTTPS')) == 'on' ) { $url['scheme'] = 'https'; // A10 Networks load balancer: } elseif (PMA_getenv('HTTP_HTTPS_FROM_LB') && strtolower(PMA_getenv('HTTP_HTTPS_FROM_LB')) == 'on') { $url['scheme'] = 'https'; } elseif (PMA_getenv('HTTP_X_FORWARDED_PROTO')) { $url['scheme'] = strtolower(PMA_getenv('HTTP_X_FORWARDED_PROTO')); } elseif (PMA_getenv('HTTP_FRONT_END_HTTPS') && strtolower(PMA_getenv('HTTP_FRONT_END_HTTPS')) == 'on' ) { $url['scheme'] = 'https'; } else { $url['scheme'] = 'http'; } } if (isset($url['scheme']) && $url['scheme'] == 'https') { $is_https = true; } else { $is_https = false; } return $is_https; } /** * detect correct cookie path * * @return void */ function checkCookiePath() { $this->set('cookie_path', $this->getCookiePath()); } /** * Get cookie path * * @return string */ public function getCookiePath() { static $cookie_path = null; if (null !== $cookie_path && !defined('TESTSUITE')) { return $cookie_path; } $parsed_url = parse_url($this->get('PmaAbsoluteUri')); $cookie_path = $parsed_url['path']; return $cookie_path; } /** * enables backward compatibility * * @return void */ function enableBc() { $GLOBALS['cfg'] = $this->settings; $GLOBALS['default_server'] = $this->default_server; unset($this->default_server); $GLOBALS['collation_connection'] = $this->get('collation_connection'); $GLOBALS['is_upload'] = $this->get('enable_upload'); $GLOBALS['max_upload_size'] = $this->get('max_upload_size'); $GLOBALS['cookie_path'] = $this->get('cookie_path'); $GLOBALS['is_https'] = $this->get('is_https'); $defines = array( 'PMA_VERSION', 'PMA_THEME_VERSION', 'PMA_THEME_GENERATION', 'PMA_PHP_STR_VERSION', 'PMA_PHP_INT_VERSION', 'PMA_IS_WINDOWS', 'PMA_IS_IIS', 'PMA_IS_GD2', 'PMA_USR_OS', 'PMA_USR_BROWSER_VER', 'PMA_USR_BROWSER_AGENT' ); foreach ($defines as $define) { if (! defined($define)) { define($define, $this->get($define)); } } } /** * returns options for font size selection * * @param string $current_size current selected font size with unit * * @return array selectable font sizes * * @static */ static protected function getFontsizeOptions($current_size = '82%') { $unit = preg_replace('/[0-9.]*/', '', $current_size); $value = preg_replace('/[^0-9.]*/', '', $current_size); $factors = array(); $options = array(); $options["$value"] = $value . $unit; if ($unit === '%') { $factors[] = 1; $factors[] = 5; $factors[] = 10; } elseif ($unit === 'em') { $factors[] = 0.05; $factors[] = 0.2; $factors[] = 1; } elseif ($unit === 'pt') { $factors[] = 0.5; $factors[] = 2; } elseif ($unit === 'px') { $factors[] = 1; $factors[] = 5; $factors[] = 10; } else { //unknown font size unit $factors[] = 0.05; $factors[] = 0.2; $factors[] = 1; $factors[] = 5; $factors[] = 10; } foreach ($factors as $key => $factor) { $option_inc = $value + $factor; $option_dec = $value - $factor; while (count($options) < 21) { $options["$option_inc"] = $option_inc . $unit; if ($option_dec > $factors[0]) { $options["$option_dec"] = $option_dec . $unit; } $option_inc += $factor; $option_dec -= $factor; if (isset($factors[$key + 1]) && $option_inc >= $value + $factors[$key + 1] ) { break; } } } ksort($options); return $options; } /** * returns html selectbox for font sizes * * @static * * @return string html selectbox */ static protected function getFontsizeSelection() { $current_size = $GLOBALS['PMA_Config']->get('fontsize'); // for the case when there is no config file (this is supported) if (empty($current_size)) { if (isset($_COOKIE['pma_fontsize'])) { $current_size = htmlspecialchars($_COOKIE['pma_fontsize']); } else { $current_size = '82%'; } } $options = PMA_Config::getFontsizeOptions($current_size); $return = '<label for="select_fontsize">' . __('Font size') . ':</label>' . "\n" . '<select name="set_fontsize" id="select_fontsize"' . ' class="autosubmit">' . "\n"; foreach ($options as $option) { $return .= '<option value="' . $option . '"'; if ($option == $current_size) { $return .= ' selected="selected"'; } $return .= '>' . $option . '</option>' . "\n"; } $return .= '</select>'; return $return; } /** * return complete font size selection form * * @static * * @return string html selectbox */ static public function getFontsizeForm() { return '<form name="form_fontsize_selection" id="form_fontsize_selection"' . ' method="get" action="index.php" class="disableAjax">' . "\n" . PMA_generate_common_hidden_inputs() . "\n" . PMA_Config::getFontsizeSelection() . "\n" . '</form>'; } /** * removes cookie * * @param string $cookie name of cookie to remove * * @return boolean result of setcookie() */ function removeCookie($cookie) { if (defined('TESTSUITE')) { if (isset($_COOKIE[$cookie])) { unset($_COOKIE[$cookie]); } return true; } return setcookie( $cookie, '', time() - 3600, $this->getCookiePath(), '', $this->isHttps() ); } /** * sets cookie if value is different from current cookie value, * or removes if value is equal to default * * @param string $cookie name of cookie to remove * @param mixed $value new cookie value * @param string $default default value * @param int $validity validity of cookie in seconds (default is one month) * @param bool $httponly whether cookie is only for HTTP (and not for scripts) * * @return boolean result of setcookie() */ function setCookie($cookie, $value, $default = null, $validity = null, $httponly = true ) { if (strlen($value) && null !== $default && $value === $default) { // default value is used if (isset($_COOKIE[$cookie])) { // remove cookie return $this->removeCookie($cookie); } return false; } if (! strlen($value) && isset($_COOKIE[$cookie])) { // remove cookie, value is empty return $this->removeCookie($cookie); } if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) { // set cookie with new value /* Calculate cookie validity */ if ($validity === null) { $validity = time() + 2592000; } elseif ($validity == 0) { $validity = 0; } else { $validity = time() + $validity; } if (defined('TESTSUITE')) { $_COOKIE[$cookie] = $value; return true; } return setcookie( $cookie, $value, $validity, $this->getCookiePath(), '', $this->isHttps(), $httponly ); } // cookie has already $value as value return true; } } ?>
zhyee/djbbs
myadmin2/libraries/Config.class.php
PHP
apache-2.0
61,227
[ 30522, 1026, 1029, 25718, 1013, 1008, 6819, 2213, 1024, 2275, 7818, 2696, 2497, 25430, 1027, 1018, 24529, 1027, 1018, 8541, 1027, 1018, 1024, 1008, 1013, 1013, 1008, 1008, 1008, 9563, 8304, 1012, 1008, 1008, 1030, 7427, 25718, 8029, 4215, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>circuits: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.0 / circuits - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> circuits <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-24 18:15:59 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-24 18:15:59 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/circuits&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Circuits&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: hardware verification&quot; &quot;category: Computer Science/Architecture&quot; ] authors: [ &quot;Laurent Arditi&quot; ] bug-reports: &quot;https://github.com/coq-contribs/circuits/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/circuits.git&quot; synopsis: &quot;Some proofs of hardware (adder, multiplier, memory block instruction)&quot; description: &quot;&quot;&quot; definition and proof of a combinatorial adder, a sequential multiplier, a memory block instruction&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/circuits/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=c37c234a02f07103936671d8488c68f4&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-circuits.8.9.0 coq.8.8.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0). The following dependencies couldn&#39;t be met: - coq-circuits -&gt; coq &gt;= 8.9 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-circuits.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.04.2-2.0.5/released/8.8.0/circuits/8.9.0.html
HTML
mit
6,997
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 418...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!-- HTML header for doxygen 1.8.18--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.9.2"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>OR-Tools: ScipMPCallbackContext</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="orLogo.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">OR-Tools &#160;<span id="projectnumber">9.2</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.9.2 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */ var searchBox = new SearchBox("searchBox", "search",'Search','.html'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */ </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&amp;dn=expat.txt MIT */ $(document).ready(function(){initNavTree('classoperations__research_1_1_scip_m_p_callback_context.html',''); initResizable(); }); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="classoperations__research_1_1_scip_m_p_callback_context-members.html">List of all members</a> </div> <div class="headertitle"><div class="title">ScipMPCallbackContext</div></div> </div><!--header--> <div class="contents"> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01051">1051</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a id="pub-methods" name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a10a6fee706e3a27dd9bbcd8c7759064a"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#a10a6fee706e3a27dd9bbcd8c7759064a">ScipMPCallbackContext</a> (const <a class="el" href="classoperations__research_1_1_scip_constraint_handler_context.html">ScipConstraintHandlerContext</a> *scip_context, bool at_integer_solution)</td></tr> <tr class="separator:a10a6fee706e3a27dd9bbcd8c7759064a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa78ec98396f42ae2122a53535813f938"><td class="memItemLeft" align="right" valign="top"><a class="el" href="namespaceoperations__research.html#a4f0b2adea9a4297f27df941fe3ed3831">MPCallbackEvent</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#aa78ec98396f42ae2122a53535813f938">Event</a> () override</td></tr> <tr class="separator:aa78ec98396f42ae2122a53535813f938"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a35b0a5ff10cf288bef84d8a90114aafc"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#a35b0a5ff10cf288bef84d8a90114aafc">CanQueryVariableValues</a> () override</td></tr> <tr class="separator:a35b0a5ff10cf288bef84d8a90114aafc"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afc5ebc320e7aa4ad2c0d8aa312ed6465"><td class="memItemLeft" align="right" valign="top">double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#afc5ebc320e7aa4ad2c0d8aa312ed6465">VariableValue</a> (const <a class="el" href="classoperations__research_1_1_m_p_variable.html">MPVariable</a> *variable) override</td></tr> <tr class="separator:afc5ebc320e7aa4ad2c0d8aa312ed6465"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aaf98ff95af0e9af5addadb5b3c271fc9"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#aaf98ff95af0e9af5addadb5b3c271fc9">AddCut</a> (const <a class="el" href="classoperations__research_1_1_linear_range.html">LinearRange</a> &amp;cutting_plane) override</td></tr> <tr class="separator:aaf98ff95af0e9af5addadb5b3c271fc9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a79b0b72307928b949a6818ef134c4b2f"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#a79b0b72307928b949a6818ef134c4b2f">AddLazyConstraint</a> (const <a class="el" href="classoperations__research_1_1_linear_range.html">LinearRange</a> &amp;lazy_constraint) override</td></tr> <tr class="separator:a79b0b72307928b949a6818ef134c4b2f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:acc4e362d92c1d8ec8453ff089329f943"><td class="memItemLeft" align="right" valign="top">double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#acc4e362d92c1d8ec8453ff089329f943">SuggestSolution</a> (const absl::flat_hash_map&lt; const <a class="el" href="classoperations__research_1_1_m_p_variable.html">MPVariable</a> *, double &gt; &amp;solution) override</td></tr> <tr class="separator:acc4e362d92c1d8ec8453ff089329f943"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a30073c763dbaefec43cc583108734f76"><td class="memItemLeft" align="right" valign="top">int64_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#a30073c763dbaefec43cc583108734f76">NumExploredNodes</a> () override</td></tr> <tr class="separator:a30073c763dbaefec43cc583108734f76"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a663fa38e30137aa88e690908fc8e4885"><td class="memItemLeft" align="right" valign="top">const std::vector&lt; <a class="el" href="structoperations__research_1_1_callback_range_constraint.html">CallbackRangeConstraint</a> &gt; &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html#a663fa38e30137aa88e690908fc8e4885">constraints_added</a> ()</td></tr> <tr class="separator:a663fa38e30137aa88e690908fc8e4885"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a id="a10a6fee706e3a27dd9bbcd8c7759064a" name="a10a6fee706e3a27dd9bbcd8c7759064a"></a> <h2 class="memtitle"><span class="permalink"><a href="#a10a6fee706e3a27dd9bbcd8c7759064a">&#9670;&nbsp;</a></span>ScipMPCallbackContext()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html">ScipMPCallbackContext</a> </td> <td>(</td> <td class="paramtype">const <a class="el" href="classoperations__research_1_1_scip_constraint_handler_context.html">ScipConstraintHandlerContext</a> *&#160;</td> <td class="paramname"><em>scip_context</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&#160;</td> <td class="paramname"><em>at_integer_solution</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01053">1053</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a id="aaf98ff95af0e9af5addadb5b3c271fc9" name="aaf98ff95af0e9af5addadb5b3c271fc9"></a> <h2 class="memtitle"><span class="permalink"><a href="#aaf98ff95af0e9af5addadb5b3c271fc9">&#9670;&nbsp;</a></span>AddCut()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void AddCut </td> <td>(</td> <td class="paramtype">const <a class="el" href="classoperations__research_1_1_linear_range.html">LinearRange</a> &amp;&#160;</td> <td class="paramname"><em>cutting_plane</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#aad0fd4b98cffeb1caa42d0bf3032607b">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01074">1074</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="a79b0b72307928b949a6818ef134c4b2f" name="a79b0b72307928b949a6818ef134c4b2f"></a> <h2 class="memtitle"><span class="permalink"><a href="#a79b0b72307928b949a6818ef134c4b2f">&#9670;&nbsp;</a></span>AddLazyConstraint()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void AddLazyConstraint </td> <td>(</td> <td class="paramtype">const <a class="el" href="classoperations__research_1_1_linear_range.html">LinearRange</a> &amp;&#160;</td> <td class="paramname"><em>lazy_constraint</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#aa1db5c0051875f7406a147aed7a13649">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01082">1082</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="a35b0a5ff10cf288bef84d8a90114aafc" name="a35b0a5ff10cf288bef84d8a90114aafc"></a> <h2 class="memtitle"><span class="permalink"><a href="#a35b0a5ff10cf288bef84d8a90114aafc">&#9670;&nbsp;</a></span>CanQueryVariableValues()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">bool CanQueryVariableValues </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#acb9490649ae0b6ce2fd9b7d5ec79409e">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01065">1065</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="a663fa38e30137aa88e690908fc8e4885" name="a663fa38e30137aa88e690908fc8e4885"></a> <h2 class="memtitle"><span class="permalink"><a href="#a663fa38e30137aa88e690908fc8e4885">&#9670;&nbsp;</a></span>constraints_added()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">const std::vector&lt; <a class="el" href="structoperations__research_1_1_callback_range_constraint.html">CallbackRangeConstraint</a> &gt; &amp; constraints_added </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01106">1106</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="aa78ec98396f42ae2122a53535813f938" name="aa78ec98396f42ae2122a53535813f938"></a> <h2 class="memtitle"><span class="permalink"><a href="#aa78ec98396f42ae2122a53535813f938">&#9670;&nbsp;</a></span>Event()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="namespaceoperations__research.html#a4f0b2adea9a4297f27df941fe3ed3831">MPCallbackEvent</a> Event </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#a114b177c99f427b6d0d6b1b379b5838a">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01058">1058</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="a30073c763dbaefec43cc583108734f76" name="a30073c763dbaefec43cc583108734f76"></a> <h2 class="memtitle"><span class="permalink"><a href="#a30073c763dbaefec43cc583108734f76">&#9670;&nbsp;</a></span>NumExploredNodes()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">int64_t NumExploredNodes </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#a44b21129261e8cdc93d44c39212ba1dd">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01095">1095</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="acc4e362d92c1d8ec8453ff089329f943" name="acc4e362d92c1d8ec8453ff089329f943"></a> <h2 class="memtitle"><span class="permalink"><a href="#acc4e362d92c1d8ec8453ff089329f943">&#9670;&nbsp;</a></span>SuggestSolution()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">double SuggestSolution </td> <td>(</td> <td class="paramtype">const absl::flat_hash_map&lt; const <a class="el" href="classoperations__research_1_1_m_p_variable.html">MPVariable</a> *, double &gt; &amp;&#160;</td> <td class="paramname"><em>solution</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#aef6f1a998a5e8be2a006cc8d0728975d">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01090">1090</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <a id="afc5ebc320e7aa4ad2c0d8aa312ed6465" name="afc5ebc320e7aa4ad2c0d8aa312ed6465"></a> <h2 class="memtitle"><span class="permalink"><a href="#afc5ebc320e7aa4ad2c0d8aa312ed6465">&#9670;&nbsp;</a></span>VariableValue()</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">double VariableValue </td> <td>(</td> <td class="paramtype">const <a class="el" href="classoperations__research_1_1_m_p_variable.html">MPVariable</a> *&#160;</td> <td class="paramname"><em>variable</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">override</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classoperations__research_1_1_m_p_callback_context.html#a83fb66141e4b17ee11bfa9e04dc66563">MPCallbackContext</a>.</p> <p class="definition">Definition at line <a class="el" href="scip__interface_8cc_source.html#l01069">1069</a> of file <a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a>.</p> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li><a class="el" href="scip__interface_8cc_source.html">scip_interface.cc</a></li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- HTML footer for doxygen 1.8.18--> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceoperations__research.html">operations_research</a></li><li class="navelem"><a class="el" href="classoperations__research_1_1_scip_m_p_callback_context.html">ScipMPCallbackContext</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.2 </li> </ul> </div> </body> </html>
google/or-tools
docs/cpp/classoperations__research_1_1_scip_m_p_callback_context.html
HTML
apache-2.0
21,214
[ 30522, 1026, 999, 1011, 1011, 16129, 20346, 2005, 2079, 18037, 6914, 1015, 1012, 1022, 1012, 2324, 1011, 1011, 1028, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 1060, 11039, 19968,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IWorkbookFunctionsCumPrincRequestBuilder. /// </summary> public partial interface IWorkbookFunctionsCumPrincRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IWorkbookFunctionsCumPrincRequest Request(IEnumerable<Option> options = null); } }
garethj-msft/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsCumPrincRequestBuilder.cs
C#
mit
997
[ 30522, 1013, 1013, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/bin/bash read -p "REALLY kill all your jobs? <y/n>? " [ "$REPLY" != "y" ] && exit ./view_jobs.sh | cut -d'.' -f1 | xargs qdel
JohnDickerson/EnvyFree
experiments/kill_all_jobs.sh
Shell
gpl-2.0
133
[ 30522, 1001, 999, 1013, 8026, 1013, 24234, 3191, 1011, 1052, 1000, 2428, 3102, 2035, 2115, 5841, 1029, 1026, 1061, 1013, 1050, 1028, 1029, 1000, 1031, 1000, 1002, 7514, 1000, 999, 1027, 1000, 1061, 1000, 1033, 1004, 1004, 6164, 1012, 1013...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import requests import copy # Получаем участников группы FB def fb_get_group_members(fb_page_id, access_token): url = 'https://graph.facebook.com/v2.8/%s/members?limit=1000&access_token=%s' % (fb_page_id, access_token) fb_group_members = {'status':'OK', 'data':{'members':[], 'users_count':0}} while True: response = requests.get(url) if response.status_code == 200: try: keys = response.json().keys() if 'data' in keys: #title_id += [ id['id'] for id in content ] content = response.json()['data'] keys = response.json().keys() url = '' if 'paging' in keys: keys = response.json()['paging'].keys() if 'next' in keys: url = response.json()['paging']['next'] for member in content: member['is_group_mamber'] = 1 fb_group_members['data']['members'].append(member) if url =='': break except (KeyError, TypeError): fb_group_members['status'] = 'Unknown error' break else: fb_group_members['status'] = str(response.status_code) break fb_group_members['data']['users_count'] = len(fb_group_members['data']['members']) return fb_group_members # получаем общую информацию о группе def fb_get_group_data(fb_page_id, access_token): url = 'https://graph.facebook.com/v2.8/%s/?fields=id,name&access_token=%s' % (fb_page_id, access_token) fb_group = {'status':'OK', 'data':{'id':'','name':'', 'updated_time':'','members':[], 'users_count':0, 'all_users':[] }} response =requests.get(url) if response.status_code == 200: fb_data = fb_group['data'] data = response.json() keys = data.keys() if 'id' in keys: fb_data['id'] = data['id'] else: fb_group['status'] = 'Missing group id' if 'name' in keys: fb_data['name'] = data['name'] else: fb_group['status'] = 'Missing group name' ''' if 'updated_time' in keys: fb_data['updated_time'] = data['updated_time'] ''' members = fb_get_group_members(fb_page_id, access_token) if members['status']== 'OK': fb_group['data']['members'] = copy.deepcopy(members['data']['members']) fb_group['data']['users_count'] = members['data']['users_count'] fb_group['data']['all_users'] = copy.deepcopy(members['data']['members']) else: fb_group['status'] = str(response.status_code) return fb_group #-----Получаем все посты из группы------- def fb_get_all_posts(fb_page_id, access_token): url = 'https://graph.facebook.com/v2.8/%s/feed?fields=id,name,link,message,from,updated_time,created_time&access_token=%s' % (fb_page_id, access_token) fb_posts = {'status':'OK', 'data':{'posts':[],'posts_count':0}} #fb_posts = {'status':'OK', 'data':{'id':'','name':'', 'updated_time':'','link':'', 'message':''}} while True: response = requests.get(url) # print(response.status_code) if response.status_code == 200: try: keys = response.json().keys() #найти is jason if 'data' in keys: content = response.json()['data'] keys = response.json().keys() url = '' if 'paging' in keys: keys = response.json()['paging'].keys() if 'next' in keys: url = response.json()['paging']['next'] for post in content: fb_posts['data']['posts'].append(post) if url =='': break except (KeyError, TypeError): fb_posts['status'] = 'Unknown error' break else: fb_posts['status'] = str(response.status_code) break fb_posts['data']['posts_count'] = len(fb_posts['data']['posts']) return fb_posts #получаем все лайки поста def fb_get_post_likes(post_id, access_token): url = 'https://graph.facebook.com/v2.8/%s/reactions/?access_token=%s' % (post_id, access_token) fb_likes = {'status':'OK', 'data':{'likes':[],'likes_count':0}} while True: response = requests.get(url) if response.status_code == 200: try: keys = response.json().keys() #найти is jason if 'data' in keys: content = response.json()['data'] keys = response.json().keys() url = '' if 'paging' in keys: keys = response.json()['paging'].keys() if 'next' in keys: url = response.json()['paging']['next'] for fb_like in content: fb_likes['data']['likes'].append(fb_like) if url =='': break except (KeyError, TypeError): fb_likes['status'] = 'Unknown error' break else: fb_likes['status'] = str(response.status_code) break fb_likes['data']['likes_count'] = len(fb_likes['data']['likes']) return fb_likes #получаем все комментарии поста def fb_get_post_comments(post_id, access_token): url = 'https://graph.facebook.com/v2.8/%s/comments/?fields=id,message,from,updated_time,created_time&access_token=%s' % (post_id, access_token) fb_comments = {'status':'OK', 'data':{'comments':[],'comments_count':0}} while True: response = requests.get(url) if response.status_code == 200: try: keys = response.json().keys() #найти is jason if 'data' in keys: content = response.json()['data'] keys = response.json().keys() url = '' if 'paging' in keys: keys = response.json()['paging'].keys() if 'next' in keys: url = response.json()['paging']['next'] for fb_comment in content: fb_comments['data']['comments'].append(fb_comment) if url =='': break except (KeyError, TypeError): fb_comments['status'] = 'Unknown error' break else: fb_comments['status'] = str(response.status_code) break fb_comments['data']['comments_count'] = len(fb_comments['data']['comments']) return fb_comments # Получаем все данные о странице def fb_get_all_data(fb_page_id, access_token): #считываем все данные группы fb_group = fb_get_group_data(fb_page_id, access_token) if fb_group['status'] == 'OK': print('Group id: %s name: %s' % (fb_group['data']['id'], fb_group['data']['name'])) print('User in group: %s' % fb_group['data']['users_count']) #пишем в бд в БД else: print(fb_group['status']) exit() #считываем все посты print('*************считываем все посты************') data = fb_get_all_posts(fb_page_id, access_token) if data['status'] == 'OK': fb_posts = copy.deepcopy(data['data']['posts']) posts_count = data['data']['posts_count'] # print(fb_posts[0]) print('Posts in group: %s' % posts_count) for fb_post in fb_posts: print('*************Пост %s от %s ************' % (fb_post['id'], fb_post['created_time'])) # тестиирум лайки к посту data = fb_get_post_likes(fb_post['id'], access_token) if data['status'] == 'OK': fb_post['likes'] = copy.deepcopy(data['data']['likes']) fb_post['likes_count'] = data['data']['likes_count'] #print('post likes to users') for user_like in fb_post['likes']: #print(user_like) if not user_like['id'] in fb_group['data']['members']: #print('new user %s'% user_like) fb_group['data']['all_users'].append({'id':user_like['id'],'name':user_like['name'], 'is_group_mamber':0}) print('Likes count: %s' % fb_post['likes_count']) else: print(data['status']) #тестируем комментарии к посту data = fb_get_post_comments(fb_post['id'], access_token) if data['status'] == 'OK': fb_post['comments'] = copy.deepcopy(data['data']['comments']) fb_post['comments_count'] = data['data']['comments_count'] print('Comments count: %s' % fb_post['comments_count'] ) #print('post likes to users') for user_comments in fb_post['comments']: #print(user_like) keys = user_comments.keys() comment_user_id = user_comments['from']['id'] if 'from' in keys else '' comment_user_name = user_comments['from']['name'] if 'from' in keys else '' if (not comment_user_id == '') and (not user_comments in fb_group['data']['members']): #print('new user %s'% user_like) fb_group['data']['all_users'].append({'id':comment_user_id,'name':comment_user_name, 'is_group_mamber':0}) else: print(data['status']) fb_group['data']['posts'] = copy.deepcopy(fb_posts) fb_group['data']['posts_count'] = posts_count else: print(data['status']) #print('до %s' % fb_group) return fb_group if __name__ == '__main__': print ('Not runns in console')
eugeneks/zmeyka
fb_req.py
Python
mit
10,919
[ 30522, 12324, 11186, 12324, 6100, 1001, 1194, 14150, 29436, 29748, 29752, 10260, 15290, 29745, 1198, 29752, 10260, 29747, 22919, 18947, 10325, 23925, 19259, 1183, 16856, 29748, 29746, 29746, 29113, 1042, 2497, 13366, 1042, 2497, 1035, 30524, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright (c) 2013-2014 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Gabriel Roldan (Boundless) - initial implementation */ package org.locationtech.geogig.geotools.data; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import org.eclipse.jdt.annotation.Nullable; import org.geotools.data.DataStore; import org.geotools.data.Transaction; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.store.ContentDataStore; import org.geotools.data.store.ContentEntry; import org.geotools.data.store.ContentState; import org.geotools.feature.NameImpl; import org.locationtech.geogig.data.FindFeatureTypeTrees; import org.locationtech.geogig.model.ObjectId; import org.locationtech.geogig.model.Ref; import org.locationtech.geogig.model.RevObject.TYPE; import org.locationtech.geogig.model.RevTree; import org.locationtech.geogig.model.SymRef; import org.locationtech.geogig.plumbing.ForEachRef; import org.locationtech.geogig.plumbing.RefParse; import org.locationtech.geogig.plumbing.RevParse; import org.locationtech.geogig.plumbing.TransactionBegin; import org.locationtech.geogig.porcelain.AddOp; import org.locationtech.geogig.porcelain.CheckoutOp; import org.locationtech.geogig.porcelain.CommitOp; import org.locationtech.geogig.repository.Context; import org.locationtech.geogig.repository.GeogigTransaction; import org.locationtech.geogig.repository.NodeRef; import org.locationtech.geogig.repository.Repository; import org.locationtech.geogig.repository.WorkingTree; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.Name; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; /** * A GeoTools {@link DataStore} that serves and edits {@link SimpleFeature}s in a geogig repository. * <p> * Multiple instances of this kind of data store may be created against the same repository, * possibly working against different {@link #setHead(String) heads}. * <p> * A head is any commit in GeoGig. If a head has a branch pointing at it then the store allows * transactions, otherwise no data modifications may be made. * * A branch in Geogig is a separate line of history that may or may not share a common ancestor with * another branch. In the later case the branch is called "orphan" and by convention the default * branch is called "master", which is created when the geogig repo is first initialized, but does * not necessarily exist. * <p> * Every read operation (like in {@link #getFeatureSource(Name)}) reads committed features out of * the configured "head" branch. Write operations are only supported if a {@link Transaction} is * set, in which case a {@link GeogigTransaction} is tied to the geotools transaction by means of a * {@link GeogigTransactionState}. During the transaction, read operations will read from the * transaction's {@link WorkingTree} in order to "see" features that haven't been committed yet. * <p> * When the transaction is committed, the changes made inside that transaction are merged onto the * actual repository. If any other change was made to the repository meanwhile, a rebase will be * attempted, and the transaction commit will fail if the rebase operation finds any conflict. This * provides for optimistic locking and reduces thread contention. * */ public class GeoGigDataStore extends ContentDataStore implements DataStore { private final Repository geogig; /** @see #setHead(String) */ private String refspec; /** When the configured head is not a branch, we disallow transactions */ private boolean allowTransactions = true; public GeoGigDataStore(Repository geogig) { super(); Preconditions.checkNotNull(geogig); this.geogig = geogig; } @Override public void dispose() { super.dispose(); geogig.close(); } /** * Instructs the datastore to operate against the specified refspec, or against the checked out * branch, whatever it is, if the argument is {@code null}. * * Editing capabilities are disabled if the refspec is not a local branch. * * @param refspec the name of the branch to work against, or {@code null} to default to the * currently checked out branch * @see #getConfiguredBranch() * @see #getOrFigureOutHead() * @throws IllegalArgumentException if {@code refspec} is not null and no such commit exists in * the repository */ public void setHead(@Nullable final String refspec) throws IllegalArgumentException { if (refspec == null) { allowTransactions = true; // when no branch name is set we assume we should make // transactions against the current HEAD } else { final Context context = getCommandLocator(null); Optional<ObjectId> rev = context.command(RevParse.class).setRefSpec(refspec).call(); if (!rev.isPresent()) { throw new IllegalArgumentException("Bad ref spec: " + refspec); } Optional<Ref> branchRef = context.command(RefParse.class).setName(refspec).call(); if (branchRef.isPresent()) { Ref ref = branchRef.get(); if (ref instanceof SymRef) { ref = context.command(RefParse.class).setName(((SymRef) ref).getTarget()).call() .orNull(); } Preconditions.checkArgument(ref != null, "refSpec is a dead symref: " + refspec); if (ref.getName().startsWith(Ref.HEADS_PREFIX)) { allowTransactions = true; } else { allowTransactions = false; } } else { allowTransactions = false; } } this.refspec = refspec; } public String getOrFigureOutHead() { String branch = getConfiguredHead(); if (branch != null) { return branch; } return getCheckedOutBranch(); } public Repository getGeogig() { return geogig; } /** * @return the configured refspec of the commit this datastore works against, or {@code null} if * no head in particular has been set, meaning the data store works against whatever the * currently checked out branch is. */ @Nullable public String getConfiguredHead() { return this.refspec; } /** * @return whether or not we can support transactions against the configured head */ public boolean isAllowTransactions() { return this.allowTransactions; } /** * @return the name of the currently checked out branch in the repository, not necessarily equal * to {@link #getConfiguredBranch()}, or {@code null} in the (improbable) case HEAD is * on a dettached state (i.e. no local branch is currently checked out) */ @Nullable public String getCheckedOutBranch() { Optional<Ref> head = getCommandLocator(null).command(RefParse.class).setName(Ref.HEAD) .call(); if (!head.isPresent()) { return null; } Ref headRef = head.get(); if (!(headRef instanceof SymRef)) { return null; } String refName = ((SymRef) headRef).getTarget(); Preconditions.checkState(refName.startsWith(Ref.HEADS_PREFIX)); String branchName = refName.substring(Ref.HEADS_PREFIX.length()); return branchName; } public ImmutableList<String> getAvailableBranches() { ImmutableSet<Ref> heads = getCommandLocator(null).command(ForEachRef.class) .setPrefixFilter(Ref.HEADS_PREFIX).call(); List<String> list = Lists.newArrayList(Collections2.transform(heads, (ref) -> { String branchName = ref.getName().substring(Ref.HEADS_PREFIX.length()); return branchName; })); Collections.sort(list); return ImmutableList.copyOf(list); } public Context getCommandLocator(@Nullable Transaction transaction) { Context commandLocator = null; if (transaction != null && !Transaction.AUTO_COMMIT.equals(transaction)) { GeogigTransactionState state; state = (GeogigTransactionState) transaction.getState(GeogigTransactionState.class); Optional<GeogigTransaction> geogigTransaction = state.getGeogigTransaction(); if (geogigTransaction.isPresent()) { commandLocator = geogigTransaction.get(); } } if (commandLocator == null) { commandLocator = geogig.context(); } return commandLocator; } public Name getDescriptorName(NodeRef treeRef) { Preconditions.checkNotNull(treeRef); Preconditions.checkArgument(TYPE.TREE.equals(treeRef.getType())); Preconditions.checkArgument(!treeRef.getMetadataId().isNull(), "NodeRef '%s' is not a feature type reference", treeRef.path()); return new NameImpl(getNamespaceURI(), NodeRef.nodeFromPath(treeRef.path())); } public NodeRef findTypeRef(Name typeName, @Nullable Transaction tx) { Preconditions.checkNotNull(typeName); final String localName = typeName.getLocalPart(); final List<NodeRef> typeRefs = findTypeRefs(tx); Collection<NodeRef> matches = Collections2.filter(typeRefs, new Predicate<NodeRef>() { @Override public boolean apply(NodeRef input) { return NodeRef.nodeFromPath(input.path()).equals(localName); } }); switch (matches.size()) { case 0: throw new NoSuchElementException( String.format("No tree ref matched the name: %s", localName)); case 1: return matches.iterator().next(); default: throw new IllegalArgumentException(String .format("More than one tree ref matches the name %s: %s", localName, matches)); } } @Override protected ContentState createContentState(ContentEntry entry) { return new ContentState(entry); } @Override protected ImmutableList<Name> createTypeNames() throws IOException { List<NodeRef> typeTrees = findTypeRefs(Transaction.AUTO_COMMIT); return ImmutableList .copyOf(Collections2.transform(typeTrees, (ref) -> getDescriptorName(ref))); } private List<NodeRef> findTypeRefs(@Nullable Transaction tx) { final String rootRef = getRootRef(tx); Context commandLocator = getCommandLocator(tx); List<NodeRef> typeTrees = commandLocator.command(FindFeatureTypeTrees.class) .setRootTreeRef(rootRef).call(); return typeTrees; } String getRootRef(@Nullable Transaction tx) { final String rootRef; if (null == tx || Transaction.AUTO_COMMIT.equals(tx)) { rootRef = getOrFigureOutHead(); } else { rootRef = Ref.WORK_HEAD; } return rootRef; } @Override protected GeogigFeatureStore createFeatureSource(ContentEntry entry) throws IOException { return new GeogigFeatureStore(entry); } /** * Creates a new feature type tree on the {@link #getOrFigureOutHead() current branch}. * <p> * Implementation detail: the operation is the homologous to starting a transaction, checking * out the current/configured branch, creating the type tree inside the transaction, issueing a * geogig commit, and committing the transaction for the created tree to be merged onto the * configured branch. */ @Override public void createSchema(SimpleFeatureType featureType) throws IOException { if (!allowTransactions) { throw new IllegalStateException("Configured head " + refspec + " is not a branch; transactions are not supported."); } GeogigTransaction tx = getCommandLocator(null).command(TransactionBegin.class).call(); boolean abort = false; try { String treePath = featureType.getName().getLocalPart(); // check out the datastore branch on the transaction space final String branch = getOrFigureOutHead(); tx.command(CheckoutOp.class).setForce(true).setSource(branch).call(); // now we can use the transaction working tree with the correct branch checked out WorkingTree workingTree = tx.workingTree(); workingTree.createTypeTree(treePath, featureType); tx.command(AddOp.class).addPattern(treePath).call(); tx.command(CommitOp.class).setMessage("Created feature type tree " + treePath).call(); tx.commit(); } catch (IllegalArgumentException alreadyExists) { abort = true; throw new IOException(alreadyExists.getMessage(), alreadyExists); } catch (Exception e) { abort = true; throw Throwables.propagate(e); } finally { if (abort) { tx.abort(); } } } // Deliberately leaving the @Override annotation commented out so that the class builds // both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x) // @Override public void removeSchema(Name name) throws IOException { throw new UnsupportedOperationException( "removeSchema not yet supported by geogig DataStore"); } // Deliberately leaving the @Override annotation commented out so that the class builds // both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x) // @Override public void removeSchema(String name) throws IOException { throw new UnsupportedOperationException( "removeSchema not yet supported by geogig DataStore"); } public static enum ChangeType { ADDED, REMOVED, CHANGED_NEW, CHANGED_OLD; } /** * Builds a FeatureSource (read-only) that fetches features out of the differences between two * root trees: a provided tree-ish as the left side of the comparison, and the datastore's * configured HEAD as the right side of the comparison. * <p> * E.g., to get all features of a given feature type that were removed between a given commit * and its parent: * * <pre> * <code> * String commitId = ... * GeoGigDataStore store = new GeoGigDataStore(geogig); * store.setHead(commitId); * FeatureSource removed = store.getDiffFeatureSource("roads", commitId + "~1", ChangeType.REMOVED); * </code> * </pre> * * @param typeName the feature type name to look up a type tree for in the datastore's current * {@link #getOrFigureOutHead() HEAD} * @param oldRoot a tree-ish string that resolves to the ROOT tree to be used as the left side * of the diff * @param changeType the type of change between {@code oldRoot} and {@link #getOrFigureOutHead() * head} to pick as the features to return. * @return a feature source whose features are computed out of the diff between the feature type * diffs between the given {@code oldRoot} and the datastore's * {@link #getOrFigureOutHead() HEAD}. */ public SimpleFeatureSource getDiffFeatureSource(final String typeName, final String oldRoot, final ChangeType changeType) throws IOException { Preconditions.checkNotNull(typeName, "typeName"); Preconditions.checkNotNull(oldRoot, "oldRoot"); Preconditions.checkNotNull(changeType, "changeType"); final Name name = name(typeName); final ContentEntry entry = ensureEntry(name); GeogigFeatureSource featureSource = new GeogigFeatureSource(entry); featureSource.setTransaction(Transaction.AUTO_COMMIT); featureSource.setChangeType(changeType); if (ObjectId.NULL.toString().equals(oldRoot) || RevTree.EMPTY_TREE_ID.toString().equals(oldRoot)) { featureSource.setOldRoot(null); } else { featureSource.setOldRoot(oldRoot); } return featureSource; } }
jodygarnett/GeoGig
src/datastore/src/main/java/org/locationtech/geogig/geotools/data/GeoGigDataStore.java
Java
lgpl-2.1
17,024
[ 30522, 1013, 1008, 9385, 1006, 1039, 1007, 2286, 1011, 2297, 5391, 3238, 1998, 2500, 1012, 30524, 1010, 1998, 2003, 2800, 2012, 1008, 16770, 1024, 1013, 1013, 7479, 1012, 13232, 1012, 8917, 1013, 8917, 1013, 5491, 1013, 3968, 2140, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<html> <head> </head> <body> <h2> But Honour Them As They Honour Men </h2> Thirdly, <span class="oldenglish"> for </span> <span class="oldenglish"> the </span> worship <span class="oldenglish"> which </span> naturally men exhibite <span class="oldenglish"> to </span> Powers invisible, <span class="oldenglish"> it </span> <span class="oldenglish"> can </span> <span class="oldenglish"> be </span> <span class="oldenglish"> no </span> other, <span class="oldenglish"> but </span> <span class="oldenglish"> such </span> <span class="french"> expressions </span> <span class="oldenglish"> of </span> <span class="oldnorse"> their </span> reverence, <span class="oldenglish"> as </span> <span class="oldnorse"> they </span> <span class="oldenglish"> would </span> <span class="oldfrench"> use </span> <span class="oldenglish"> towards </span> men; Gifts, Petitions, Thanks, <span class="oldfrench"> Submission </span> <span class="oldenglish"> of </span> Body, <span class="latin"> Considerate </span> Addresses, sober Behaviour, <span class="latin"> premeditated </span> Words, Swearing (that is, <span class="oldfrench"> assuring </span> <span class="oldenglish"> one </span> <span class="oldenglish"> another </span> <span class="oldenglish"> of </span> <span class="oldnorse"> their </span> promises,) <span class="oldenglish"> by </span> <span class="french"> invoking </span> them. <span class="oldenglish"> Beyond </span> <span class="oldenglish"> that </span> <span class="oldfrench"> reason </span> suggesteth nothing; <span class="oldenglish"> but </span> <span class="oldenglish"> leaves </span> <span class="oldnorse"> them </span> <span class="oldenglish"> either </span> <span class="oldenglish"> to </span> <span class="oldenglish"> rest </span> there; <span class="oldenglish"> or </span> <span class="oldenglish"> for </span> <span class="oldenglish"> further </span> ceremonies, <span class="oldenglish"> to </span> <span class="oldfrench"> rely </span> <span class="oldenglish"> on </span> <span class="oldenglish"> those </span> <span class="oldnorse"> they </span> <span class="oldenglish"> believe </span> <span class="oldenglish"> to </span> <span class="oldenglish"> be </span> <span class="oldenglish"> wiser </span> <span class="oldenglish"> than </span> themselves. </body> </html>
charlesreid1/wordswordswords
etymology/html/leviathan103.html
HTML
mit
2,705
[ 30522, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 1013, 2132, 1028, 1026, 2303, 1028, 1026, 1044, 2475, 1028, 2021, 6225, 2068, 2004, 2027, 6225, 2273, 1026, 1013, 1044, 2475, 1028, 2353, 2135, 1010, 1026, 8487, 2465, 1027, 1000, 2214, 13...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.lang; import com.intellij.lexer.Lexer; import com.intellij.lexer.LexerUtil; import com.intellij.psi.TokenType; import com.intellij.psi.impl.source.CharTableImpl; import com.intellij.psi.impl.source.CodeFragmentElement; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.*; import com.intellij.util.CharTable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class ASTFactory { public static final DefaultFactory DEFAULT = new DefaultFactory(); private static final CharTable WHITSPACES = new CharTableImpl(); @Nullable public abstract CompositeElement createComposite(IElementType type); @Nullable public LazyParseableElement createLazy(ILazyParseableElementType type, CharSequence text) { if (type instanceof IFileElementType) { return new FileElement(type, text); } return new LazyParseableElement(type, text); } @Nullable public abstract LeafElement createLeaf(IElementType type, CharSequence text); @NotNull public static LazyParseableElement lazy(ILazyParseableElementType type, CharSequence text) { ASTNode node = type.createNode(text); if (node != null) return (LazyParseableElement)node; if (type == TokenType.CODE_FRAGMENT) { return new CodeFragmentElement(null); } LazyParseableElement psi = factory(type).createLazy(type, text); return psi != null ? psi : DEFAULT.createLazy(type, text); } @Deprecated @NotNull public static LeafElement leaf(IElementType type, CharSequence fileText, int start, int end, CharTable table) { return leaf(type, table.intern(fileText, start, end)); } @NotNull public static LeafElement leaf(IElementType type, CharSequence text) { if (type == TokenType.WHITE_SPACE) { return new PsiWhiteSpaceImpl(text); } if (type instanceof ILeafElementType) { return (LeafElement)((ILeafElementType)type).createLeafNode(text); } final LeafElement customLeaf = factory(type).createLeaf(type, text); return customLeaf != null ? customLeaf : DEFAULT.createLeaf(type, text); } private static ASTFactory factory(IElementType type) { return LanguageASTFactory.INSTANCE.forLanguage(type.getLanguage()); } public static LeafElement whitespace(CharSequence text) { PsiWhiteSpaceImpl w = new PsiWhiteSpaceImpl(WHITSPACES.intern(text)); CodeEditUtil.setNodeGenerated(w, true); return w; } public static LeafElement leaf(IElementType type, CharSequence text, CharTable table) { return leaf(type, table.intern(text)); } public static LeafElement leaf(final Lexer lexer, final CharTable charTable) { return leaf(lexer.getTokenType(), LexerUtil.internToken(lexer, charTable)); } @NotNull public static CompositeElement composite(IElementType type) { if (type instanceof ICompositeElementType) { return (CompositeElement)((ICompositeElementType)type).createCompositeNode(); } if (type == TokenType.CODE_FRAGMENT) { return new CodeFragmentElement(null); } final CompositeElement customComposite = factory(type).createComposite(type); return customComposite != null ? customComposite : DEFAULT.createComposite(type); } private static class DefaultFactory extends ASTFactory { @Override @NotNull public CompositeElement createComposite(IElementType type) { if (type instanceof IFileElementType) { return new FileElement(type, null); } return new CompositeElement(type); } @Override @NotNull public LeafElement createLeaf(IElementType type, CharSequence text) { final Language lang = type.getLanguage(); final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(lang); if (parserDefinition != null) { if (parserDefinition.getCommentTokens().contains(type)) { return new PsiCommentImpl(type, text); } } return new LeafPsiElement(type, text); } } }
jexp/idea2
platform/lang-impl/src/com/intellij/lang/ASTFactory.java
Java
apache-2.0
4,716
[ 30522, 1013, 1008, 1008, 9385, 2456, 1011, 2268, 6892, 10024, 7076, 1055, 1012, 1054, 1012, 1051, 1012, 1008, 1008, 7000, 2104, 1996, 30524, 8917, 1013, 15943, 1013, 6105, 1011, 1016, 1012, 1014, 1008, 1008, 4983, 3223, 2011, 12711, 2375, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
'''The Example from Huang and Darwiche's Procedural Guide''' from __future__ import division from bayesian.factor_graph import * from bayesian.utils import make_key def f_a(a): return 1 / 2 def f_b(a, b): tt = dict( tt=0.5, ft=0.4, tf=0.5, ff=0.6) return tt[make_key(a, b)] def f_c(a, c): tt = dict( tt=0.7, ft=0.2, tf=0.3, ff=0.8) return tt[make_key(a, c)] def f_d(b, d): tt = dict( tt=0.9, ft=0.5, tf=0.1, ff=0.5) return tt[make_key(b, d)] def f_e(c, e): tt = dict( tt=0.3, ft=0.6, tf=0.7, ff=0.4) return tt[make_key(c, e)] def f_f(d, e, f): tt = dict( ttt=0.01, ttf=0.99, tft=0.01, tff=0.99, ftt=0.01, ftf=0.99, fft=0.99, fff=0.01) return tt[make_key(d, e, f)] def f_g(c, g): tt = dict( tt=0.8, tf=0.2, ft=0.1, ff=0.9) return tt[make_key(c, g)] def f_h(e, g, h): tt = dict( ttt=0.05, ttf=0.95, tft=0.95, tff=0.05, ftt=0.95, ftf=0.05, fft=0.95, fff=0.05) return tt[make_key(e, g, h)] if __name__ == '__main__': g = build_graph( f_a, f_b, f_c, f_d, f_e, f_f, f_g, f_h) g.n_samples = 1000 g.q()
kamijawa/ogc_server
bayesian/examples/factor_graphs/huang_darwiche.py
Python
mit
1,341
[ 30522, 1005, 1005, 1005, 1996, 2742, 2013, 15469, 1998, 18243, 12414, 2063, 1005, 1055, 24508, 5009, 1005, 1005, 1005, 2013, 1035, 1035, 2925, 1035, 1035, 12324, 2407, 2013, 3016, 25253, 1012, 5387, 1035, 10629, 12324, 1008, 2013, 3016, 252...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs */ #include <linux/kallsyms.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/utsname.h> #include <linux/hardirq.h> #include <linux/kdebug.h> #include <linux/module.h> #include <linux/ptrace.h> #include <linux/ftrace.h> #include <linux/kexec.h> #include <linux/bug.h> #include <linux/nmi.h> #include <linux/sysfs.h> #include <asm/stacktrace.h> int panic_on_unrecovered_nmi; int panic_on_io_nmi; unsigned int code_bytes = 64; int kstack_depth_to_print = 3 * STACKSLOTS_PER_LINE; static int die_counter; static void printk_stack_address(unsigned long address, int reliable, void *data) { printk("%s [<%p>] %s%pB\n", (char *)data, (void *)address, reliable ? "" : "? ", (void *)address); } void printk_address(unsigned long address) { pr_cont(" [<%p>] %pS\n", (void *)address, (void *)address); } #ifdef CONFIG_FUNCTION_GRAPH_TRACER static void print_ftrace_graph_addr(unsigned long addr, void *data, const struct stacktrace_ops *ops, struct thread_info *tinfo, int *graph) { struct task_struct *task; unsigned long ret_addr; int index; if (addr != (unsigned long)return_to_handler) return; task = tinfo->task; index = task->curr_ret_stack; if (!task->ret_stack || index < *graph) return; index -= *graph; ret_addr = task->ret_stack[index].ret; ops->address(data, ret_addr, 1); (*graph)++; } #else static inline void print_ftrace_graph_addr(unsigned long addr, void *data, const struct stacktrace_ops *ops, struct thread_info *tinfo, int *graph) { } #endif /* * x86-64 can have up to three kernel stacks: * process stack * interrupt stack * severe exception (double fault, nmi, stack fault, debug, mce) hardware stack */ static inline int valid_stack_ptr(struct thread_info *tinfo, void *p, unsigned int size, void *end) { void *t = tinfo; if (end) { if (p < end && p >= (end-THREAD_SIZE)) return 1; else return 0; } return p > t && p < t + THREAD_SIZE - size; } unsigned long print_context_stack(struct thread_info *tinfo, unsigned long *stack, unsigned long bp, const struct stacktrace_ops *ops, void *data, unsigned long *end, int *graph) { struct stack_frame *frame = (struct stack_frame *)bp; while (valid_stack_ptr(tinfo, stack, sizeof(*stack), end)) { unsigned long addr; addr = *stack; if (__kernel_text_address(addr)) { if ((unsigned long) stack == bp + sizeof(long)) { ops->address(data, addr, 1); frame = frame->next_frame; bp = (unsigned long) frame; } else { ops->address(data, addr, 0); } print_ftrace_graph_addr(addr, data, ops, tinfo, graph); } stack++; } return bp; } EXPORT_SYMBOL_GPL(print_context_stack); unsigned long print_context_stack_bp(struct thread_info *tinfo, unsigned long *stack, unsigned long bp, const struct stacktrace_ops *ops, void *data, unsigned long *end, int *graph) { struct stack_frame *frame = (struct stack_frame *)bp; unsigned long *ret_addr = &frame->return_address; while (valid_stack_ptr(tinfo, ret_addr, sizeof(*ret_addr), end)) { unsigned long addr = *ret_addr; if (!__kernel_text_address(addr)) break; if (ops->address(data, addr, 1)) break; frame = frame->next_frame; ret_addr = &frame->return_address; print_ftrace_graph_addr(addr, data, ops, tinfo, graph); } return (unsigned long)frame; } EXPORT_SYMBOL_GPL(print_context_stack_bp); static int print_trace_stack(void *data, char *name) { printk("%s <%s> ", (char *)data, name); return 0; } /* * Print one address/symbol entries per line. */ static int print_trace_address(void *data, unsigned long addr, int reliable) { touch_nmi_watchdog(); printk_stack_address(addr, reliable, data); return 0; } static const struct stacktrace_ops print_trace_ops = { .stack = print_trace_stack, .address = print_trace_address, .walk_stack = print_context_stack, }; void show_trace_log_lvl(struct task_struct *task, struct pt_regs *regs, unsigned long *stack, unsigned long bp, char *log_lvl) { printk("%sCall Trace:\n", log_lvl); dump_trace(task, regs, stack, bp, &print_trace_ops, log_lvl); } void show_trace(struct task_struct *task, struct pt_regs *regs, unsigned long *stack, unsigned long bp) { show_trace_log_lvl(task, regs, stack, bp, ""); } void show_stack(struct task_struct *task, unsigned long *sp) { unsigned long bp = 0; unsigned long stack; /* * Stack frames below this one aren't interesting. Don't show them * if we're printing for %current. */ if (!sp && (!task || task == current)) { sp = &stack; bp = stack_frame(current, NULL); } show_stack_log_lvl(task, NULL, sp, bp, ""); } static arch_spinlock_t die_lock = __ARCH_SPIN_LOCK_UNLOCKED; static int die_owner = -1; static unsigned int die_nest_count; unsigned long oops_begin(void) { int cpu; unsigned long flags; oops_enter(); /* racy, but better than risking deadlock. */ raw_local_irq_save(flags); cpu = smp_processor_id(); if (!arch_spin_trylock(&die_lock)) { if (cpu == die_owner) /* nested oops. should stop eventually */; else arch_spin_lock(&die_lock); } die_nest_count++; die_owner = cpu; console_verbose(); bust_spinlocks(1); return flags; } EXPORT_SYMBOL_GPL(oops_begin); NOKPROBE_SYMBOL(oops_begin); void oops_end(unsigned long flags, struct pt_regs *regs, int signr) { if (regs && kexec_should_crash(current)) crash_kexec(regs); bust_spinlocks(0); die_owner = -1; add_taint(TAINT_DIE, LOCKDEP_NOW_UNRELIABLE); die_nest_count--; if (!die_nest_count) /* Nest count reaches zero, release the lock. */ arch_spin_unlock(&die_lock); raw_local_irq_restore(flags); oops_exit(); if (!signr) return; if (in_interrupt()) panic("Fatal exception in interrupt"); if (panic_on_oops) panic("Fatal exception"); do_exit(signr); } NOKPROBE_SYMBOL(oops_end); int __die(const char *str, struct pt_regs *regs, long err) { #ifdef CONFIG_X86_32 unsigned short ss; unsigned long sp; #endif printk(KERN_DEFAULT "%s: %04lx [#%d] ", str, err & 0xffff, ++die_counter); #ifdef CONFIG_PREEMPT printk("PREEMPT "); #endif #ifdef CONFIG_SMP printk("SMP "); #endif if (debug_pagealloc_enabled()) printk("DEBUG_PAGEALLOC "); #ifdef CONFIG_KASAN printk("KASAN"); #endif printk("\n"); if (notify_die(DIE_OOPS, str, regs, err, current->thread.trap_nr, SIGSEGV) == NOTIFY_STOP) return 1; print_modules(); show_regs(regs); #ifdef CONFIG_X86_32 if (user_mode(regs)) { sp = regs->sp; ss = regs->ss & 0xffff; } else { sp = kernel_stack_pointer(regs); savesegment(ss, ss); } printk(KERN_EMERG "EIP: [<%08lx>] ", regs->ip); print_symbol("%s", regs->ip); printk(" SS:ESP %04x:%08lx\n", ss, sp); #else /* Executive summary in case the oops scrolled away */ printk(KERN_ALERT "RIP "); printk_address(regs->ip); printk(" RSP <%016lx>\n", regs->sp); #endif return 0; } NOKPROBE_SYMBOL(__die); /* * This is gone through when something in the kernel has done something bad * and is about to be terminated: */ void die(const char *str, struct pt_regs *regs, long err) { unsigned long flags = oops_begin(); int sig = SIGSEGV; if (!user_mode(regs)) report_bug(regs->ip, regs); if (__die(str, regs, err)) sig = 0; oops_end(flags, regs, sig); } static int __init kstack_setup(char *s) { ssize_t ret; unsigned long val; if (!s) return -EINVAL; ret = kstrtoul(s, 0, &val); if (ret) return ret; kstack_depth_to_print = val; return 0; } early_param("kstack", kstack_setup); static int __init code_bytes_setup(char *s) { ssize_t ret; unsigned long val; if (!s) return -EINVAL; ret = kstrtoul(s, 0, &val); if (ret) return ret; code_bytes = val; if (code_bytes > 8192) code_bytes = 8192; return 1; } __setup("code_bytes=", code_bytes_setup);
david-a-wheeler/linux
arch/x86/kernel/dumpstack.c
C
gpl-2.0
7,847
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2889, 1010, 2826, 11409, 2271, 17153, 10175, 5104, 1008, 9385, 1006, 1039, 1007, 2456, 1010, 2541, 1010, 2526, 1998, 2072, 1047, 24129, 1010, 10514, 3366, 13625, 1008, 1013, 1001, 2421, 1026,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: post title: "Paper published: mlr - Machine Learning in R" author: jakob --- We are happy to announce that we can finally answer the question on how to cite *mlr* properly in publications. Our paper on *mlr* has been published in the open-access Journal of Machine Learning Research (JMLR) and can be downloaded on the [journal home page](http://www.jmlr.org/papers/v17/15-066.html). <!--more--> [![preview paper](/images/2016-10-20-Paper-published-mlr-Machine-Learning-in-R/paper-first-page.png)](http://www.jmlr.org/papers/v17/15-066.html) The paper gives a brief overview of the features of *mlr* and also includes a comparison with similar toolkits. For an in-depth understanding we still recommend our excellent [online mlr tutorial](https://mlr-org.github.io/mlr/) which is now also available as a [PDF](https://arxiv.org/abs/1609.06146) on arxiv.org or as [zipped HTML files](https://mlr-org.github.io/mlr/devel/mlr_tutorial.zip) for offline reading. Once *mlr 2.10* hits CRAN you can retrieve the citation information from within R: {% highlight r %} citation("mlr") {% endhighlight %} {% highlight text %} ## ## Bischl B, Lang M, Kotthoff L, Schiffner J, Richter J, Studerus ## E, Casalicchio G and Jones Z (2016). "mlr: Machine Learning in ## R." _Journal of Machine Learning Research_, *17*(170), pp. ## 1-5. <URL: http://jmlr.org/papers/v17/15-066.html>. ## ## A BibTeX entry for LaTeX users is ## ## @Article{mlr, ## title = {% raw %}{{{% endraw %}mlr}: Machine Learning in R}, ## author = {Bernd Bischl and Michel Lang and Lars Kotthoff and Julia Schiffner and Jakob Richter and Erich Studerus and Giuseppe Casalicchio and Zachary M. Jones}, ## journal = {Journal of Machine Learning Research}, ## year = {2016}, ## volume = {17}, ## number = {170}, ## pages = {1-5}, ## url = {http://jmlr.org/papers/v17/15-066.html}, ## } ## {% endhighlight %}
mlr-org/mlr-org.github.io
_posts/2016-10-20-Paper-published-mlr-Machine-Learning-in-R.md
Markdown
mit
1,938
[ 30522, 1011, 1011, 1011, 9621, 1024, 2695, 2516, 1024, 1000, 3259, 2405, 1024, 19875, 2099, 1011, 3698, 4083, 1999, 1054, 1000, 3166, 1024, 19108, 1011, 1011, 1011, 2057, 2024, 3407, 2000, 14970, 2008, 2057, 2064, 2633, 3437, 1996, 3160, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*! * DevExtreme (dx.messages.es.js) * Version: 17.2.17 * Build date: Fri Apr 23 2021 * * Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define(function(require) { factory(require("devextreme/localization")) }) } else { if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } } }(this, function(localization) { localization.loadMessages({ es: { Yes: "Sí", No: "No", Cancel: "Cancelar", Clear: "Limpiar", Done: "Hecho", Loading: "Cargando...", Select: "Seleccionar...", Search: "Buscar", Back: "Volver", OK: "Aceptar", "dxCollectionWidget-noDataText": "Sin datos para mostrar", "validation-required": "Obligatorio", "validation-required-formatted": "{0} es obligatorio", "validation-numeric": "Valor debe ser un número", "validation-numeric-formatted": "{0} debe ser un número", "validation-range": "Valor fuera de rango", "validation-range-formatted": "{0} fuera de rango", "validation-stringLength": "El largo del valor es incorrecto", "validation-stringLength-formatted": "El largo de {0} es incorrecto", "validation-custom": "Valor inválido", "validation-custom-formatted": "{0} inválido", "validation-compare": "Valores no coinciden", "validation-compare-formatted": "{0} no coinciden", "validation-pattern": "Valor no coincide con el patrón", "validation-pattern-formatted": "{0} no coincide con el patrón", "validation-email": "Email inválido", "validation-email-formatted": "{0} inválido", "validation-mask": "Valor inválido", "dxLookup-searchPlaceholder": "Cantidad mínima de caracteres: {0}", "dxList-pullingDownText": "Desliza hacia abajo para actualizar...", "dxList-pulledDownText": "Suelta para actualizar...", "dxList-refreshingText": "Actualizando...", "dxList-pageLoadingText": "Cargando...", "dxList-nextButtonText": "Más", "dxList-selectAll": "Seleccionar Todo", "dxListEditDecorator-delete": "Eliminar", "dxListEditDecorator-more": "Más", "dxScrollView-pullingDownText": "Desliza hacia abajo para actualizar...", "dxScrollView-pulledDownText": "Suelta para actualizar...", "dxScrollView-refreshingText": "Actualizando...", "dxScrollView-reachBottomText": "Cargando...", "dxDateBox-simulatedDataPickerTitleTime": "Seleccione hora", "dxDateBox-simulatedDataPickerTitleDate": "Seleccione fecha", "dxDateBox-simulatedDataPickerTitleDateTime": "Seleccione fecha y hora", "dxDateBox-validation-datetime": "Valor debe ser una fecha u hora", "dxFileUploader-selectFile": "Seleccionar archivo", "dxFileUploader-dropFile": "o Arrastre un archivo aquí", "dxFileUploader-bytes": "bytes", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "Subir", "dxFileUploader-uploaded": "Subido", "dxFileUploader-readyToUpload": "Listo para subir", "dxFileUploader-uploadFailedMessage": "Súbida fallo", "dxRangeSlider-ariaFrom": "Desde", "dxRangeSlider-ariaTill": "Hasta", "dxSwitch-onText": "ENCENDIDO", "dxSwitch-offText": "APAGADO", "dxForm-optionalMark": "opcional", "dxForm-requiredMessage": "{0} es obligatorio", "dxNumberBox-invalidValueMessage": "Valor debe ser un número", "dxDataGrid-columnChooserTitle": "Selector de Columnas", "dxDataGrid-columnChooserEmptyText": "Arrastra una columna aquí para esconderla", "dxDataGrid-groupContinuesMessage": "Continúa en la página siguiente", "dxDataGrid-groupContinuedMessage": "Continuación de la página anterior", "dxDataGrid-groupHeaderText": "Agrupar por esta columna", "dxDataGrid-ungroupHeaderText": "Desagrupar", "dxDataGrid-ungroupAllText": "Desagrupar Todo", "dxDataGrid-editingEditRow": "Editar", "dxDataGrid-editingSaveRowChanges": "Guardar", "dxDataGrid-editingCancelRowChanges": "Cancelar", "dxDataGrid-editingDeleteRow": "Eliminar", "dxDataGrid-editingUndeleteRow": "Recuperar", "dxDataGrid-editingConfirmDeleteMessage": "¿Está seguro que desea eliminar este registro?", "dxDataGrid-validationCancelChanges": "Cancelar cambios", "dxDataGrid-groupPanelEmptyText": "Arrastra una columna aquí para agrupar por ella", "dxDataGrid-noDataText": "Sin datos", "dxDataGrid-searchPanelPlaceholder": "Buscar...", "dxDataGrid-filterRowShowAllText": "(Todo)", "dxDataGrid-filterRowResetOperationText": "Reestablecer", "dxDataGrid-filterRowOperationEquals": "Igual", "dxDataGrid-filterRowOperationNotEquals": "No es igual", "dxDataGrid-filterRowOperationLess": "Menor que", "dxDataGrid-filterRowOperationLessOrEquals": "Menor que o igual a", "dxDataGrid-filterRowOperationGreater": "Mayor que", "dxDataGrid-filterRowOperationGreaterOrEquals": "Mayor que o igual a", "dxDataGrid-filterRowOperationStartsWith": "Empieza con", "dxDataGrid-filterRowOperationContains": "Contiene", "dxDataGrid-filterRowOperationNotContains": "No contiene", "dxDataGrid-filterRowOperationEndsWith": "Termina con", "dxDataGrid-filterRowOperationBetween": "Entre", "dxDataGrid-filterRowOperationBetweenStartText": "Inicio", "dxDataGrid-filterRowOperationBetweenEndText": "Fin", "dxDataGrid-applyFilterText": "Filtrar", "dxDataGrid-trueText": "verdadero", "dxDataGrid-falseText": "falso", "dxDataGrid-sortingAscendingText": "Orden Ascendente", "dxDataGrid-sortingDescendingText": "Orden Descendente", "dxDataGrid-sortingClearText": "Limpiar Ordenamiento", "dxDataGrid-editingSaveAllChanges": "Guardar cambios", "dxDataGrid-editingCancelAllChanges": "Descartar cambios", "dxDataGrid-editingAddRow": "Agregar una fila", "dxDataGrid-summaryMin": "Mín: {0}", "dxDataGrid-summaryMinOtherColumn": "Mín de {1} es {0}", "dxDataGrid-summaryMax": "Máx: {0}", "dxDataGrid-summaryMaxOtherColumn": "Máx de {1} es {0}", "dxDataGrid-summaryAvg": "Prom: {0}", "dxDataGrid-summaryAvgOtherColumn": "Prom de {1} es {0}", "dxDataGrid-summarySum": "Suma: {0}", "dxDataGrid-summarySumOtherColumn": "Suma de {1} es {0}", "dxDataGrid-summaryCount": "Recuento: {0}", "dxDataGrid-columnFixingFix": "Anclar", "dxDataGrid-columnFixingUnfix": "Desanclar", "dxDataGrid-columnFixingLeftPosition": "A la izquierda", "dxDataGrid-columnFixingRightPosition": "A la derecha", "dxDataGrid-exportTo": "Exportar", "dxDataGrid-exportToExcel": "Exportar a archivo Excel", "dxDataGrid-excelFormat": "Archivo Excel", "dxDataGrid-selectedRows": "Filas seleccionadas", "dxDataGrid-exportSelectedRows": "Exportar filas seleccionadas", "dxDataGrid-exportAll": "Exportar todo", "dxDataGrid-headerFilterEmptyValue": "(En Blanco)", "dxDataGrid-headerFilterOK": "Aceptar", "dxDataGrid-headerFilterCancel": "Cancelar", "dxDataGrid-ariaColumn": "Columna", "dxDataGrid-ariaValue": "Valor", "dxDataGrid-ariaFilterCell": "Celda de filtro", "dxDataGrid-ariaCollapse": "Colapsar", "dxDataGrid-ariaExpand": "Expandir", "dxDataGrid-ariaDataGrid": "Rejilla de datos", "dxDataGrid-ariaSearchInGrid": "Buscar en la rejilla de datos", "dxDataGrid-ariaSelectAll": "Seleccionar todo", "dxDataGrid-ariaSelectRow": "Seleccionar fila", "dxTreeList-ariaTreeList": "Lista de árbol", "dxTreeList-editingAddRowToNode": "Añadir", "dxPager-infoText": "Página {0} de {1} ({2} elementos)", "dxPager-pagesCountText": "de", "dxPivotGrid-grandTotal": "Gran Total", "dxPivotGrid-total": "{0} Total", "dxPivotGrid-fieldChooserTitle": "Selector de Campos", "dxPivotGrid-showFieldChooser": "Mostrar Selector de Campos", "dxPivotGrid-expandAll": "Expandir Todo", "dxPivotGrid-collapseAll": "Colapsar Todo", "dxPivotGrid-sortColumnBySummary": 'Ordenar "{0}" por Esta Columna', "dxPivotGrid-sortRowBySummary": 'Ordenar "{0}" por Esta Fila', "dxPivotGrid-removeAllSorting": "Remover Ordenamiento", "dxPivotGrid-dataNotAvailable": "N/A", "dxPivotGrid-rowFields": "Campos de Fila", "dxPivotGrid-columnFields": "Campos de Columna", "dxPivotGrid-dataFields": "Campos de Dato", "dxPivotGrid-filterFields": "Campos de Filtro", "dxPivotGrid-allFields": "Todos los Campos", "dxPivotGrid-columnFieldArea": "Arrastra Campos de Columna Aquí", "dxPivotGrid-dataFieldArea": "Arrastra Campos de Dato Aquí", "dxPivotGrid-rowFieldArea": "Arrastra Campos de Fila Aquí", "dxPivotGrid-filterFieldArea": "Arrastra Campos de Filtro Aquí", "dxScheduler-editorLabelTitle": "Asunto", "dxScheduler-editorLabelStartDate": "Fecha Inicio", "dxScheduler-editorLabelEndDate": "Fecha Término", "dxScheduler-editorLabelDescription": "Descripción", "dxScheduler-editorLabelRecurrence": "Repetir", "dxScheduler-openAppointment": "Abrir cita", "dxScheduler-recurrenceNever": "Nunca", "dxScheduler-recurrenceDaily": "Diario", "dxScheduler-recurrenceWeekly": "Semanal", "dxScheduler-recurrenceMonthly": "Mensual", "dxScheduler-recurrenceYearly": "Anual", "dxScheduler-recurrenceEvery": "Cada", "dxScheduler-recurrenceEnd": "Terminar repetición", "dxScheduler-recurrenceAfter": "Después", "dxScheduler-recurrenceOn": "En", "dxScheduler-recurrenceRepeatDaily": "día(s)", "dxScheduler-recurrenceRepeatWeekly": "semana(s)", "dxScheduler-recurrenceRepeatMonthly": "mes(es)", "dxScheduler-recurrenceRepeatYearly": "año(s)", "dxScheduler-switcherDay": "Día", "dxScheduler-switcherWeek": "Semana", "dxScheduler-switcherWorkWeek": "Semana Laboral", "dxScheduler-switcherMonth": "Mes", "dxScheduler-switcherAgenda": "Agenda", "dxScheduler-switcherTimelineDay": "Línea de tiempo Día", "dxScheduler-switcherTimelineWeek": "Línea de tiempo Semana", "dxScheduler-switcherTimelineWorkWeek": "Línea de tiempo Semana Laboral", "dxScheduler-switcherTimelineMonth": "Línea de tiempo Mes", "dxScheduler-recurrenceRepeatOnDate": "en la fecha", "dxScheduler-recurrenceRepeatCount": "ocurrencia(s)", "dxScheduler-allDay": "Todo el día", "dxScheduler-confirmRecurrenceEditMessage": "¿Quiere editar solo esta cita o toda la serie?", "dxScheduler-confirmRecurrenceDeleteMessage": "¿Quiere eliminar solo esta cita o toda la serie?", "dxScheduler-confirmRecurrenceEditSeries": "Editar serie", "dxScheduler-confirmRecurrenceDeleteSeries": "Eliminar serie", "dxScheduler-confirmRecurrenceEditOccurrence": "Editar cita", "dxScheduler-confirmRecurrenceDeleteOccurrence": "Eliminar cita", "dxScheduler-noTimezoneTitle": "Sin zona horaria", "dxScheduler-moreAppointments": "{0} más", "dxCalendar-todayButtonText": "Hoy", "dxCalendar-ariaWidgetName": "Calendario", "dxColorView-ariaRed": "Rojo", "dxColorView-ariaGreen": "Verde", "dxColorView-ariaBlue": "Azul", "dxColorView-ariaAlpha": "Transparencia", "dxColorView-ariaHex": "Código de color", "dxTagBox-selected": "{0} seleccionado", "dxTagBox-allSelected": "Todos seleccionados ({0})", "dxTagBox-moreSelected": "{0} más", "vizExport-printingButtonText": "Imprimir", "vizExport-titleMenuText": "Exportar/Imprimir", "vizExport-exportButtonText": "Archivo {0}", "dxFilterBuilder-and": "E", "dxFilterBuilder-or": "O", "dxFilterBuilder-notAnd": "NO E", "dxFilterBuilder-notOr": "NO O", "dxFilterBuilder-addCondition": "Añadir condición", "dxFilterBuilder-addGroup": "Añadir Grupo", "dxFilterBuilder-enterValueText": "<rellene con un valor>", "dxFilterBuilder-filterOperationEquals": "Igual", "dxFilterBuilder-filterOperationNotEquals": "Diferente", "dxFilterBuilder-filterOperationLess": "Menos que", "dxFilterBuilder-filterOperationLessOrEquals": "Menor o igual que", "dxFilterBuilder-filterOperationGreater": "Más grande que", "dxFilterBuilder-filterOperationGreaterOrEquals": "Mayor o igual que", "dxFilterBuilder-filterOperationStartsWith": "Comienza con", "dxFilterBuilder-filterOperationContains": "Contiene", "dxFilterBuilder-filterOperationNotContains": "No contiene", "dxFilterBuilder-filterOperationEndsWith": "Termina con", "dxFilterBuilder-filterOperationIsBlank": "Vacio", "dxFilterBuilder-filterOperationIsNotBlank": "No vacio" } }) });
cdnjs/cdnjs
ajax/libs/devextreme/17.2.17/js/localization/dx.messages.es.js
JavaScript
mit
14,845
[ 30522, 1013, 1008, 999, 1008, 16475, 10288, 7913, 4168, 1006, 1040, 2595, 1012, 7696, 1012, 9686, 1012, 1046, 2015, 1007, 1008, 2544, 1024, 2459, 1012, 1016, 1012, 2459, 1008, 3857, 3058, 1024, 10424, 2072, 19804, 2603, 25682, 1008, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
exports.createSession = function(req, res, newUser) { return req.session.regenerate(function() { req.session.user = newUser; // res.redirect('/'); }); }; exports.isLoggedIn = function(req, res) { // return req.session ? !!req.session.user : false; console.log(!!req.user); return req.user ? !!req.user : false; }; exports.checkUser = function(req, res, next){ if (!exports.isLoggedIn(req)){ res.redirect('/login'); } else { next(); } };
TCL735/job-spotter
server/lib/utility.js
JavaScript
mit
476
[ 30522, 14338, 1012, 9005, 7971, 3258, 1027, 3853, 1006, 2128, 4160, 1010, 24501, 1010, 2047, 20330, 1007, 1063, 2709, 2128, 4160, 1012, 5219, 1012, 19723, 24454, 3686, 1006, 3853, 1006, 1007, 1063, 2128, 4160, 1012, 5219, 1012, 5310, 1027, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# # Copyright 2017, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'poise_boiler/spec_helper' require 'poise_file' require 'poise_file/cheftie'
poise/poise-file
test/spec/spec_helper.rb
Ruby
apache-2.0
666
[ 30522, 1001, 1001, 9385, 2418, 1010, 7240, 26044, 10524, 8838, 1001, 1001, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1001, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12646, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * linux/mm/memory.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds */ /* * demand-loading started 01.12.91 - seems it is high on the list of * things wanted, and it should be easy to implement. - Linus */ /* * Ok, demand-loading was easy, shared pages a little bit tricker. Shared * pages started 02.12.91, seems to work. - Linus. * * Tested sharing by executing about 30 /bin/sh: under the old kernel it * would have taken more than the 6M I have free, but it worked well as * far as I could see. * * Also corrected some "invalidate()"s - I wasn't doing enough of them. */ /* * Real VM (paging to/from disk) started 18.12.91. Much more work and * thought has to go into this. Oh, well.. * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why. * Found it. Everything seems to work now. * 20.12.91 - Ok, making the swap-device changeable like the root. */ /* * 05.04.94 - Multi-page memory management added for v1.1. * Idea by Alex Bligh (alex@cconcepts.co.uk) * * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG * (Gerhard.Wichert@pdb.siemens.de) * * Aug/Sep 2004 Changed to four level page tables (Andi Kleen) */ #include <linux/kernel_stat.h> #include <linux/mm.h> #include <linux/hugetlb.h> #include <linux/mman.h> #include <linux/swap.h> #include <linux/highmem.h> #include <linux/pagemap.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/export.h> #include <linux/delayacct.h> #include <linux/init.h> #include <linux/writeback.h> #include <linux/memcontrol.h> #include <linux/mmu_notifier.h> #include <linux/kallsyms.h> #include <linux/swapops.h> #include <linux/elf.h> #include <linux/gfp.h> #include <linux/migrate.h> #include <linux/string.h> #include <asm/io.h> #include <asm/pgalloc.h> #include <asm/uaccess.h> #include <asm/tlb.h> #include <asm/tlbflush.h> #include <asm/pgtable.h> #include "internal.h" #ifdef LAST_NID_NOT_IN_PAGE_FLAGS #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_nid. #endif #ifndef CONFIG_NEED_MULTIPLE_NODES /* use the per-pgdat data instead for discontigmem - mbligh */ unsigned long max_mapnr; struct page *mem_map; EXPORT_SYMBOL(max_mapnr); EXPORT_SYMBOL(mem_map); #endif unsigned long num_physpages; /* * A number of key systems in x86 including ioremap() rely on the assumption * that high_memory defines the upper bound on direct map memory, then end * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL * and ZONE_HIGHMEM. */ void * high_memory; EXPORT_SYMBOL(num_physpages); EXPORT_SYMBOL(high_memory); /* * Randomize the address space (stacks, mmaps, brk, etc.). * * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization, * as ancient (libc5 based) binaries can segfault. ) */ int randomize_va_space __read_mostly = #ifdef CONFIG_COMPAT_BRK 1; #else 2; #endif static int __init disable_randmaps(char *s) { randomize_va_space = 0; return 1; } __setup("norandmaps", disable_randmaps); unsigned long zero_pfn __read_mostly; unsigned long highest_memmap_pfn __read_mostly; #ifdef CONFIG_UKSM unsigned long uksm_zero_pfn __read_mostly; struct page *empty_uksm_zero_page; static int __init setup_uksm_zero_page(void) { unsigned long addr; addr = __get_free_pages(GFP_KERNEL | __GFP_ZERO, 0); if (!addr) panic("Oh boy, that early out of memory?"); empty_uksm_zero_page = virt_to_page((void *) addr); SetPageReserved(empty_uksm_zero_page); uksm_zero_pfn = page_to_pfn(empty_uksm_zero_page); return 0; } core_initcall(setup_uksm_zero_page); #endif /* * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init() */ static int __init init_zero_pfn(void) { zero_pfn = page_to_pfn(ZERO_PAGE(0)); return 0; } core_initcall(init_zero_pfn); #if defined(SPLIT_RSS_COUNTING) void sync_mm_rss(struct mm_struct *mm) { int i; for (i = 0; i < NR_MM_COUNTERS; i++) { if (current->rss_stat.count[i]) { add_mm_counter(mm, i, current->rss_stat.count[i]); current->rss_stat.count[i] = 0; } } current->rss_stat.events = 0; } static void add_mm_counter_fast(struct mm_struct *mm, int member, int val) { struct task_struct *task = current; if (likely(task->mm == mm)) task->rss_stat.count[member] += val; else add_mm_counter(mm, member, val); } #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1) #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1) /* sync counter once per 64 page faults */ #define TASK_RSS_EVENTS_THRESH (64) static void check_sync_rss_stat(struct task_struct *task) { if (unlikely(task != current)) return; if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH)) sync_mm_rss(task->mm); } #else /* SPLIT_RSS_COUNTING */ #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member) #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member) static void check_sync_rss_stat(struct task_struct *task) { } #endif /* SPLIT_RSS_COUNTING */ #ifdef HAVE_GENERIC_MMU_GATHER static int tlb_next_batch(struct mmu_gather *tlb) { struct mmu_gather_batch *batch; batch = tlb->active; if (batch->next) { tlb->active = batch->next; return 1; } if (tlb->batch_count == MAX_GATHER_BATCH_COUNT) return 0; batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0); if (!batch) return 0; tlb->batch_count++; batch->next = NULL; batch->nr = 0; batch->max = MAX_GATHER_BATCH; tlb->active->next = batch; tlb->active = batch; return 1; } /* tlb_gather_mmu * Called to initialize an (on-stack) mmu_gather structure for page-table * tear-down from @mm. The @fullmm argument is used when @mm is without * users and we're going to destroy the full address space (exit/execve). */ void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end) { tlb->mm = mm; /* Is it from 0 to ~0? */ tlb->fullmm = !(start | (end+1)); tlb->need_flush_all = 0; tlb->start = start; tlb->end = end; tlb->need_flush = 0; tlb->local.next = NULL; tlb->local.nr = 0; tlb->local.max = ARRAY_SIZE(tlb->__pages); tlb->active = &tlb->local; tlb->batch_count = 0; #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb->batch = NULL; #endif } void tlb_flush_mmu(struct mmu_gather *tlb) { struct mmu_gather_batch *batch; if (!tlb->need_flush) return; tlb->need_flush = 0; tlb_flush(tlb); #ifdef CONFIG_HAVE_RCU_TABLE_FREE tlb_table_flush(tlb); #endif for (batch = &tlb->local; batch; batch = batch->next) { free_pages_and_swap_cache(batch->pages, batch->nr); batch->nr = 0; } tlb->active = &tlb->local; } /* tlb_finish_mmu * Called at the end of the shootdown operation to free up any resources * that were required. */ void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end) { struct mmu_gather_batch *batch, *next; tlb_flush_mmu(tlb); /* keep the page table cache within bounds */ check_pgt_cache(); for (batch = tlb->local.next; batch; batch = next) { next = batch->next; free_pages((unsigned long)batch, 0); } tlb->local.next = NULL; } /* __tlb_remove_page * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while * handling the additional races in SMP caused by other CPUs caching valid * mappings in their TLBs. Returns the number of free page slots left. * When out of page slots we must call tlb_flush_mmu(). */ int __tlb_remove_page(struct mmu_gather *tlb, struct page *page) { struct mmu_gather_batch *batch; VM_BUG_ON(!tlb->need_flush); batch = tlb->active; batch->pages[batch->nr++] = page; if (batch->nr == batch->max) { if (!tlb_next_batch(tlb)) return 0; batch = tlb->active; } VM_BUG_ON(batch->nr > batch->max); return batch->max - batch->nr; } #endif /* HAVE_GENERIC_MMU_GATHER */ #ifdef CONFIG_HAVE_RCU_TABLE_FREE /* * See the comment near struct mmu_table_batch. */ static void tlb_remove_table_smp_sync(void *arg) { /* Simply deliver the interrupt */ } static void tlb_remove_table_one(void *table) { /* * This isn't an RCU grace period and hence the page-tables cannot be * assumed to be actually RCU-freed. * * It is however sufficient for software page-table walkers that rely on * IRQ disabling. See the comment near struct mmu_table_batch. */ smp_call_function(tlb_remove_table_smp_sync, NULL, 1); __tlb_remove_table(table); } static void tlb_remove_table_rcu(struct rcu_head *head) { struct mmu_table_batch *batch; int i; batch = container_of(head, struct mmu_table_batch, rcu); for (i = 0; i < batch->nr; i++) __tlb_remove_table(batch->tables[i]); free_page((unsigned long)batch); } void tlb_table_flush(struct mmu_gather *tlb) { struct mmu_table_batch **batch = &tlb->batch; if (*batch) { call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu); *batch = NULL; } } void tlb_remove_table(struct mmu_gather *tlb, void *table) { struct mmu_table_batch **batch = &tlb->batch; tlb->need_flush = 1; /* * When there's less then two users of this mm there cannot be a * concurrent page-table walk. */ if (atomic_read(&tlb->mm->mm_users) < 2) { __tlb_remove_table(table); return; } if (*batch == NULL) { *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN); if (*batch == NULL) { tlb_remove_table_one(table); return; } (*batch)->nr = 0; } (*batch)->tables[(*batch)->nr++] = table; if ((*batch)->nr == MAX_TABLE_BATCH) tlb_table_flush(tlb); } #endif /* CONFIG_HAVE_RCU_TABLE_FREE */ /* * If a p?d_bad entry is found while walking page tables, report * the error, before resetting entry to p?d_none. Usually (but * very seldom) called out from the p?d_none_or_clear_bad macros. */ void pgd_clear_bad(pgd_t *pgd) { pgd_ERROR(*pgd); pgd_clear(pgd); } void pud_clear_bad(pud_t *pud) { pud_ERROR(*pud); pud_clear(pud); } void pmd_clear_bad(pmd_t *pmd) { pmd_ERROR(*pmd); pmd_clear(pmd); } /* * Note: this doesn't free the actual pages themselves. That * has been handled earlier when unmapping all the memory regions. */ static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd, unsigned long addr) { pgtable_t token = pmd_pgtable(*pmd); pmd_clear(pmd); pte_free_tlb(tlb, token, addr); tlb->mm->nr_ptes--; } static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pmd_t *pmd; unsigned long next; unsigned long start; start = addr; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_none_or_clear_bad(pmd)) continue; free_pte_range(tlb, pmd, addr); } while (pmd++, addr = next, addr != end); start &= PUD_MASK; if (start < floor) return; if (ceiling) { ceiling &= PUD_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) return; pmd = pmd_offset(pud, start); pud_clear(pud); pmd_free_tlb(tlb, pmd, start); } static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pud_t *pud; unsigned long next; unsigned long start; start = addr; pud = pud_offset(pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(pud)) continue; free_pmd_range(tlb, pud, addr, next, floor, ceiling); } while (pud++, addr = next, addr != end); start &= PGDIR_MASK; if (start < floor) return; if (ceiling) { ceiling &= PGDIR_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) return; pud = pud_offset(pgd, start); pgd_clear(pgd); pud_free_tlb(tlb, pud, start); } /* * This function frees user-level page tables of a process. * * Must be called with pagetable lock held. */ void free_pgd_range(struct mmu_gather *tlb, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling) { pgd_t *pgd; unsigned long next; /* * The next few lines have given us lots of grief... * * Why are we testing PMD* at this top level? Because often * there will be no work to do at all, and we'd prefer not to * go all the way down to the bottom just to discover that. * * Why all these "- 1"s? Because 0 represents both the bottom * of the address space and the top of it (using -1 for the * top wouldn't help much: the masks would do the wrong thing). * The rule is that addr 0 and floor 0 refer to the bottom of * the address space, but end 0 and ceiling 0 refer to the top * Comparisons need to use "end - 1" and "ceiling - 1" (though * that end 0 case should be mythical). * * Wherever addr is brought up or ceiling brought down, we must * be careful to reject "the opposite 0" before it confuses the * subsequent tests. But what about where end is brought down * by PMD_SIZE below? no, end can't go down to 0 there. * * Whereas we round start (addr) and ceiling down, by different * masks at different levels, in order to test whether a table * now has no other vmas using it, so can be freed, we don't * bother to round floor or end up - the tests don't need that. */ addr &= PMD_MASK; if (addr < floor) { addr += PMD_SIZE; if (!addr) return; } if (ceiling) { ceiling &= PMD_MASK; if (!ceiling) return; } if (end - 1 > ceiling - 1) end -= PMD_SIZE; if (addr > end - 1) return; pgd = pgd_offset(tlb->mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; free_pud_range(tlb, pgd, addr, next, floor, ceiling); } while (pgd++, addr = next, addr != end); } void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long floor, unsigned long ceiling) { while (vma) { struct vm_area_struct *next = vma->vm_next; unsigned long addr = vma->vm_start; /* * Hide vma from rmap and truncate_pagecache before freeing * pgtables */ unlink_anon_vmas(vma); unlink_file_vma(vma); if (is_vm_hugetlb_page(vma)) { hugetlb_free_pgd_range(tlb, addr, vma->vm_end, floor, next? next->vm_start: ceiling); } else { /* * Optimization: gather nearby vmas into one call down */ while (next && next->vm_start <= vma->vm_end + PMD_SIZE && !is_vm_hugetlb_page(next)) { vma = next; next = vma->vm_next; unlink_anon_vmas(vma); unlink_file_vma(vma); } free_pgd_range(tlb, addr, vma->vm_end, floor, next? next->vm_start: ceiling); } vma = next; } } int __pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, unsigned long address) { pgtable_t new = pte_alloc_one(mm, address); int wait_split_huge_page; if (!new) return -ENOMEM; /* * Ensure all pte setup (eg. pte page lock and page clearing) are * visible before the pte is made visible to other CPUs by being * put into page tables. * * The other side of the story is the pointer chasing in the page * table walking code (when walking the page table without locking; * ie. most of the time). Fortunately, these data accesses consist * of a chain of data-dependent loads, meaning most CPUs (alpha * being the notable exception) will already guarantee loads are * seen in-order. See the alpha page table accessors for the * smp_read_barrier_depends() barriers in page table walking code. */ smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */ spin_lock(&mm->page_table_lock); wait_split_huge_page = 0; if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ mm->nr_ptes++; pmd_populate(mm, pmd, new); new = NULL; } else if (unlikely(pmd_trans_splitting(*pmd))) wait_split_huge_page = 1; spin_unlock(&mm->page_table_lock); if (new) pte_free(mm, new); if (wait_split_huge_page) wait_split_huge_page(vma->anon_vma, pmd); return 0; } int __pte_alloc_kernel(pmd_t *pmd, unsigned long address) { pte_t *new = pte_alloc_one_kernel(&init_mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&init_mm.page_table_lock); if (likely(pmd_none(*pmd))) { /* Has another populated it ? */ pmd_populate_kernel(&init_mm, pmd, new); new = NULL; } else VM_BUG_ON(pmd_trans_splitting(*pmd)); spin_unlock(&init_mm.page_table_lock); if (new) pte_free_kernel(&init_mm, new); return 0; } static inline void init_rss_vec(int *rss) { memset(rss, 0, sizeof(int) * NR_MM_COUNTERS); } static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss) { int i; if (current->mm == mm) sync_mm_rss(mm); for (i = 0; i < NR_MM_COUNTERS; i++) if (rss[i]) add_mm_counter(mm, i, rss[i]); } /* * This function is called to print an error when a bad pte * is found. For example, we might have a PFN-mapped pte in * a region that doesn't allow it. * * The calling function must still handle the error. */ static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr, pte_t pte, struct page *page) { pgd_t *pgd = pgd_offset(vma->vm_mm, addr); pud_t *pud = pud_offset(pgd, addr); pmd_t *pmd = pmd_offset(pud, addr); struct address_space *mapping; pgoff_t index; static unsigned long resume; static unsigned long nr_shown; static unsigned long nr_unshown; /* * Allow a burst of 60 reports, then keep quiet for that minute; * or allow a steady drip of one report per second. */ if (nr_shown == 60) { if (time_before(jiffies, resume)) { nr_unshown++; return; } if (nr_unshown) { printk(KERN_ALERT "BUG: Bad page map: %lu messages suppressed\n", nr_unshown); nr_unshown = 0; } nr_shown = 0; } if (nr_shown++ == 0) resume = jiffies + 60 * HZ; mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL; index = linear_page_index(vma, addr); printk(KERN_ALERT "BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n", current->comm, (long long)pte_val(pte), (long long)pmd_val(*pmd)); if (page) dump_page(page); printk(KERN_ALERT "addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n", (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index); /* * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y */ if (vma->vm_ops) printk(KERN_ALERT "vma->vm_ops->fault: %pSR\n", vma->vm_ops->fault); if (vma->vm_file && vma->vm_file->f_op) printk(KERN_ALERT "vma->vm_file->f_op->mmap: %pSR\n", vma->vm_file->f_op->mmap); dump_stack(); add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); } static inline bool is_cow_mapping(vm_flags_t flags) { return (flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE; } /* * vm_normal_page -- This function gets the "struct page" associated with a pte. * * "Special" mappings do not wish to be associated with a "struct page" (either * it doesn't exist, or it exists but they don't want to touch it). In this * case, NULL is returned here. "Normal" mappings do have a struct page. * * There are 2 broad cases. Firstly, an architecture may define a pte_special() * pte bit, in which case this function is trivial. Secondly, an architecture * may not have a spare pte bit, which requires a more complicated scheme, * described below. * * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a * special mapping (even if there are underlying and valid "struct pages"). * COWed pages of a VM_PFNMAP are always normal. * * The way we recognize COWed pages within VM_PFNMAP mappings is through the * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit * set, and the vm_pgoff will point to the first PFN mapped: thus every special * mapping will always honor the rule * * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT) * * And for normal mappings this is false. * * This restricts such mappings to be a linear translation from virtual address * to pfn. To get around this restriction, we allow arbitrary mappings so long * as the vma is not a COW mapping; in that case, we know that all ptes are * special (because none can have been COWed). * * * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP. * * VM_MIXEDMAP mappings can likewise contain memory with or without "struct * page" backing, however the difference is that _all_ pages with a struct * page (that is, those where pfn_valid is true) are refcounted and considered * normal pages by the VM. The disadvantage is that pages are refcounted * (which can be slower and simply not an option for some PFNMAP users). The * advantage is that we don't have to follow the strict linearity rule of * PFNMAP mappings in order to support COWable mappings. * */ #ifdef __HAVE_ARCH_PTE_SPECIAL # define HAVE_PTE_SPECIAL 1 #else # define HAVE_PTE_SPECIAL 0 #endif struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte) { unsigned long pfn = pte_pfn(pte); if (HAVE_PTE_SPECIAL) { if (likely(!pte_special(pte))) goto check_pfn; if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP)) return NULL; if (!is_zero_pfn(pfn)) print_bad_pte(vma, addr, pte, NULL); return NULL; } /* !HAVE_PTE_SPECIAL case follows: */ if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) { if (vma->vm_flags & VM_MIXEDMAP) { if (!pfn_valid(pfn)) return NULL; goto out; } else { unsigned long off; off = (addr - vma->vm_start) >> PAGE_SHIFT; if (pfn == vma->vm_pgoff + off) return NULL; if (!is_cow_mapping(vma->vm_flags)) return NULL; } } if (is_zero_pfn(pfn)) return NULL; check_pfn: if (unlikely(pfn > highest_memmap_pfn)) { print_bad_pte(vma, addr, pte, NULL); return NULL; } /* * NOTE! We still have PageReserved() pages in the page tables. * eg. VDSO mappings can cause them to exist. */ out: return pfn_to_page(pfn); } /* * copy one vm_area from one task to the other. Assumes the page tables * already present in the new task to be cleared in the whole range * covered by this vma. */ static inline unsigned long copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm, pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma, unsigned long addr, int *rss) { unsigned long vm_flags = vma->vm_flags; pte_t pte = *src_pte; struct page *page; /* pte contains position in swap or file, so copy. */ if (unlikely(!pte_present(pte))) { if (!pte_file(pte)) { swp_entry_t entry = pte_to_swp_entry(pte); if (likely(!non_swap_entry(entry))) { if (swap_duplicate(entry) < 0) return entry.val; /* make sure dst_mm is on swapoff's mmlist. */ if (unlikely(list_empty(&dst_mm->mmlist))) { spin_lock(&mmlist_lock); if (list_empty(&dst_mm->mmlist)) list_add(&dst_mm->mmlist, &src_mm->mmlist); spin_unlock(&mmlist_lock); } rss[MM_SWAPENTS]++; } else if (is_migration_entry(entry)) { page = migration_entry_to_page(entry); if (PageAnon(page)) { rss[MM_ANONPAGES]++; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_ANONPAGES]++; #endif } else { rss[MM_FILEPAGES]++; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_FILEPAGES]++; #endif } if (is_write_migration_entry(entry) && is_cow_mapping(vm_flags)) { /* * COW mappings require pages in both * parent and child to be set to read. */ make_migration_entry_read(&entry); pte = swp_entry_to_pte(entry); set_pte_at(src_mm, addr, src_pte, pte); } /* Should return NULL in vm_normal_page() */ uksm_bugon_zeropage(pte); } else { uksm_map_zero_page(pte); } } goto out_set_pte; } /* * If it's a COW mapping, write protect it both * in the parent and the child */ if (is_cow_mapping(vm_flags)) { ptep_set_wrprotect(src_mm, addr, src_pte); pte = pte_wrprotect(pte); } /* * If it's a shared mapping, mark it clean in * the child */ if (vm_flags & VM_SHARED) pte = pte_mkclean(pte); pte = pte_mkold(pte); page = vm_normal_page(vma, addr, pte); if (page) { get_page(page); page_dup_rmap(page); if (PageAnon(page)) { rss[MM_ANONPAGES]++; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_ANONPAGES]++; #endif } else { rss[MM_FILEPAGES]++; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_FILEPAGES]++; #endif } } out_set_pte: set_pte_at(dst_mm, addr, dst_pte, pte); return 0; } int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pte_t *orig_src_pte, *orig_dst_pte; pte_t *src_pte, *dst_pte; spinlock_t *src_ptl, *dst_ptl; int progress = 0; int rss[NR_MM_COUNTERS]; swp_entry_t entry = (swp_entry_t){0}; again: init_rss_vec(rss); dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl); if (!dst_pte) return -ENOMEM; src_pte = pte_offset_map(src_pmd, addr); src_ptl = pte_lockptr(src_mm, src_pmd); spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); orig_src_pte = src_pte; orig_dst_pte = dst_pte; arch_enter_lazy_mmu_mode(); do { /* * We are holding two locks at this point - either of them * could generate latencies in another task on another CPU. */ if (progress >= 32) { progress = 0; if (need_resched() || spin_needbreak(src_ptl) || spin_needbreak(dst_ptl)) break; } if (pte_none(*src_pte)) { progress++; continue; } entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte, vma, addr, rss); if (entry.val) break; progress += 8; } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); spin_unlock(src_ptl); pte_unmap(orig_src_pte); add_mm_rss_vec(dst_mm, rss); pte_unmap_unlock(orig_dst_pte, dst_ptl); cond_resched(); if (entry.val) { if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) return -ENOMEM; progress = 0; } if (addr != end) goto again; return 0; } static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pmd_t *src_pmd, *dst_pmd; unsigned long next; dst_pmd = pmd_alloc(dst_mm, dst_pud, addr); if (!dst_pmd) return -ENOMEM; src_pmd = pmd_offset(src_pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*src_pmd)) { int err; VM_BUG_ON(next-addr != HPAGE_PMD_SIZE); err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd, addr, vma); if (err == -ENOMEM) return -ENOMEM; if (!err) continue; /* fall through */ } if (pmd_none_or_clear_bad(src_pmd)) continue; if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd, vma, addr, next)) return -ENOMEM; } while (dst_pmd++, src_pmd++, addr = next, addr != end); return 0; } static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma, unsigned long addr, unsigned long end) { pud_t *src_pud, *dst_pud; unsigned long next; dst_pud = pud_alloc(dst_mm, dst_pgd, addr); if (!dst_pud) return -ENOMEM; src_pud = pud_offset(src_pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(src_pud)) continue; if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud, vma, addr, next)) return -ENOMEM; } while (dst_pud++, src_pud++, addr = next, addr != end); return 0; } int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm, struct vm_area_struct *vma) { pgd_t *src_pgd, *dst_pgd; unsigned long next; unsigned long addr = vma->vm_start; unsigned long end = vma->vm_end; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ bool is_cow; int ret; /* * Don't copy ptes where a page fault will fill them correctly. * Fork becomes much lighter when there are big shared or private * readonly mappings. The tradeoff is that copy_page_range is more * efficient than faulting. */ if (!(vma->vm_flags & (VM_HUGETLB | VM_NONLINEAR | VM_PFNMAP | VM_MIXEDMAP))) { if (!vma->anon_vma) return 0; } if (is_vm_hugetlb_page(vma)) return copy_hugetlb_page_range(dst_mm, src_mm, vma); if (unlikely(vma->vm_flags & VM_PFNMAP)) { /* * We do not free on error cases below as remove_vma * gets called on error from higher level routine */ ret = track_pfn_copy(vma); if (ret) return ret; } /* * We need to invalidate the secondary MMU mappings only when * there could be a permission downgrade on the ptes of the * parent mm. And a permission downgrade will only happen if * is_cow_mapping() returns true. */ is_cow = is_cow_mapping(vma->vm_flags); mmun_start = addr; mmun_end = end; if (is_cow) mmu_notifier_invalidate_range_start(src_mm, mmun_start, mmun_end); ret = 0; dst_pgd = pgd_offset(dst_mm, addr); src_pgd = pgd_offset(src_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(src_pgd)) continue; if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd, vma, addr, next))) { ret = -ENOMEM; break; } } while (dst_pgd++, src_pgd++, addr = next, addr != end); if (is_cow) mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end); return ret; } static unsigned long zap_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd, unsigned long addr, unsigned long end, struct zap_details *details) { struct mm_struct *mm = tlb->mm; int force_flush = 0; int rss[NR_MM_COUNTERS]; spinlock_t *ptl; pte_t *start_pte; pte_t *pte; again: init_rss_vec(rss); start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl); pte = start_pte; arch_enter_lazy_mmu_mode(); do { pte_t ptent = *pte; if (pte_none(ptent)) { continue; } if (pte_present(ptent)) { struct page *page; page = vm_normal_page(vma, addr, ptent); if (unlikely(details) && page) { /* * unmap_shared_mapping_pages() wants to * invalidate cache without truncating: * unmap shared but keep private pages. */ if (details->check_mapping && details->check_mapping != page->mapping) continue; /* * Each page->index must be checked when * invalidating or truncating nonlinear. */ if (details->nonlinear_vma && (page->index < details->first_index || page->index > details->last_index)) continue; } ptent = ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm); tlb_remove_tlb_entry(tlb, pte, addr); if (unlikely(!page)) { uksm_unmap_zero_page(ptent); continue; } if (unlikely(details) && details->nonlinear_vma && linear_page_index(details->nonlinear_vma, addr) != page->index) set_pte_at(mm, addr, pte, pgoff_to_pte(page->index)); if (PageAnon(page)) { rss[MM_ANONPAGES]--; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_ANONPAGES]--; #endif } else { if (pte_dirty(ptent)) set_page_dirty(page); if (pte_young(ptent) && likely(!VM_SequentialReadHint(vma))) mark_page_accessed(page); rss[MM_FILEPAGES]--; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_FILEPAGES]--; #endif } page_remove_rmap(page); if (unlikely(page_mapcount(page) < 0)) print_bad_pte(vma, addr, ptent, page); force_flush = !__tlb_remove_page(tlb, page); if (force_flush) break; continue; } /* * If details->check_mapping, we leave swap entries; * if details->nonlinear_vma, we leave file entries. */ if (unlikely(details)) continue; if (pte_file(ptent)) { if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) print_bad_pte(vma, addr, ptent, NULL); } else { swp_entry_t entry = pte_to_swp_entry(ptent); if (!non_swap_entry(entry)) rss[MM_SWAPENTS]--; else if (is_migration_entry(entry)) { struct page *page; page = migration_entry_to_page(entry); if (PageAnon(page)) { rss[MM_ANONPAGES]--; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_ANONPAGES]--; #endif } else { rss[MM_FILEPAGES]--; #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) rss[MM_LOW_FILEPAGES]--; #endif } } if (unlikely(!free_swap_and_cache(entry))) print_bad_pte(vma, addr, ptent, NULL); } pte_clear_not_present_full(mm, addr, pte, tlb->fullmm); } while (pte++, addr += PAGE_SIZE, addr != end); add_mm_rss_vec(mm, rss); arch_leave_lazy_mmu_mode(); pte_unmap_unlock(start_pte, ptl); /* * mmu_gather ran out of room to batch pages, we break out of * the PTE lock to avoid doing the potential expensive TLB invalidate * and page-free while holding it. */ if (force_flush) { unsigned long old_end; force_flush = 0; /* * Flush the TLB just for the previous segment, * then update the range to be the remaining * TLB range. */ old_end = tlb->end; tlb->end = addr; tlb_flush_mmu(tlb); tlb->start = addr; tlb->end = old_end; if (addr != end) goto again; } return addr; } static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next - addr != HPAGE_PMD_SIZE) { #ifdef CONFIG_DEBUG_VM if (!rwsem_is_locked(&tlb->mm->mmap_sem)) { pr_err("%s: mmap_sem is unlocked! addr=0x%lx end=0x%lx vma->vm_start=0x%lx vma->vm_end=0x%lx\n", __func__, addr, end, vma->vm_start, vma->vm_end); BUG(); } #endif split_huge_page_pmd(vma, addr, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) goto next; /* fall through */ } /* * Here there can be other concurrent MADV_DONTNEED or * trans huge page faults running, and if the pmd is * none or trans huge it can change under us. This is * because MADV_DONTNEED holds the mmap_sem in read * mode. */ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) goto next; next = zap_pte_range(tlb, vma, pmd, addr, next, details); next: cond_resched(); } while (pmd++, addr = next, addr != end); return addr; } static inline unsigned long zap_pud_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pgd_t *pgd, unsigned long addr, unsigned long end, struct zap_details *details) { pud_t *pud; unsigned long next; pud = pud_offset(pgd, addr); do { next = pud_addr_end(addr, end); if (pud_none_or_clear_bad(pud)) continue; next = zap_pmd_range(tlb, vma, pud, addr, next, details); } while (pud++, addr = next, addr != end); return addr; } static void unmap_page_range(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long addr, unsigned long end, struct zap_details *details) { pgd_t *pgd; unsigned long next; if (details && !details->check_mapping && !details->nonlinear_vma) details = NULL; BUG_ON(addr >= end); mem_cgroup_uncharge_start(); tlb_start_vma(tlb, vma); pgd = pgd_offset(vma->vm_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; next = zap_pud_range(tlb, vma, pgd, addr, next, details); } while (pgd++, addr = next, addr != end); tlb_end_vma(tlb, vma); mem_cgroup_uncharge_end(); } static void unmap_single_vma(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, struct zap_details *details) { unsigned long start = max(vma->vm_start, start_addr); unsigned long end; if (start >= vma->vm_end) return; end = min(vma->vm_end, end_addr); if (end <= vma->vm_start) return; if (vma->vm_file) uprobe_munmap(vma, start, end); if (unlikely(vma->vm_flags & VM_PFNMAP)) untrack_pfn(vma, 0, 0); if (start != end) { if (unlikely(is_vm_hugetlb_page(vma))) { /* * It is undesirable to test vma->vm_file as it * should be non-null for valid hugetlb area. * However, vm_file will be NULL in the error * cleanup path of do_mmap_pgoff. When * hugetlbfs ->mmap method fails, * do_mmap_pgoff() nullifies vma->vm_file * before calling this function to clean up. * Since no pte has actually been setup, it is * safe to do nothing in this case. */ if (vma->vm_file) { mutex_lock(&vma->vm_file->f_mapping->i_mmap_mutex); __unmap_hugepage_range_final(tlb, vma, start, end, NULL); mutex_unlock(&vma->vm_file->f_mapping->i_mmap_mutex); } } else unmap_page_range(tlb, vma, start, end, details); } } /** * unmap_vmas - unmap a range of memory covered by a list of vma's * @tlb: address of the caller's struct mmu_gather * @vma: the starting vma * @start_addr: virtual address at which to start unmapping * @end_addr: virtual address at which to end unmapping * * Unmap all pages in the vma list. * * Only addresses between `start' and `end' will be unmapped. * * The VMA list must be sorted in ascending virtual address order. * * unmap_vmas() assumes that the caller will flush the whole unmapped address * range after unmap_vmas() returns. So the only responsibility here is to * ensure that any thus-far unmapped pages are flushed before unmap_vmas() * drops the lock and schedules. */ void unmap_vmas(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr) { struct mm_struct *mm = vma->vm_mm; mmu_notifier_invalidate_range_start(mm, start_addr, end_addr); for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next) unmap_single_vma(tlb, vma, start_addr, end_addr, NULL); mmu_notifier_invalidate_range_end(mm, start_addr, end_addr); } /** * zap_page_range - remove user pages in a given range * @vma: vm_area_struct holding the applicable pages * @start: starting address of pages to zap * @size: number of bytes to zap * @details: details of nonlinear truncation or shared cache invalidation * * Caller must protect the VMA list */ void zap_page_range(struct vm_area_struct *vma, unsigned long start, unsigned long size, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; struct mmu_gather tlb; unsigned long end = start + size; lru_add_drain(); tlb_gather_mmu(&tlb, mm, start, end); update_hiwater_rss(mm); mmu_notifier_invalidate_range_start(mm, start, end); for ( ; vma && vma->vm_start < end; vma = vma->vm_next) unmap_single_vma(&tlb, vma, start, end, details); mmu_notifier_invalidate_range_end(mm, start, end); tlb_finish_mmu(&tlb, start, end); } /** * zap_page_range_single - remove user pages in a given range * @vma: vm_area_struct holding the applicable pages * @address: starting address of pages to zap * @size: number of bytes to zap * @details: details of nonlinear truncation or shared cache invalidation * * The range must fit into one VMA. */ static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address, unsigned long size, struct zap_details *details) { struct mm_struct *mm = vma->vm_mm; struct mmu_gather tlb; unsigned long end = address + size; lru_add_drain(); tlb_gather_mmu(&tlb, mm, address, end); update_hiwater_rss(mm); mmu_notifier_invalidate_range_start(mm, address, end); unmap_single_vma(&tlb, vma, address, end, details); mmu_notifier_invalidate_range_end(mm, address, end); tlb_finish_mmu(&tlb, address, end); } /** * zap_vma_ptes - remove ptes mapping the vma * @vma: vm_area_struct holding ptes to be zapped * @address: starting address of pages to zap * @size: number of bytes to zap * * This function only unmaps ptes assigned to VM_PFNMAP vmas. * * The entire address range must be fully contained within the vma. * * Returns 0 if successful. */ int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, unsigned long size) { if (address < vma->vm_start || address + size > vma->vm_end || !(vma->vm_flags & VM_PFNMAP)) return -1; zap_page_range_single(vma, address, size, NULL); return 0; } EXPORT_SYMBOL_GPL(zap_vma_ptes); /** * follow_page_mask - look up a page descriptor from a user-virtual address * @vma: vm_area_struct mapping @address * @address: virtual address to look up * @flags: flags modifying lookup behaviour * @page_mask: on output, *page_mask is set according to the size of the page * * @flags can have FOLL_ flags set, defined in <linux/mm.h> * * Returns the mapped (struct page *), %NULL if no mapping exists, or * an error pointer if there is a mapping to something not represented * by a page descriptor (see also vm_normal_page()). */ struct page *follow_page_mask(struct vm_area_struct *vma, unsigned long address, unsigned int flags, unsigned int *page_mask) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; struct page *page; struct mm_struct *mm = vma->vm_mm; *page_mask = 0; page = follow_huge_addr(mm, address, flags & FOLL_WRITE); if (!IS_ERR(page)) { BUG_ON(flags & FOLL_GET); goto out; } page = NULL; pgd = pgd_offset(mm, address); if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) goto no_page_table; pud = pud_offset(pgd, address); if (pud_none(*pud)) goto no_page_table; if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) { BUG_ON(flags & FOLL_GET); page = follow_huge_pud(mm, address, pud, flags & FOLL_WRITE); goto out; } if (unlikely(pud_bad(*pud))) goto no_page_table; pmd = pmd_offset(pud, address); if (pmd_none(*pmd)) goto no_page_table; if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) { BUG_ON(flags & FOLL_GET); page = follow_huge_pmd(mm, address, pmd, flags & FOLL_WRITE); goto out; } if ((flags & FOLL_NUMA) && pmd_numa(*pmd)) goto no_page_table; if (pmd_trans_huge(*pmd)) { if (flags & FOLL_SPLIT) { split_huge_page_pmd(vma, address, pmd); goto split_fallthrough; } spin_lock(&mm->page_table_lock); if (likely(pmd_trans_huge(*pmd))) { if (unlikely(pmd_trans_splitting(*pmd))) { spin_unlock(&mm->page_table_lock); wait_split_huge_page(vma->anon_vma, pmd); } else { page = follow_trans_huge_pmd(vma, address, pmd, flags); spin_unlock(&mm->page_table_lock); *page_mask = HPAGE_PMD_NR - 1; goto out; } } else spin_unlock(&mm->page_table_lock); /* fall through */ } split_fallthrough: if (unlikely(pmd_bad(*pmd))) goto no_page_table; ptep = pte_offset_map_lock(mm, pmd, address, &ptl); pte = *ptep; if (!pte_present(pte)) { swp_entry_t entry; /* * KSM's break_ksm() relies upon recognizing a ksm page * even while it is being migrated, so for that case we * need migration_entry_wait(). */ if (likely(!(flags & FOLL_MIGRATION))) goto no_page; if (pte_none(pte) || pte_file(pte)) goto no_page; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto no_page; pte_unmap_unlock(ptep, ptl); migration_entry_wait(mm, pmd, address); goto split_fallthrough; } if ((flags & FOLL_NUMA) && pte_numa(pte)) goto no_page; if ((flags & FOLL_WRITE) && !pte_write(pte)) goto unlock; page = vm_normal_page(vma, address, pte); if (unlikely(!page)) { if ((flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(pte))) goto bad_page; page = pte_page(pte); } if (flags & FOLL_GET) get_page_foll(page); if (flags & FOLL_TOUCH) { if ((flags & FOLL_WRITE) && !pte_dirty(pte) && !PageDirty(page)) set_page_dirty(page); /* * pte_mkyoung() would be more correct here, but atomic care * is needed to avoid losing the dirty bit: it is easier to use * mark_page_accessed(). */ mark_page_accessed(page); } if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) { /* * The preliminary mapping check is mainly to avoid the * pointless overhead of lock_page on the ZERO_PAGE * which might bounce very badly if there is contention. * * If the page is already locked, we don't need to * handle it now - vmscan will handle it later if and * when it attempts to reclaim the page. */ if (page->mapping && trylock_page(page)) { lru_add_drain(); /* push cached pages to LRU */ /* * Because we lock page here, and migration is * blocked by the pte's page reference, and we * know the page is still mapped, we don't even * need to check for file-cache page truncation. */ mlock_vma_page(page); unlock_page(page); } } unlock: pte_unmap_unlock(ptep, ptl); out: return page; bad_page: pte_unmap_unlock(ptep, ptl); return ERR_PTR(-EFAULT); no_page: pte_unmap_unlock(ptep, ptl); if (!pte_none(pte)) return page; no_page_table: /* * When core dumping an enormous anonymous area that nobody * has touched so far, we don't want to allocate unnecessary pages or * page tables. Return error instead of NULL to skip handle_mm_fault, * then get_dump_page() will return NULL to leave a hole in the dump. * But we can only make this optimization where a hole would surely * be zero-filled if handle_mm_fault() actually did handle it. */ if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault)) return ERR_PTR(-EFAULT); return page; } static inline int stack_guard_page(struct vm_area_struct *vma, unsigned long addr) { return stack_guard_page_start(vma, addr) || stack_guard_page_end(vma, addr+PAGE_SIZE); } /** * __get_user_pages() - pin user pages in memory * @tsk: task_struct of target task * @mm: mm_struct of target mm * @start: starting user address * @nr_pages: number of pages from start to pin * @gup_flags: flags modifying pin behaviour * @pages: array that receives pointers to the pages pinned. * Should be at least nr_pages long. Or NULL, if caller * only intends to ensure the pages are faulted in. * @vmas: array of pointers to vmas corresponding to each page. * Or NULL if the caller does not require them. * @nonblocking: whether waiting for disk IO or mmap_sem contention * * Returns number of pages pinned. This may be fewer than the number * requested. If nr_pages is 0 or negative, returns 0. If no pages * were pinned, returns -errno. Each page returned must be released * with a put_page() call when it is finished with. vmas will only * remain valid while mmap_sem is held. * * Must be called with mmap_sem held for read or write. * * __get_user_pages walks a process's page tables and takes a reference to * each struct page that each user address corresponds to at a given * instant. That is, it takes the page that would be accessed if a user * thread accesses the given user virtual address at that instant. * * This does not guarantee that the page exists in the user mappings when * __get_user_pages returns, and there may even be a completely different * page there in some cases (eg. if mmapped pagecache has been invalidated * and subsequently re faulted). However it does guarantee that the page * won't be freed completely. And mostly callers simply care that the page * contains data that was valid *at some point in time*. Typically, an IO * or similar operation cannot guarantee anything stronger anyway because * locks can't be held over the syscall boundary. * * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If * the page is written to, set_page_dirty (or set_page_dirty_lock, as * appropriate) must be called after the page is finished with, and * before put_page is called. * * If @nonblocking != NULL, __get_user_pages will not wait for disk IO * or mmap_sem contention, and if waiting is needed to pin all pages, * *@nonblocking will be set to 0. * * In most cases, get_user_pages or get_user_pages_fast should be used * instead of __get_user_pages. __get_user_pages should be used only if * you need some special @gup_flags. */ long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, unsigned long nr_pages, unsigned int gup_flags, struct page **pages, struct vm_area_struct **vmas, int *nonblocking) { long i; unsigned long vm_flags; unsigned int page_mask; if (!nr_pages) return 0; VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET)); /* * Require read or write permissions. * If FOLL_FORCE is set, we only require the "MAY" flags. */ vm_flags = (gup_flags & FOLL_WRITE) ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD); vm_flags &= (gup_flags & FOLL_FORCE) ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE); /* * If FOLL_FORCE and FOLL_NUMA are both set, handle_mm_fault * would be called on PROT_NONE ranges. We must never invoke * handle_mm_fault on PROT_NONE ranges or the NUMA hinting * page faults would unprotect the PROT_NONE ranges if * _PAGE_NUMA and _PAGE_PROTNONE are sharing the same pte/pmd * bitflag. So to avoid that, don't set FOLL_NUMA if * FOLL_FORCE is set. */ if (!(gup_flags & FOLL_FORCE)) gup_flags |= FOLL_NUMA; i = 0; do { struct vm_area_struct *vma; vma = find_extend_vma(mm, start); if (!vma && in_gate_area(mm, start)) { unsigned long pg = start & PAGE_MASK; pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; /* user gate pages are read-only */ if (gup_flags & FOLL_WRITE) return i ? : -EFAULT; if (pg > TASK_SIZE) pgd = pgd_offset_k(pg); else pgd = pgd_offset_gate(mm, pg); BUG_ON(pgd_none(*pgd)); pud = pud_offset(pgd, pg); BUG_ON(pud_none(*pud)); pmd = pmd_offset(pud, pg); if (pmd_none(*pmd)) return i ? : -EFAULT; VM_BUG_ON(pmd_trans_huge(*pmd)); pte = pte_offset_map(pmd, pg); if (pte_none(*pte)) { pte_unmap(pte); return i ? : -EFAULT; } vma = get_gate_vma(mm); if (pages) { struct page *page; page = vm_normal_page(vma, start, *pte); if (!page) { if (!(gup_flags & FOLL_DUMP) && (is_zero_pfn(pte_pfn(*pte)))) page = pte_page(*pte); else { pte_unmap(pte); return i ? : -EFAULT; } } pages[i] = page; get_page(page); } pte_unmap(pte); page_mask = 0; goto next_page; } if (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP)) || !(vm_flags & vma->vm_flags)) return i ? : -EFAULT; if (is_vm_hugetlb_page(vma)) { i = follow_hugetlb_page(mm, vma, pages, vmas, &start, &nr_pages, i, gup_flags); continue; } do { struct page *page; unsigned int foll_flags = gup_flags; unsigned int page_increm; /* * If we have a pending SIGKILL, don't keep faulting * pages and potentially allocating memory. */ if (unlikely(fatal_signal_pending(current))) return i ? i : -ERESTARTSYS; cond_resched(); while (!(page = follow_page_mask(vma, start, foll_flags, &page_mask))) { int ret; unsigned int fault_flags = 0; /* For mlock, just skip the stack guard page. */ if (foll_flags & FOLL_MLOCK) { if (stack_guard_page(vma, start)) goto next_page; } if (foll_flags & FOLL_WRITE) fault_flags |= FAULT_FLAG_WRITE; if (nonblocking) fault_flags |= FAULT_FLAG_ALLOW_RETRY; if (foll_flags & FOLL_NOWAIT) fault_flags |= (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT); ret = handle_mm_fault(mm, vma, start, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return i ? i : -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) { if (i) return i; else if (gup_flags & FOLL_HWPOISON) return -EHWPOISON; else return -EFAULT; } if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV)) return i ? i : -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } if (ret & VM_FAULT_RETRY) { if (nonblocking) *nonblocking = 0; return i; } /* * The VM_FAULT_WRITE bit tells us that * do_wp_page has broken COW when necessary, * even if maybe_mkwrite decided not to set * pte_write. We can thus safely do subsequent * page lookups as if they were reads. But only * do so when looping for pte_write is futile: * in some cases userspace may also be wanting * to write to the gotten user page, which a * read fault here might prevent (a readonly * page might get reCOWed by userspace write). */ if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE)) foll_flags &= ~FOLL_WRITE; cond_resched(); } if (IS_ERR(page)) return i ? i : PTR_ERR(page); if (pages) { pages[i] = page; flush_anon_page(vma, page, start); flush_dcache_page(page); page_mask = 0; } next_page: if (vmas) { vmas[i] = vma; page_mask = 0; } page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask); if (page_increm > nr_pages) page_increm = nr_pages; i += page_increm; start += page_increm * PAGE_SIZE; nr_pages -= page_increm; } while (nr_pages && start < vma->vm_end); } while (nr_pages); return i; } EXPORT_SYMBOL(__get_user_pages); /* * fixup_user_fault() - manually resolve a user page fault * @tsk: the task_struct to use for page fault accounting, or * NULL if faults are not to be recorded. * @mm: mm_struct of target mm * @address: user address * @fault_flags:flags to pass down to handle_mm_fault() * * This is meant to be called in the specific scenario where for locking reasons * we try to access user memory in atomic context (within a pagefault_disable() * section), this returns -EFAULT, and we want to resolve the user fault before * trying again. * * Typically this is meant to be used by the futex code. * * The main difference with get_user_pages() is that this function will * unconditionally call handle_mm_fault() which will in turn perform all the * necessary SW fixup of the dirty and young bits in the PTE, while * handle_mm_fault() only guarantees to update these in the struct page. * * This is important for some architectures where those bits also gate the * access permission to the page because they are maintained in software. On * such architectures, gup() will not be enough to make a subsequent access * succeed. * * This should be called with the mm_sem held for read. */ int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm, unsigned long address, unsigned int fault_flags) { struct vm_area_struct *vma; vm_flags_t vm_flags; int ret; vma = find_extend_vma(mm, address); if (!vma || address < vma->vm_start) return -EFAULT; vm_flags = (fault_flags & FAULT_FLAG_WRITE) ? VM_WRITE : VM_READ; if (!(vm_flags & vma->vm_flags)) return -EFAULT; ret = handle_mm_fault(mm, vma, address, fault_flags); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return -ENOMEM; if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE)) return -EHWPOISON; if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV)) return -EFAULT; BUG(); } if (tsk) { if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; } return 0; } /* * get_user_pages() - pin user pages in memory * @tsk: the task_struct to use for page fault accounting, or * NULL if faults are not to be recorded. * @mm: mm_struct of target mm * @start: starting user address * @nr_pages: number of pages from start to pin * @write: whether pages will be written to by the caller * @force: whether to force write access even if user mapping is * readonly. This will result in the page being COWed even * in MAP_SHARED mappings. You do not want this. * @pages: array that receives pointers to the pages pinned. * Should be at least nr_pages long. Or NULL, if caller * only intends to ensure the pages are faulted in. * @vmas: array of pointers to vmas corresponding to each page. * Or NULL if the caller does not require them. * * Returns number of pages pinned. This may be fewer than the number * requested. If nr_pages is 0 or negative, returns 0. If no pages * were pinned, returns -errno. Each page returned must be released * with a put_page() call when it is finished with. vmas will only * remain valid while mmap_sem is held. * * Must be called with mmap_sem held for read or write. * * get_user_pages walks a process's page tables and takes a reference to * each struct page that each user address corresponds to at a given * instant. That is, it takes the page that would be accessed if a user * thread accesses the given user virtual address at that instant. * * This does not guarantee that the page exists in the user mappings when * get_user_pages returns, and there may even be a completely different * page there in some cases (eg. if mmapped pagecache has been invalidated * and subsequently re faulted). However it does guarantee that the page * won't be freed completely. And mostly callers simply care that the page * contains data that was valid *at some point in time*. Typically, an IO * or similar operation cannot guarantee anything stronger anyway because * locks can't be held over the syscall boundary. * * If write=0, the page must not be written to. If the page is written to, * set_page_dirty (or set_page_dirty_lock, as appropriate) must be called * after the page is finished with, and before put_page is called. * * get_user_pages is typically used for fewer-copy IO operations, to get a * handle on the memory by some means other than accesses via the user virtual * addresses. The pages may be submitted for DMA to devices or accessed via * their kernel linear mapping (via the kmap APIs). Care should be taken to * use the correct cache flushing APIs. * * See also get_user_pages_fast, for performance critical applications. */ long get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, unsigned long nr_pages, int write, int force, struct page **pages, struct vm_area_struct **vmas) { int flags = FOLL_TOUCH; if (pages) flags |= FOLL_GET; if (write) flags |= FOLL_WRITE; if (force) flags |= FOLL_FORCE; return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas, NULL); } EXPORT_SYMBOL(get_user_pages); /** * get_dump_page() - pin user page in memory while writing it to core dump * @addr: user address * * Returns struct page pointer of user page pinned for dump, * to be freed afterwards by page_cache_release() or put_page(). * * Returns NULL on any kind of failure - a hole must then be inserted into * the corefile, to preserve alignment with its headers; and also returns * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found - * allowing a hole to be left in the corefile to save diskspace. * * Called without mmap_sem, but after all other threads have been killed. */ #ifdef CONFIG_ELF_CORE struct page *get_dump_page(unsigned long addr) { struct vm_area_struct *vma; struct page *page; if (__get_user_pages(current, current->mm, addr, 1, FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma, NULL) < 1) return NULL; flush_cache_page(vma, addr, page_to_pfn(page)); return page; } #endif /* CONFIG_ELF_CORE */ pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl) { pgd_t * pgd = pgd_offset(mm, addr); pud_t * pud = pud_alloc(mm, pgd, addr); if (pud) { pmd_t * pmd = pmd_alloc(mm, pud, addr); if (pmd) { VM_BUG_ON(pmd_trans_huge(*pmd)); return pte_alloc_map_lock(mm, pmd, addr, ptl); } } return NULL; } /* * This is the old fallback for page remapping. * * For historical reasons, it only allows reserved pages. Only * old drivers should use this, and they needed to mark their * pages reserved for the old functions anyway. */ static int insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte; spinlock_t *ptl; retval = -EINVAL; if (PageAnon(page)) goto out; retval = -ENOMEM; flush_dcache_page(page); pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ get_page(page); inc_mm_counter_fast(mm, MM_FILEPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) inc_mm_counter_fast(mm, MM_LOW_FILEPAGES); #endif page_add_file_rmap(page); set_pte_at(mm, addr, pte, mk_pte(page, prot)); retval = 0; pte_unmap_unlock(pte, ptl); return retval; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } /** * vm_insert_page - insert single page into user vma * @vma: user vma to map to * @addr: target user address of this page * @page: source kernel page * * This allows drivers to insert individual pages they've allocated * into a user vma. * * The page has to be a nice clean _individual_ kernel allocation. * If you allocate a compound page, you need to have marked it as * such (__GFP_COMP), or manually just split the page up yourself * (see split_page()). * * NOTE! Traditionally this was done with "remap_pfn_range()" which * took an arbitrary page protection parameter. This doesn't allow * that. Your vma protection will have to be set up correctly, which * means that if you want a shared writable mapping, you'd better * ask for a shared writable mapping! * * The page does not need to be reserved. * * Usually this function is called from f_op->mmap() handler * under mm->mmap_sem write-lock, so it can change vma->vm_flags. * Caller must set VM_MIXEDMAP on vma if it wants to call this * function from other places, for example from page-fault handler. */ int vm_insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page) { if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; if (!page_count(page)) return -EINVAL; if (!(vma->vm_flags & VM_MIXEDMAP)) { BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem)); BUG_ON(vma->vm_flags & VM_PFNMAP); vma->vm_flags |= VM_MIXEDMAP; } return insert_page(vma, addr, page, vma->vm_page_prot); } EXPORT_SYMBOL(vm_insert_page); static int insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte, entry; spinlock_t *ptl; retval = -ENOMEM; pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ entry = pte_mkspecial(pfn_pte(pfn, prot)); set_pte_at(mm, addr, pte, entry); update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */ retval = 0; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } /** * vm_insert_pfn - insert single pfn into user vma * @vma: user vma to map to * @addr: target user address of this page * @pfn: source kernel pfn * * Similar to vm_insert_page, this allows drivers to insert individual pages * they've allocated into a user vma. Same comments apply. * * This function should only be called from a vm_ops->fault handler, and * in that case the handler should return NULL. * * vma cannot be a COW mapping. * * As this is called only for pages that do not currently exist, we * do not need to flush old virtual caches or the TLB. */ int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { int ret; pgprot_t pgprot = vma->vm_page_prot; /* * Technically, architectures with pte_special can avoid all these * restrictions (same for remap_pfn_range). However we would like * consistency in testing and feature parity among all, so we should * try to keep these invariants in place for everybody. */ BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == (VM_PFNMAP|VM_MIXEDMAP)); BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags)); BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; if (track_pfn_insert(vma, &pgprot, pfn)) return -EINVAL; ret = insert_pfn(vma, addr, pfn, pgprot); return ret; } EXPORT_SYMBOL(vm_insert_pfn); int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { BUG_ON(!(vma->vm_flags & VM_MIXEDMAP)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; /* * If we don't have pte special, then we have to use the pfn_valid() * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must* * refcount the page if pfn_valid is true (hence insert_page rather * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP * without pte special, it would there be refcounted as a normal page. */ if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) { struct page *page; page = pfn_to_page(pfn); return insert_page(vma, addr, page, vma->vm_page_prot); } return insert_pfn(vma, addr, pfn, vma->vm_page_prot); } EXPORT_SYMBOL(vm_insert_mixed); /* * maps a range of physical memory into the requested pages. the old * mappings are removed. any references to nonexistent pages results * in null mappings (currently treated as "copy-on-access") */ static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pte_t *pte; spinlock_t *ptl; pte = pte_alloc_map_lock(mm, pmd, addr, &ptl); if (!pte) return -ENOMEM; arch_enter_lazy_mmu_mode(); do { BUG_ON(!pte_none(*pte)); set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot))); pfn++; } while (pte++, addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); pte_unmap_unlock(pte - 1, ptl); return 0; } static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pmd_t *pmd; unsigned long next; pfn -= addr >> PAGE_SHIFT; pmd = pmd_alloc(mm, pud, addr); if (!pmd) return -ENOMEM; VM_BUG_ON(pmd_trans_huge(*pmd)); do { next = pmd_addr_end(addr, end); if (remap_pte_range(mm, pmd, addr, next, pfn + (addr >> PAGE_SHIFT), prot)) return -ENOMEM; } while (pmd++, addr = next, addr != end); return 0; } static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd, unsigned long addr, unsigned long end, unsigned long pfn, pgprot_t prot) { pud_t *pud; unsigned long next; pfn -= addr >> PAGE_SHIFT; pud = pud_alloc(mm, pgd, addr); if (!pud) return -ENOMEM; do { next = pud_addr_end(addr, end); if (remap_pmd_range(mm, pud, addr, next, pfn + (addr >> PAGE_SHIFT), prot)) return -ENOMEM; } while (pud++, addr = next, addr != end); return 0; } /** * remap_pfn_range - remap kernel memory to userspace * @vma: user vma to map to * @addr: target user address to start at * @pfn: physical address of kernel memory * @size: size of map area * @prot: page protection flags for this mapping * * Note: this is only safe if the mm semaphore is held when called. */ int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, unsigned long size, pgprot_t prot) { pgd_t *pgd; unsigned long next; unsigned long end = addr + PAGE_ALIGN(size); struct mm_struct *mm = vma->vm_mm; int err; /* * Physically remapped pages are special. Tell the * rest of the world about it: * VM_IO tells people not to look at these pages * (accesses can have side effects). * VM_PFNMAP tells the core MM that the base pages are just * raw PFN mappings, and do not have a "struct page" associated * with them. * VM_DONTEXPAND * Disable vma merging and expanding with mremap(). * VM_DONTDUMP * Omit vma from core dump, even when VM_IO turned off. * * There's a horrible special case to handle copy-on-write * behaviour that some programs depend on. We mark the "original" * un-COW'ed pages by matching them up with "vma->vm_pgoff". * See vm_normal_page() for details. */ if (is_cow_mapping(vma->vm_flags)) { if (addr != vma->vm_start || end != vma->vm_end) return -EINVAL; vma->vm_pgoff = pfn; } err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size)); if (err) return -EINVAL; vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP; BUG_ON(addr >= end); pfn -= addr >> PAGE_SHIFT; pgd = pgd_offset(mm, addr); flush_cache_range(vma, addr, end); do { next = pgd_addr_end(addr, end); err = remap_pud_range(mm, pgd, addr, next, pfn + (addr >> PAGE_SHIFT), prot); if (err) break; } while (pgd++, addr = next, addr != end); if (err) untrack_pfn(vma, pfn, PAGE_ALIGN(size)); return err; } EXPORT_SYMBOL(remap_pfn_range); /** * vm_iomap_memory - remap memory to userspace * @vma: user vma to map to * @start: start of area * @len: size of area * * This is a simplified io_remap_pfn_range() for common driver use. The * driver just needs to give us the physical memory range to be mapped, * we'll figure out the rest from the vma information. * * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get * whatever write-combining details or similar. */ int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len) { unsigned long vm_len, pfn, pages; /* Check that the physical memory area passed in looks valid */ if (start + len < start) return -EINVAL; /* * You *really* shouldn't map things that aren't page-aligned, * but we've historically allowed it because IO memory might * just have smaller alignment. */ len += start & ~PAGE_MASK; pfn = start >> PAGE_SHIFT; pages = (len + ~PAGE_MASK) >> PAGE_SHIFT; if (pfn + pages < pfn) return -EINVAL; /* We start the mapping 'vm_pgoff' pages into the area */ if (vma->vm_pgoff > pages) return -EINVAL; pfn += vma->vm_pgoff; pages -= vma->vm_pgoff; /* Can we fit all of the mapping? */ vm_len = vma->vm_end - vma->vm_start; if (vm_len >> PAGE_SHIFT > pages) return -EINVAL; /* Ok, let it rip */ return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot); } EXPORT_SYMBOL(vm_iomap_memory); static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pte_t *pte; int err; pgtable_t token; spinlock_t *uninitialized_var(ptl); pte = (mm == &init_mm) ? pte_alloc_kernel(pmd, addr) : pte_alloc_map_lock(mm, pmd, addr, &ptl); if (!pte) return -ENOMEM; BUG_ON(pmd_huge(*pmd)); arch_enter_lazy_mmu_mode(); token = pmd_pgtable(*pmd); do { err = fn(pte++, token, addr, data); if (err) break; } while (addr += PAGE_SIZE, addr != end); arch_leave_lazy_mmu_mode(); if (mm != &init_mm) pte_unmap_unlock(pte-1, ptl); return err; } static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pmd_t *pmd; unsigned long next; int err; BUG_ON(pud_huge(*pud)); pmd = pmd_alloc(mm, pud, addr); if (!pmd) return -ENOMEM; do { next = pmd_addr_end(addr, end); err = apply_to_pte_range(mm, pmd, addr, next, fn, data); if (err) break; } while (pmd++, addr = next, addr != end); return err; } static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd, unsigned long addr, unsigned long end, pte_fn_t fn, void *data) { pud_t *pud; unsigned long next; int err; pud = pud_alloc(mm, pgd, addr); if (!pud) return -ENOMEM; do { next = pud_addr_end(addr, end); err = apply_to_pmd_range(mm, pud, addr, next, fn, data); if (err) break; } while (pud++, addr = next, addr != end); return err; } /* * Scan a region of virtual memory, filling in page tables as necessary * and calling a provided function on each leaf page table. */ int apply_to_page_range(struct mm_struct *mm, unsigned long addr, unsigned long size, pte_fn_t fn, void *data) { pgd_t *pgd; unsigned long next; unsigned long end = addr + size; int err; BUG_ON(addr >= end); pgd = pgd_offset(mm, addr); do { next = pgd_addr_end(addr, end); err = apply_to_pud_range(mm, pgd, addr, next, fn, data); if (err) break; } while (pgd++, addr = next, addr != end); return err; } EXPORT_SYMBOL_GPL(apply_to_page_range); /* * handle_pte_fault chooses page fault handler according to an entry * which was read non-atomically. Before making any commitment, on * those architectures or configurations (e.g. i386 with PAE) which * might give a mix of unmatched parts, do_swap_page and do_nonlinear_fault * must check under lock before unmapping the pte and proceeding * (but do_wp_page is only called after already making such a check; * and do_anonymous_page can safely check later on). */ static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd, pte_t *page_table, pte_t orig_pte) { int same = 1; #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT) if (sizeof(pte_t) > sizeof(unsigned long)) { spinlock_t *ptl = pte_lockptr(mm, pmd); spin_lock(ptl); same = pte_same(*page_table, orig_pte); spin_unlock(ptl); } #endif pte_unmap(page_table); return same; } static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma) { /* * If the source page was a PFN mapping, we don't have * a "struct page" for it. We do a best-effort copy by * just copying from the original user address. If that * fails, we just zero-fill it. Live with it. */ if (unlikely(!src)) { void *kaddr = kmap_atomic(dst); void __user *uaddr = (void __user *)(va & PAGE_MASK); /* * This really shouldn't fail, because the page is there * in the page tables. But it might just be unreadable, * in which case we just give up and fill the result with * zeroes. */ if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) clear_page(kaddr); kunmap_atomic(kaddr); flush_dcache_page(dst); } else { copy_user_highpage(dst, src, va, vma); uksm_cow_page(vma, src); } } /* * This routine handles present pages, when users try to write * to a shared page. It is done by copying the page to a new address * and decrementing the shared-page counter for the old page. * * Note that this routine assumes that the protection checks have been * done by the caller (the low-level page fault routine in most cases). * Thus we can safely just mark it writable once we've done any necessary * COW. * * We also mark the page dirty at this point even though the page will * change only once the write actually happens. This avoids a few races, * and potentially makes it more efficient. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), with pte both mapped and locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, spinlock_t *ptl, pte_t orig_pte) __releases(ptl) { struct page *old_page, *new_page = NULL; pte_t entry; int ret = 0; int page_mkwrite = 0; struct page *dirty_page = NULL; unsigned long mmun_start = 0; /* For mmu_notifiers */ unsigned long mmun_end = 0; /* For mmu_notifiers */ old_page = vm_normal_page(vma, address, orig_pte); if (!old_page) { /* * VM_MIXEDMAP !pfn_valid() case * * We should not cow pages in a shared writeable mapping. * Just mark the pages writable as we can't do any dirty * accounting on raw pfn maps. */ if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) == (VM_WRITE|VM_SHARED)) goto reuse; goto gotten; } /* * Take out anonymous pages first, anonymous shared vmas are * not dirty accountable. */ if (PageAnon(old_page) && !PageKsm(old_page)) { if (!trylock_page(old_page)) { page_cache_get(old_page); pte_unmap_unlock(page_table, ptl); lock_page(old_page); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_same(*page_table, orig_pte)) { unlock_page(old_page); goto unlock; } page_cache_release(old_page); } if (reuse_swap_page(old_page)) { /* * The page is all ours. Move it to our anon_vma so * the rmap code will not search our parent or siblings. * Protected against the rmap code by the page lock. */ page_move_anon_rmap(old_page, vma, address); unlock_page(old_page); goto reuse; } unlock_page(old_page); } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) == (VM_WRITE|VM_SHARED))) { /* * Only catch write-faults on shared writable pages, * read-only shared pages can get COWed by * get_user_pages(.write=1, .force=1). */ if (vma->vm_ops && vma->vm_ops->page_mkwrite) { struct vm_fault vmf; int tmp; vmf.virtual_address = (void __user *)(address & PAGE_MASK); vmf.pgoff = old_page->index; vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; vmf.page = old_page; /* * Notify the address space that the page is about to * become writable so that it can prohibit this or wait * for the page to get into an appropriate state. * * We do this without the lock held, so that it can * sleep if it needs to. */ page_cache_get(old_page); pte_unmap_unlock(page_table, ptl); tmp = vma->vm_ops->page_mkwrite(vma, &vmf); if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { ret = tmp; goto unwritable_page; } if (unlikely(!(tmp & VM_FAULT_LOCKED))) { lock_page(old_page); if (!old_page->mapping) { ret = 0; /* retry the fault */ unlock_page(old_page); goto unwritable_page; } } else VM_BUG_ON(!PageLocked(old_page)); /* * Since we dropped the lock we need to revalidate * the PTE as someone else may have changed it. If * they did, we just return, as we can count on the * MMU to tell us if they didn't also make it writable. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_same(*page_table, orig_pte)) { unlock_page(old_page); goto unlock; } page_mkwrite = 1; } dirty_page = old_page; get_page(dirty_page); reuse: flush_cache_page(vma, address, pte_pfn(orig_pte)); entry = pte_mkyoung(orig_pte); entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (ptep_set_access_flags(vma, address, page_table, entry,1)) update_mmu_cache(vma, address, page_table); pte_unmap_unlock(page_table, ptl); ret |= VM_FAULT_WRITE; if (!dirty_page) return ret; /* * Yes, Virginia, this is actually required to prevent a race * with clear_page_dirty_for_io() from clearing the page dirty * bit after it clear all dirty ptes, but before a racing * do_wp_page installs a dirty pte. * * __do_fault is protected similarly. */ if (!page_mkwrite) { wait_on_page_locked(dirty_page); set_page_dirty_balance(dirty_page, page_mkwrite); /* file_update_time outside page_lock */ if (vma->vm_file) file_update_time(vma->vm_file); } put_page(dirty_page); if (page_mkwrite) { struct address_space *mapping = dirty_page->mapping; set_page_dirty(dirty_page); unlock_page(dirty_page); page_cache_release(dirty_page); if (mapping) { /* * Some device drivers do not set page.mapping * but still dirty their pages */ balance_dirty_pages_ratelimited(mapping); } } return ret; } /* * Ok, we need to copy. Oh, well.. */ page_cache_get(old_page); gotten: pte_unmap_unlock(page_table, ptl); if (unlikely(anon_vma_prepare(vma))) goto oom; if (is_zero_pfn(pte_pfn(orig_pte))) { new_page = alloc_zeroed_user_highpage_movable(vma, address); if (!new_page) goto oom; uksm_cow_pte(vma, orig_pte); } else { new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (!new_page) goto oom; cow_user_page(new_page, old_page, address, vma); } __SetPageUptodate(new_page); if (mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL)) goto oom_free_new; mmun_start = address & PAGE_MASK; mmun_end = mmun_start + PAGE_SIZE; mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); /* * Re-check the pte - we dropped the lock */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) { if (old_page) { if (!PageAnon(old_page)) { dec_mm_counter_fast(mm, MM_FILEPAGES); inc_mm_counter_fast(mm, MM_ANONPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(old_page)) dec_mm_counter_fast(mm, MM_LOW_FILEPAGES); if (!PageHighMem(new_page)) inc_mm_counter_fast(mm, MM_LOW_ANONPAGES); } else { if(!PageHighMem(old_page) && PageHighMem(new_page)) dec_mm_counter_fast(mm, MM_LOW_ANONPAGES); if(PageHighMem(old_page) && !PageHighMem(new_page)) inc_mm_counter_fast(mm, MM_LOW_ANONPAGES); #endif } uksm_bugon_zeropage(orig_pte); } else { uksm_unmap_zero_page(orig_pte); inc_mm_counter_fast(mm, MM_ANONPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(new_page)) inc_mm_counter_fast(mm, MM_LOW_ANONPAGES); #endif } flush_cache_page(vma, address, pte_pfn(orig_pte)); entry = mk_pte(new_page, vma->vm_page_prot); entry = maybe_mkwrite(pte_mkdirty(entry), vma); /* * Clear the pte entry and flush it first, before updating the * pte with the new entry. This will avoid a race condition * seen in the presence of one thread doing SMC and another * thread doing COW. */ ptep_clear_flush(vma, address, page_table); page_add_new_anon_rmap(new_page, vma, address); /* * We call the notify macro here because, when using secondary * mmu page tables (such as kvm shadow page tables), we want the * new page to be mapped directly into the secondary page table. */ set_pte_at_notify(mm, address, page_table, entry); update_mmu_cache(vma, address, page_table); if (old_page) { /* * Only after switching the pte to the new page may * we remove the mapcount here. Otherwise another * process may come and find the rmap count decremented * before the pte is switched to the new page, and * "reuse" the old page writing into it while our pte * here still points into it and can be read by other * threads. * * The critical issue is to order this * page_remove_rmap with the ptp_clear_flush above. * Those stores are ordered by (if nothing else,) * the barrier present in the atomic_add_negative * in page_remove_rmap. * * Then the TLB flush in ptep_clear_flush ensures that * no process can access the old page before the * decremented mapcount is visible. And the old page * cannot be reused until after the decremented * mapcount is visible. So transitively, TLBs to * old page will be flushed before it can be reused. */ page_remove_rmap(old_page); } /* Free the old page.. */ new_page = old_page; ret |= VM_FAULT_WRITE; } else mem_cgroup_uncharge_page(new_page); if (new_page) page_cache_release(new_page); unlock: pte_unmap_unlock(page_table, ptl); if (mmun_end > mmun_start) mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); if (old_page) { /* * Don't let another task, with possibly unlocked vma, * keep the mlocked page. */ if ((ret & VM_FAULT_WRITE) && (vma->vm_flags & VM_LOCKED)) { lock_page(old_page); /* LRU manipulation */ munlock_vma_page(old_page); unlock_page(old_page); } page_cache_release(old_page); } return ret; oom_free_new: page_cache_release(new_page); oom: if (old_page) page_cache_release(old_page); return VM_FAULT_OOM; unwritable_page: page_cache_release(old_page); return ret; } static void unmap_mapping_range_vma(struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, struct zap_details *details) { zap_page_range_single(vma, start_addr, end_addr - start_addr, details); } static inline void unmap_mapping_range_tree(struct rb_root *root, struct zap_details *details) { struct vm_area_struct *vma; pgoff_t vba, vea, zba, zea; vma_interval_tree_foreach(vma, root, details->first_index, details->last_index) { vba = vma->vm_pgoff; vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1; /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */ zba = details->first_index; if (zba < vba) zba = vba; zea = details->last_index; if (zea > vea) zea = vea; unmap_mapping_range_vma(vma, ((zba - vba) << PAGE_SHIFT) + vma->vm_start, ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start, details); } } static inline void unmap_mapping_range_list(struct list_head *head, struct zap_details *details) { struct vm_area_struct *vma; /* * In nonlinear VMAs there is no correspondence between virtual address * offset and file offset. So we must perform an exhaustive search * across *all* the pages in each nonlinear VMA, not just the pages * whose virtual address lies outside the file truncation point. */ list_for_each_entry(vma, head, shared.nonlinear) { details->nonlinear_vma = vma; unmap_mapping_range_vma(vma, vma->vm_start, vma->vm_end, details); } } /** * unmap_mapping_range - unmap the portion of all mmaps in the specified address_space corresponding to the specified page range in the underlying file. * @mapping: the address space containing mmaps to be unmapped. * @holebegin: byte in first page to unmap, relative to the start of * the underlying file. This will be rounded down to a PAGE_SIZE * boundary. Note that this is different from truncate_pagecache(), which * must keep the partial page. In contrast, we must get rid of * partial pages. * @holelen: size of prospective hole in bytes. This will be rounded * up to a PAGE_SIZE boundary. A holelen of zero truncates to the * end of the file. * @even_cows: 1 when truncating a file, unmap even private COWed pages; * but 0 when invalidating pagecache, don't throw away private data. */ void unmap_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen, int even_cows) { struct zap_details details; pgoff_t hba = holebegin >> PAGE_SHIFT; pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; /* Check for overflow. */ if (sizeof(holelen) > sizeof(hlen)) { long long holeend = (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT; if (holeend & ~(long long)ULONG_MAX) hlen = ULONG_MAX - hba + 1; } details.check_mapping = even_cows? NULL: mapping; details.nonlinear_vma = NULL; details.first_index = hba; details.last_index = hba + hlen - 1; if (details.last_index < details.first_index) details.last_index = ULONG_MAX; mutex_lock(&mapping->i_mmap_mutex); if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap))) unmap_mapping_range_tree(&mapping->i_mmap, &details); if (unlikely(!list_empty(&mapping->i_mmap_nonlinear))) unmap_mapping_range_list(&mapping->i_mmap_nonlinear, &details); mutex_unlock(&mapping->i_mmap_mutex); } EXPORT_SYMBOL(unmap_mapping_range); /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { spinlock_t *ptl; struct page *page, *swapcache; swp_entry_t entry; pte_t pte; int locked; struct mem_cgroup *ptr; int exclusive = 0; int ret = 0; if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) goto out; entry = pte_to_swp_entry(orig_pte); if (unlikely(non_swap_entry(entry))) { if (is_migration_entry(entry)) { migration_entry_wait(mm, pmd, address); } else if (is_hwpoison_entry(entry)) { ret = VM_FAULT_HWPOISON; } else { print_bad_pte(vma, address, orig_pte, NULL); ret = VM_FAULT_SIGBUS; } goto out; } delayacct_set_flag(DELAYACCT_PF_SWAPIN); page = lookup_swap_cache(entry); if (!page) { page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vma, address); if (!page) { /* * Back out if somebody else faulted in this pte * while we released the pte lock. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (likely(pte_same(*page_table, orig_pte))) ret = VM_FAULT_OOM; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); goto unlock; } /* Had to read the page from swap area: Major fault */ ret = VM_FAULT_MAJOR; count_vm_event(PGMAJFAULT); mem_cgroup_count_vm_event(mm, PGMAJFAULT); } else if (PageHWPoison(page)) { /* * hwpoisoned dirty swapcache pages are kept for killing * owner processes (which may be unknown at hwpoison time) */ ret = VM_FAULT_HWPOISON; delayacct_clear_flag(DELAYACCT_PF_SWAPIN); swapcache = page; goto out_release; } swapcache = page; locked = lock_page_or_retry(page, mm, flags); delayacct_clear_flag(DELAYACCT_PF_SWAPIN); if (!locked) { ret |= VM_FAULT_RETRY; goto out_release; } /* * Make sure try_to_free_swap or reuse_swap_page or swapoff did not * release the swapcache from under us. The page pin, and pte_same * test below, are not enough to exclude that. Even if it is still * swapcache, we need to check that the page's swap has not changed. */ if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val)) goto out_page; page = ksm_might_need_to_copy(page, vma, address); if (unlikely(!page)) { ret = VM_FAULT_OOM; page = swapcache; goto out_page; } if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) { ret = VM_FAULT_OOM; goto out_page; } /* * Back out if somebody else already faulted in this pte. */ page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (unlikely(!pte_same(*page_table, orig_pte))) goto out_nomap; if (unlikely(!PageUptodate(page))) { ret = VM_FAULT_SIGBUS; goto out_nomap; } /* * The page isn't present yet, go ahead with the fault. * * Be careful about the sequence of operations here. * To get its accounting right, reuse_swap_page() must be called * while the page is counted on swap but not yet in mapcount i.e. * before page_add_anon_rmap() and swap_free(); try_to_free_swap() * must be called after the swap_free(), or it will never succeed. * Because delete_from_swap_page() may be called by reuse_swap_page(), * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry * in page->private. In this case, a record in swap_cgroup is silently * discarded at swap_free(). */ inc_mm_counter_fast(mm, MM_ANONPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) inc_mm_counter_fast(mm, MM_LOW_ANONPAGES); #endif dec_mm_counter_fast(mm, MM_SWAPENTS); pte = mk_pte(page, vma->vm_page_prot); if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) { pte = maybe_mkwrite(pte_mkdirty(pte), vma); flags &= ~FAULT_FLAG_WRITE; ret |= VM_FAULT_WRITE; exclusive = 1; } flush_icache_page(vma, page); set_pte_at(mm, address, page_table, pte); if (page == swapcache) do_page_add_anon_rmap(page, vma, address, exclusive); else /* ksm created a completely new copy */ page_add_new_anon_rmap(page, vma, address); /* It's better to call commit-charge after rmap is established */ mem_cgroup_commit_charge_swapin(page, ptr); swap_free(entry); if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page)) try_to_free_swap(page); unlock_page(page); if (page != swapcache) { /* * Hold the lock to avoid the swap entry to be reused * until we take the PT lock for the pte_same() check * (to avoid false positives from pte_same). For * further safety release the lock after the swap_free * so that the swap count won't change under a * parallel locked swapcache. */ unlock_page(swapcache); page_cache_release(swapcache); } if (flags & FAULT_FLAG_WRITE) { ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte); if (ret & VM_FAULT_ERROR) ret &= VM_FAULT_ERROR; goto out; } /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); out: return ret; out_nomap: mem_cgroup_cancel_charge_swapin(ptr); pte_unmap_unlock(page_table, ptl); out_page: unlock_page(page); out_release: page_cache_release(page); if (page != swapcache) { unlock_page(swapcache); page_cache_release(swapcache); } return ret; } /* * This is like a special single-page "expand_{down|up}wards()", * except we must first make sure that 'address{-|+}PAGE_SIZE' * doesn't hit another vma. */ static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address) { address &= PAGE_MASK; if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) { struct vm_area_struct *prev = vma->vm_prev; /* * Is there a mapping abutting this one below? * * That's only ok if it's the same stack mapping * that has gotten split.. */ if (prev && prev->vm_end == address) return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM; return expand_downwards(vma, address - PAGE_SIZE); } if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) { struct vm_area_struct *next = vma->vm_next; /* As VM_GROWSDOWN but s/below/above/ */ if (next && next->vm_start == address + PAGE_SIZE) return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM; return expand_upwards(vma, address + PAGE_SIZE); } return 0; } /* * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* File mapping without ->vm_ops ? */ if (vma->vm_flags & VM_SHARED) return VM_FAULT_SIGBUS; /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGSEGV; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; /* * The memory barrier inside __SetPageUptodate makes sure that * preceeding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL)) goto oom_free_page; entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) inc_mm_counter_fast(mm, MM_LOW_ANONPAGES); #endif page_add_new_anon_rmap(page, vma, address); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_uncharge_page(page); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; } /* * __do_fault() tries to create a new page mapping. It aggressively * tries to share with existing pages, but makes a separate copy if * the FAULT_FLAG_WRITE is set in the flags parameter in order to avoid * the next page fault. * * As this is called only for pages that do not currently exist, we * do not need to flush old virtual caches or the TLB. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte neither mapped nor locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int __do_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, pgoff_t pgoff, unsigned int flags, pte_t orig_pte) { pte_t *page_table; spinlock_t *ptl; struct page *page; struct page *cow_page; pte_t entry; int anon = 0; struct page *dirty_page = NULL; struct vm_fault vmf; int ret; int page_mkwrite = 0; /* * If we do COW later, allocate page befor taking lock_page() * on the file cache page. This will reduce lock holding time. */ if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { if (unlikely(anon_vma_prepare(vma))) return VM_FAULT_OOM; cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (!cow_page) return VM_FAULT_OOM; if (mem_cgroup_newpage_charge(cow_page, mm, GFP_KERNEL)) { page_cache_release(cow_page); return VM_FAULT_OOM; } } else cow_page = NULL; vmf.virtual_address = (void __user *)(address & PAGE_MASK); vmf.pgoff = pgoff; vmf.flags = flags; vmf.page = NULL; ret = vma->vm_ops->fault(vma, &vmf); if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY))) goto uncharge_out; if (unlikely(PageHWPoison(vmf.page))) { if (ret & VM_FAULT_LOCKED) unlock_page(vmf.page); ret = VM_FAULT_HWPOISON; goto uncharge_out; } /* * For consistency in subsequent calls, make the faulted page always * locked. */ if (unlikely(!(ret & VM_FAULT_LOCKED))) lock_page(vmf.page); else VM_BUG_ON(!PageLocked(vmf.page)); /* * Should we do an early C-O-W break? */ page = vmf.page; if (flags & FAULT_FLAG_WRITE) { if (!(vma->vm_flags & VM_SHARED)) { page = cow_page; anon = 1; copy_user_highpage(page, vmf.page, address, vma); __SetPageUptodate(page); } else { /* * If the page will be shareable, see if the backing * address space wants to know that the page is about * to become writable */ if (vma->vm_ops->page_mkwrite) { int tmp; unlock_page(page); vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE; tmp = vma->vm_ops->page_mkwrite(vma, &vmf); if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) { ret = tmp; goto unwritable_page; } if (unlikely(!(tmp & VM_FAULT_LOCKED))) { lock_page(page); if (!page->mapping) { ret = 0; /* retry the fault */ unlock_page(page); goto unwritable_page; } } else VM_BUG_ON(!PageLocked(page)); page_mkwrite = 1; } } } page_table = pte_offset_map_lock(mm, pmd, address, &ptl); /* * This silly early PAGE_DIRTY setting removes a race * due to the bad i386 page protection. But it's valid * for other architectures too. * * Note that if FAULT_FLAG_WRITE is set, we either now have * an exclusive copy of the page, or this is a shared mapping, * so we can make it writable and dirty to avoid having to * handle that later. */ /* Only go through if we didn't race with anybody else... */ if (likely(pte_same(*page_table, orig_pte))) { flush_icache_page(vma, page); entry = mk_pte(page, vma->vm_page_prot); if (flags & FAULT_FLAG_WRITE) entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (anon) { inc_mm_counter_fast(mm, MM_ANONPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) inc_mm_counter_fast(mm, MM_LOW_ANONPAGES); #endif page_add_new_anon_rmap(page, vma, address); } else { inc_mm_counter_fast(mm, MM_FILEPAGES); #ifdef CONFIG_ZOOM_KILLER if (!PageHighMem(page)) inc_mm_counter_fast(mm, MM_LOW_FILEPAGES); #endif page_add_file_rmap(page); if (flags & FAULT_FLAG_WRITE) { dirty_page = page; get_page(dirty_page); } } set_pte_at(mm, address, page_table, entry); /* no need to invalidate: a not-present page won't be cached */ update_mmu_cache(vma, address, page_table); } else { if (cow_page) mem_cgroup_uncharge_page(cow_page); if (anon) page_cache_release(page); else anon = 1; /* no anon but release faulted_page */ } pte_unmap_unlock(page_table, ptl); if (dirty_page) { struct address_space *mapping = page->mapping; int dirtied = 0; if (set_page_dirty(dirty_page)) dirtied = 1; unlock_page(dirty_page); put_page(dirty_page); if ((dirtied || page_mkwrite) && mapping) { /* * Some device drivers do not set page.mapping but still * dirty their pages */ balance_dirty_pages_ratelimited(mapping); } /* file_update_time outside page_lock */ if (vma->vm_file && !page_mkwrite) file_update_time(vma->vm_file); } else { unlock_page(vmf.page); if (anon) page_cache_release(vmf.page); } return ret; unwritable_page: page_cache_release(page); return ret; uncharge_out: /* fs's fault handler get error */ if (cow_page) { mem_cgroup_uncharge_page(cow_page); page_cache_release(cow_page); } return ret; } static int do_linear_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff = (((address & PAGE_MASK) - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; pte_unmap(page_table); /* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */ if (!vma->vm_ops->fault) return VM_FAULT_SIGBUS; return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); } /* * Fault of a previously existing named mapping. Repopulate the pte * from the encoded file_pte if possible. This enables swappable * nonlinear vmas. * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ static int do_nonlinear_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff; flags |= FAULT_FLAG_NONLINEAR; if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) return 0; if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) { /* * Page table corrupted: show pte and kill process. */ print_bad_pte(vma, address, orig_pte, NULL); return VM_FAULT_SIGBUS; } pgoff = pte_to_pgoff(orig_pte); return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); } int numa_migrate_prep(struct page *page, struct vm_area_struct *vma, unsigned long addr, int page_nid) { get_page(page); count_vm_numa_event(NUMA_HINT_FAULTS); if (page_nid == numa_node_id()) count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL); return mpol_misplaced(page, vma, addr); } int do_numa_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, pte_t pte, pte_t *ptep, pmd_t *pmd) { struct page *page = NULL; spinlock_t *ptl; int page_nid = -1; int target_nid; bool migrated = false; /* * The "pte" at this point cannot be used safely without * validation through pte_unmap_same(). It's of NUMA type but * the pfn may be screwed if the read is non atomic. * * ptep_modify_prot_start is not called as this is clearing * the _PAGE_NUMA bit and it is not really expected that there * would be concurrent hardware modifications to the PTE. */ ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*ptep, pte))) { pte_unmap_unlock(ptep, ptl); goto out; } pte = pte_mknonnuma(pte); set_pte_at(mm, addr, ptep, pte); update_mmu_cache(vma, addr, ptep); page = vm_normal_page(vma, addr, pte); if (!page) { pte_unmap_unlock(ptep, ptl); return 0; } page_nid = page_to_nid(page); target_nid = numa_migrate_prep(page, vma, addr, page_nid); pte_unmap_unlock(ptep, ptl); if (target_nid == -1) { put_page(page); goto out; } /* Migrate to the requested node */ migrated = migrate_misplaced_page(page, target_nid); if (migrated) page_nid = target_nid; out: if (page_nid != -1) task_numa_fault(page_nid, 1, migrated); return 0; } /* NUMA hinting page fault entry point for regular pmds */ #ifdef CONFIG_NUMA_BALANCING static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, pmd_t *pmdp) { pmd_t pmd; pte_t *pte, *orig_pte; unsigned long _addr = addr & PMD_MASK; unsigned long offset; spinlock_t *ptl; bool numa = false; spin_lock(&mm->page_table_lock); pmd = *pmdp; if (pmd_numa(pmd)) { set_pmd_at(mm, _addr, pmdp, pmd_mknonnuma(pmd)); numa = true; } spin_unlock(&mm->page_table_lock); if (!numa) return 0; /* we're in a page fault so some vma must be in the range */ BUG_ON(!vma); BUG_ON(vma->vm_start >= _addr + PMD_SIZE); offset = max(_addr, vma->vm_start) & ~PMD_MASK; VM_BUG_ON(offset >= PMD_SIZE); orig_pte = pte = pte_offset_map_lock(mm, pmdp, _addr, &ptl); pte += offset >> PAGE_SHIFT; for (addr = _addr + offset; addr < _addr + PMD_SIZE; pte++, addr += PAGE_SIZE) { pte_t pteval = *pte; struct page *page; int page_nid = -1; int target_nid; bool migrated = false; if (!pte_present(pteval)) continue; if (!pte_numa(pteval)) continue; if (addr >= vma->vm_end) { vma = find_vma(mm, addr); /* there's a pte present so there must be a vma */ BUG_ON(!vma); BUG_ON(addr < vma->vm_start); } if (pte_numa(pteval)) { pteval = pte_mknonnuma(pteval); set_pte_at(mm, addr, pte, pteval); } page = vm_normal_page(vma, addr, pteval); if (unlikely(!page)) continue; /* only check non-shared pages */ if (unlikely(page_mapcount(page) != 1)) continue; page_nid = page_to_nid(page); target_nid = numa_migrate_prep(page, vma, addr, page_nid); pte_unmap_unlock(pte, ptl); if (target_nid != -1) { migrated = migrate_misplaced_page(page, target_nid); if (migrated) page_nid = target_nid; } else { put_page(page); } if (page_nid != -1) task_numa_fault(page_nid, 1, migrated); pte = pte_offset_map_lock(mm, pmdp, addr, &ptl); } pte_unmap_unlock(orig_pte, ptl); return 0; } #else static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long addr, pmd_t *pmdp) { BUG(); return 0; } #endif /* CONFIG_NUMA_BALANCING */ /* * These routines also need to handle stuff like marking pages dirty * and/or accessed for architectures that don't do it in hardware (most * RISC architectures). The early dirtying is also good on the i386. * * There is also a hook called "update_mmu_cache()" that architectures * with external mmu caches can use to update those (ie the Sparc or * PowerPC hashed page tables that act as extended TLBs). * * We enter with non-exclusive mmap_sem (to exclude vma changes, * but allow concurrent faults), and pte mapped but not yet locked. * We return with mmap_sem still held, but pte unmapped and unlocked. */ int handle_pte_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *pte, pmd_t *pmd, unsigned int flags) { pte_t entry; spinlock_t *ptl; entry = *pte; if (!pte_present(entry)) { if (pte_none(entry)) { if (vma->vm_ops) return do_linear_fault(mm, vma, address, pte, pmd, flags, entry); return do_anonymous_page(mm, vma, address, pte, pmd, flags); } if (pte_file(entry)) return do_nonlinear_fault(mm, vma, address, pte, pmd, flags, entry); return do_swap_page(mm, vma, address, pte, pmd, flags, entry); } if (pte_numa(entry)) return do_numa_page(mm, vma, address, entry, pte, pmd); ptl = pte_lockptr(mm, pmd); spin_lock(ptl); if (unlikely(!pte_same(*pte, entry))) goto unlock; if (flags & FAULT_FLAG_WRITE) { if (!pte_write(entry)) return do_wp_page(mm, vma, address, pte, pmd, ptl, entry); entry = pte_mkdirty(entry); } entry = pte_mkyoung(entry); if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) { update_mmu_cache(vma, address, pte); } else { /* * This is needed only for protection faults but the arch code * is not yet telling us if this is a protection fault or not. * This still avoids useless tlb flushes for .text page faults * with threads. */ if (flags & FAULT_FLAG_WRITE) flush_tlb_fix_spurious_fault(vma, address); } unlock: pte_unmap_unlock(pte, ptl); return 0; } /* * By the time we get here, we already hold the mm semaphore */ static int __handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (unlikely(is_vm_hugetlb_page(vma))) return hugetlb_fault(mm, vma, address, flags); retry: pgd = pgd_offset(mm, address); pud = pud_alloc(mm, pgd, address); if (!pud) return VM_FAULT_OOM; pmd = pmd_alloc(mm, pud, address); if (!pmd) return VM_FAULT_OOM; if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) { if (!vma->vm_ops) return do_huge_pmd_anonymous_page(mm, vma, address, pmd, flags); } else { pmd_t orig_pmd = *pmd; int ret; barrier(); if (pmd_trans_huge(orig_pmd)) { unsigned int dirty = flags & FAULT_FLAG_WRITE; /* * If the pmd is splitting, return and retry the * the fault. Alternative: wait until the split * is done, and goto retry. */ if (pmd_trans_splitting(orig_pmd)) return 0; if (pmd_numa(orig_pmd)) return do_huge_pmd_numa_page(mm, vma, address, orig_pmd, pmd); if (dirty && !pmd_write(orig_pmd)) { ret = do_huge_pmd_wp_page(mm, vma, address, pmd, orig_pmd); /* * If COW results in an oom, the huge pmd will * have been split, so retry the fault on the * pte for a smaller charge. */ if (unlikely(ret & VM_FAULT_OOM)) goto retry; return ret; } else { huge_pmd_set_accessed(mm, vma, address, pmd, orig_pmd, dirty); } return 0; } } if (pmd_numa(*pmd)) return do_pmd_numa_page(mm, vma, address, pmd); /* * Use __pte_alloc instead of pte_alloc_map, because we can't * run pte_offset_map on the pmd, if an huge pmd could * materialize from under us from a different thread. */ if (unlikely(pmd_none(*pmd)) && unlikely(__pte_alloc(mm, vma, pmd, address))) return VM_FAULT_OOM; /* if an huge pmd materialized from under us just retry later */ if (unlikely(pmd_trans_huge(*pmd))) return 0; /* * A regular pmd is established and it can't morph into a huge pmd * from under us anymore at this point because we hold the mmap_sem * read mode and khugepaged takes it in write mode. So now it's * safe to run pte_offset_map(). */ pte = pte_offset_map(pmd, address); return handle_pte_fault(mm, vma, address, pte, pmd, flags); } int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { int ret; __set_current_state(TASK_RUNNING); count_vm_event(PGFAULT); mem_cgroup_count_vm_event(mm, PGFAULT); /* do counter updates before entering really critical section. */ check_sync_rss_stat(current); /* * Enable the memcg OOM handling for faults triggered in user * space. Kernel faults are handled more gracefully. */ if (flags & FAULT_FLAG_USER) mem_cgroup_oom_enable(); ret = __handle_mm_fault(mm, vma, address, flags); if (flags & FAULT_FLAG_USER) { mem_cgroup_oom_disable(); /* * The task may have entered a memcg OOM situation but * if the allocation error was handled gracefully (no * VM_FAULT_OOM), there is no need to kill anything. * Just clean up the OOM state peacefully. */ if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM)) mem_cgroup_oom_synchronize(false); } return ret; } #ifndef __PAGETABLE_PUD_FOLDED /* * Allocate page upper directory. * We've already handled the fast-path in-line. */ int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { pud_t *new = pud_alloc_one(mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&mm->page_table_lock); if (pgd_present(*pgd)) /* Another has populated it */ pud_free(mm, new); else pgd_populate(mm, pgd, new); spin_unlock(&mm->page_table_lock); return 0; } #endif /* __PAGETABLE_PUD_FOLDED */ #ifndef __PAGETABLE_PMD_FOLDED /* * Allocate page middle directory. * We've already handled the fast-path in-line. */ int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { pmd_t *new = pmd_alloc_one(mm, address); if (!new) return -ENOMEM; smp_wmb(); /* See comment in __pte_alloc */ spin_lock(&mm->page_table_lock); #ifndef __ARCH_HAS_4LEVEL_HACK if (pud_present(*pud)) /* Another has populated it */ pmd_free(mm, new); else pud_populate(mm, pud, new); #else if (pgd_present(*pud)) /* Another has populated it */ pmd_free(mm, new); else pgd_populate(mm, pud, new); #endif /* __ARCH_HAS_4LEVEL_HACK */ spin_unlock(&mm->page_table_lock); return 0; } #endif /* __PAGETABLE_PMD_FOLDED */ #if !defined(__HAVE_ARCH_GATE_AREA) #if defined(AT_SYSINFO_EHDR) static struct vm_area_struct gate_vma; static int __init gate_vma_init(void) { gate_vma.vm_mm = NULL; gate_vma.vm_start = FIXADDR_USER_START; gate_vma.vm_end = FIXADDR_USER_END; gate_vma.vm_flags = VM_READ | VM_MAYREAD | VM_EXEC | VM_MAYEXEC; gate_vma.vm_page_prot = __P101; return 0; } __initcall(gate_vma_init); #endif struct vm_area_struct *get_gate_vma(struct mm_struct *mm) { #ifdef AT_SYSINFO_EHDR return &gate_vma; #else return NULL; #endif } int in_gate_area_no_mm(unsigned long addr) { #ifdef AT_SYSINFO_EHDR if ((addr >= FIXADDR_USER_START) && (addr < FIXADDR_USER_END)) return 1; #endif return 0; } #endif /* __HAVE_ARCH_GATE_AREA */ static int __follow_pte(struct mm_struct *mm, unsigned long address, pte_t **ptepp, spinlock_t **ptlp) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *ptep; pgd = pgd_offset(mm, address); if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) goto out; pud = pud_offset(pgd, address); if (pud_none(*pud) || unlikely(pud_bad(*pud))) goto out; pmd = pmd_offset(pud, address); VM_BUG_ON(pmd_trans_huge(*pmd)); if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd))) goto out; /* We cannot handle huge page PFN maps. Luckily they don't exist. */ if (pmd_huge(*pmd)) goto out; ptep = pte_offset_map_lock(mm, pmd, address, ptlp); if (!ptep) goto out; if (!pte_present(*ptep)) goto unlock; *ptepp = ptep; return 0; unlock: pte_unmap_unlock(ptep, *ptlp); out: return -EINVAL; } static inline int follow_pte(struct mm_struct *mm, unsigned long address, pte_t **ptepp, spinlock_t **ptlp) { int res; /* (void) is needed to make gcc happy */ (void) __cond_lock(*ptlp, !(res = __follow_pte(mm, address, ptepp, ptlp))); return res; } /** * follow_pfn - look up PFN at a user virtual address * @vma: memory mapping * @address: user virtual address * @pfn: location to store found PFN * * Only IO mappings and raw PFN mappings are allowed. * * Returns zero and the pfn at @pfn on success, -ve otherwise. */ int follow_pfn(struct vm_area_struct *vma, unsigned long address, unsigned long *pfn) { int ret = -EINVAL; spinlock_t *ptl; pte_t *ptep; if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) return ret; ret = follow_pte(vma->vm_mm, address, &ptep, &ptl); if (ret) return ret; *pfn = pte_pfn(*ptep); pte_unmap_unlock(ptep, ptl); return 0; } EXPORT_SYMBOL(follow_pfn); #ifdef CONFIG_HAVE_IOREMAP_PROT int follow_phys(struct vm_area_struct *vma, unsigned long address, unsigned int flags, unsigned long *prot, resource_size_t *phys) { int ret = -EINVAL; pte_t *ptep, pte; spinlock_t *ptl; if (!(vma->vm_flags & (VM_IO | VM_PFNMAP))) goto out; if (follow_pte(vma->vm_mm, address, &ptep, &ptl)) goto out; pte = *ptep; if ((flags & FOLL_WRITE) && !pte_write(pte)) goto unlock; *prot = pgprot_val(pte_pgprot(pte)); *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT; ret = 0; unlock: pte_unmap_unlock(ptep, ptl); out: return ret; } int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write) { resource_size_t phys_addr; unsigned long prot = 0; void __iomem *maddr; int offset = addr & (PAGE_SIZE-1); if (follow_phys(vma, addr, write, &prot, &phys_addr)) return -EINVAL; maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot); if (write) memcpy_toio(maddr + offset, buf, len); else memcpy_fromio(buf, maddr + offset, len); iounmap(maddr); return len; } EXPORT_SYMBOL_GPL(generic_access_phys); #endif /* * Access another process' address space as given in mm. If non-NULL, use the * given task for page fault accounting. */ static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm, unsigned long addr, void *buf, int len, int write) { struct vm_area_struct *vma; void *old_buf = buf; down_read(&mm->mmap_sem); /* ignore errors, just check how much was successfully transferred */ while (len) { int bytes, ret, offset; void *maddr; struct page *page = NULL; ret = get_user_pages(tsk, mm, addr, 1, write, 1, &page, &vma); if (ret <= 0) { /* * Check if this is a VM_IO | VM_PFNMAP VMA, which * we can access using slightly different code. */ #ifdef CONFIG_HAVE_IOREMAP_PROT vma = find_vma(mm, addr); if (!vma || vma->vm_start > addr) break; if (vma->vm_ops && vma->vm_ops->access) ret = vma->vm_ops->access(vma, addr, buf, len, write); if (ret <= 0) #endif break; bytes = ret; } else { bytes = len; offset = addr & (PAGE_SIZE-1); if (bytes > PAGE_SIZE-offset) bytes = PAGE_SIZE-offset; maddr = kmap(page); if (write) { copy_to_user_page(vma, page, addr, maddr + offset, buf, bytes); set_page_dirty_lock(page); } else { copy_from_user_page(vma, page, addr, buf, maddr + offset, bytes); } kunmap(page); page_cache_release(page); } len -= bytes; buf += bytes; addr += bytes; } up_read(&mm->mmap_sem); return buf - old_buf; } /** * access_remote_vm - access another process' address space * @mm: the mm_struct of the target address space * @addr: start address to access * @buf: source or destination buffer * @len: number of bytes to transfer * @write: whether the access is a write * * The caller must hold a reference on @mm. */ int access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf, int len, int write) { return __access_remote_vm(NULL, mm, addr, buf, len, write); } /* * Access another process' address space. * Source/target buffer must be kernel space, * Do not walk the page table directly, use get_user_pages */ int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write) { struct mm_struct *mm; int ret; mm = get_task_mm(tsk); if (!mm) return 0; ret = __access_remote_vm(tsk, mm, addr, buf, len, write); mmput(mm); return ret; } /* * Print the name of a VMA. */ void print_vma_addr(char *prefix, unsigned long ip) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; /* * Do not print if we are in atomic * contexts (in exception stacks, etc.): */ if (preempt_count()) return; down_read(&mm->mmap_sem); vma = find_vma(mm, ip); if (vma && vma->vm_file) { struct file *f = vma->vm_file; char *buf = (char *)__get_free_page(GFP_KERNEL); if (buf) { char *p; p = d_path(&f->f_path, buf, PAGE_SIZE); if (IS_ERR(p)) p = "?"; printk("%s%s[%lx+%lx]", prefix, kbasename(p), vma->vm_start, vma->vm_end - vma->vm_start); free_page((unsigned long)buf); } } up_read(&mm->mmap_sem); } #ifdef CONFIG_PROVE_LOCKING void might_fault(void) { /* * Some code (nfs/sunrpc) uses socket ops on kernel memory while * holding the mmap_sem, this is safe because kernel memory doesn't * get paged out, therefore we'll never actually fault, and the * below annotations will generate false positives. */ if (segment_eq(get_fs(), KERNEL_DS)) return; might_sleep(); /* * it would be nicer only to annotate paths which are not under * pagefault_disable, however that requires a larger audit and * providing helpers like get_user_atomic. */ if (!in_atomic() && current->mm) might_lock_read(&current->mm->mmap_sem); } EXPORT_SYMBOL(might_fault); #endif #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) static void clear_gigantic_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page) { int i; struct page *p = page; might_sleep(); for (i = 0; i < pages_per_huge_page; i++, p = mem_map_next(p, page, i)) { cond_resched(); clear_user_highpage(p, addr + i * PAGE_SIZE); } } void clear_huge_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page) { int i; if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { clear_gigantic_page(page, addr, pages_per_huge_page); return; } might_sleep(); for (i = 0; i < pages_per_huge_page; i++) { cond_resched(); clear_user_highpage(page + i, addr + i * PAGE_SIZE); } } static void copy_user_gigantic_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < pages_per_huge_page; ) { cond_resched(); copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } void copy_user_huge_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page) { int i; if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) { copy_user_gigantic_page(dst, src, addr, vma, pages_per_huge_page); return; } might_sleep(); for (i = 0; i < pages_per_huge_page; i++) { cond_resched(); copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma); } } #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
myjang0507/slte
mm/memory.c
C
gpl-2.0
122,319
[ 30522, 1013, 1008, 1008, 11603, 1013, 3461, 1013, 3638, 1012, 1039, 1008, 1008, 9385, 1006, 1039, 1007, 2889, 1010, 2826, 1010, 2857, 1010, 2807, 11409, 2271, 17153, 10175, 5104, 1008, 1013, 1013, 1008, 1008, 5157, 1011, 10578, 2318, 5890, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import React from 'react'; import { createStore } from 'redux'; import { createBrowserHistory } from 'history'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import rootReducer from '../../src/reducers'; import Routes from '../../src/Routes'; import App from '../../src/containers/App'; const configureStore = initialState => createStore( rootReducer, initialState, ); describe('Container | App', () => { it('renders Routes component', () => { const wrapper = shallow(<App history={createBrowserHistory()} store={configureStore()}/>); expect(wrapper.find(Routes)).to.have.lengthOf(1); }); });
elemus/react-redux-todo-example
test/containers/App.spec.js
JavaScript
mit
652
[ 30522, 12324, 10509, 2013, 1005, 10509, 1005, 1025, 12324, 1063, 9005, 19277, 1065, 2013, 1005, 2417, 5602, 1005, 1025, 12324, 1063, 3443, 12618, 9333, 2121, 24158, 7062, 1065, 2013, 1005, 2381, 1005, 1025, 12324, 1063, 5987, 1065, 2013, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * @name शेक बॉल बाउंस * @description एक बॉल क्लास बनाएं, कई ऑब्जेक्ट्स को इंस्टेंट करें, इसे स्क्रीन के चारों ओर घुमाएं, और कैनवास के किनारे को छूने पर बाउंस करें। * त्वरणX और त्वरण में कुल परिवर्तन के आधार पर शेक घटना का पता लगाएं और पता लगाने के आधार पर वस्तुओं को गति दें या धीमा करें। */ let balls = []; let threshold = 30; let accChangeX = 0; let accChangeY = 0; let accChangeT = 0; function setup() { createCanvas(displayWidth, displayHeight); for (let i = 0; i < 20; i++) { balls.push(new Ball()); } } function draw() { background(0); for (let i = 0; i < balls.length; i++) { balls[i].move(); balls[i].display(); } checkForShake(); } function checkForShake() { // Calculate total change in accelerationX and accelerationY accChangeX = abs(accelerationX - pAccelerationX); accChangeY = abs(accelerationY - pAccelerationY); accChangeT = accChangeX + accChangeY; // If shake if (accChangeT >= threshold) { for (let i = 0; i < balls.length; i++) { balls[i].shake(); balls[i].turn(); } } // If not shake else { for (let i = 0; i < balls.length; i++) { balls[i].stopShake(); balls[i].turn(); balls[i].move(); } } } // Ball class class Ball { constructor() { this.x = random(width); this.y = random(height); this.diameter = random(10, 30); this.xspeed = random(-2, 2); this.yspeed = random(-2, 2); this.oxspeed = this.xspeed; this.oyspeed = this.yspeed; this.direction = 0.7; } move() { this.x += this.xspeed * this.direction; this.y += this.yspeed * this.direction; } // Bounce when touch the edge of the canvas turn() { if (this.x < 0) { this.x = 0; this.direction = -this.direction; } else if (this.y < 0) { this.y = 0; this.direction = -this.direction; } else if (this.x > width - 20) { this.x = width - 20; this.direction = -this.direction; } else if (this.y > height - 20) { this.y = height - 20; this.direction = -this.direction; } } // Add to xspeed and yspeed based on // the change in accelerationX value shake() { this.xspeed += random(5, accChangeX / 3); this.yspeed += random(5, accChangeX / 3); } // Gradually slows down stopShake() { if (this.xspeed > this.oxspeed) { this.xspeed -= 0.6; } else { this.xspeed = this.oxspeed; } if (this.yspeed > this.oyspeed) { this.yspeed -= 0.6; } else { this.yspeed = this.oyspeed; } } display() { ellipse(this.x, this.y, this.diameter, this.diameter); } }
processing/p5.js-website
src/data/examples/hi/35_Mobile/03_Shake_Ball_Bounce.js
JavaScript
mit
3,037
[ 30522, 1013, 1008, 1008, 1030, 2171, 1336, 29851, 100, 1329, 29876, 29849, 29874, 1008, 1030, 6412, 1314, 29851, 100, 1315, 29870, 29876, 29874, 1329, 29863, 29876, 29850, 1010, 100, 100, 1315, 29879, 100, 1315, 29869, 1010, 100, 1338, 2985...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.reasm.m68k.assembly.internal; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import org.reasm.Value; import org.reasm.ValueToBooleanVisitor; /** * The <code>WHILE</code> directive. * * @author Francis Gagné */ @Immutable class WhileDirective extends Mnemonic { @Nonnull static final WhileDirective WHILE = new WhileDirective(); private WhileDirective() { } @Override void assemble(M68KAssemblyContext context) { context.sizeNotAllowed(); final Object blockState = context.getParentBlock(); if (!(blockState instanceof WhileBlockState)) { throw new AssertionError(); } final WhileBlockState whileBlockState = (WhileBlockState) blockState; // The WHILE directive is assembled on every iteration. // Parse the condition operand on the first iteration only. if (!whileBlockState.parsedCondition) { if (context.requireNumberOfOperands(1)) { whileBlockState.conditionExpression = parseExpressionOperand(context, 0); } whileBlockState.parsedCondition = true; } final Value condition; if (whileBlockState.conditionExpression != null) { condition = whileBlockState.conditionExpression.evaluate(context.getEvaluationContext()); } else { condition = null; } final Boolean result = Value.accept(condition, ValueToBooleanVisitor.INSTANCE); if (!(result != null && result.booleanValue())) { // Skip the block body and stop the iteration. whileBlockState.iterator.next(); whileBlockState.hasNextIteration = false; } } }
reasm/reasm-m68k
src/main/java/org/reasm/m68k/assembly/internal/WhileDirective.java
Java
mit
1,747
[ 30522, 7427, 8917, 1012, 2128, 3022, 2213, 1012, 1049, 2575, 2620, 2243, 1012, 3320, 1012, 4722, 1025, 12324, 9262, 2595, 1012, 5754, 17287, 3508, 1012, 2512, 11231, 3363, 1025, 12324, 9262, 2595, 1012, 5754, 17287, 3508, 1012, 16483, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*GENERAL*/ html { zoom: 0.8; -webkit-print-color-adjust: exact; } body { font-family: "Source Sans Pro", Arial, Helvetica, sans-serif; font-weight: 400; font-size: 14px; } h1,h2,h3 { font-weight: 300; margin: 0.3em 0; } h4,h5 { font-weight: 400; margin: 0.5em 0; } h5 { font-size: 1.2em; } h1 { font-size: 2.4em; } h2 { font-size: 1.9em; } .center { text-align: center; } .right { text-align: right; } .container.heading { margin: 2em auto; } .container.heading { color: #555; } .container.heading h5 { color: #000; } /*CONTACT INFO SECTION*/ .contact .title { text-transform: uppercase; font-size: 1.3em; letter-spacing: 0.2em; } .contact .info .heading { color: black; display: block; font-size: 1.1em; } .contact .info { color: #555; font-size: 1em; } .contact h2 { margin-bottom: 20px; } /*INVOICE SECTION*/ .invoice .title h2 { margin: 60px 0 30px 0; } .invoice .item { font-weight: 400; padding: 0.4em 0; color: #555; } .invoice hr:last-of-type { border-top: 2px solid #1abc9c; } .invoice .total p { font-weight: 400; text-transform: uppercase; font-size: 1.1em; margin: 0; } .invoice .total strong { font-weight: 300; font-size: 2em; } .invoice .total time{ font-weight: 400; } /*PAYMENT SECTION*/ .container.payment { margin-top: 20px; } .container.payment .title { font-size: 1.4em; } .payment hr { border-top: 2px solid #1abc9c; } .payment h4 { font-size: 1.2em; } .payment p { font-size: 1.1em; margin: 0; color: #555; }
timojarv/genvoice
templates/invoice.css
CSS
mit
1,505
[ 30522, 1013, 1008, 2236, 1008, 1013, 16129, 1063, 24095, 1024, 1014, 1012, 1022, 1025, 1011, 4773, 23615, 1011, 6140, 1011, 3609, 1011, 14171, 1024, 6635, 1025, 1065, 2303, 1063, 15489, 1011, 2155, 1024, 1000, 3120, 20344, 4013, 1000, 1010,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# IBackgroundTask`1 _namespace: [Microsoft.VisualBasic.Parallel.Tasks](./index.md)_ 背景线程的任务抽象
amethyst-asuka/GCModeller
src/runtime/sciBASIC#/docs/sdk/Microsoft.VisualBasic.Parallel.Tasks/IBackgroundTask`1.md
Markdown
gpl-3.0
120
[ 30522, 1001, 21307, 8684, 16365, 10230, 2243, 1036, 1015, 1035, 3415, 15327, 1024, 1031, 7513, 1012, 5107, 22083, 2594, 1012, 5903, 1012, 8518, 1033, 1006, 1012, 1013, 5950, 1012, 9108, 1007, 1035, 100, 100, 100, 100, 1916, 100, 100, 100,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.freedom.modulos.fnc.business.component.cnab; import org.freedom.infra.functions.StringFunctions; import org.freedom.library.business.component.Banco; import org.freedom.library.business.exceptions.ExceptionCnab; import org.freedom.modulos.fnc.library.business.compoent.FbnUtil.ETipo; public class RegTrailer extends Reg { private String codBanco; private String loteServico; private String registroTrailer; private String conta; private int qtdLotes; private int qtdRegistros; private int qtdConsilacoes; private int seqregistro; public RegTrailer() { setLoteServico( "9999" ); setRegistroTrailer( "9" ); } public int getSeqregistro() { return seqregistro; } public void setSeqregistro( int seqregistro ) { this.seqregistro = seqregistro; } public String getCodBanco() { return codBanco; } public void setCodBanco( final String codBanco ) { this.codBanco = codBanco; } public String getLoteServico() { return loteServico; } private void setLoteServico( final String loteServico ) { this.loteServico = loteServico; } public int getQtdConsilacoes() { return qtdConsilacoes; } public void setQtdConsilacoes( final int qtdConsilacoes ) { this.qtdConsilacoes = qtdConsilacoes; } public int getQtdLotes() { return qtdLotes; } public void setQtdLotes( final int qtdLotes ) { this.qtdLotes = qtdLotes; } public int getQtdRegistros() { return qtdRegistros; } public void setQtdRegistros( final int qtdRegistros ) { this.qtdRegistros = qtdRegistros; } public String getRegistroTrailer() { return registroTrailer; } private void setRegistroTrailer( final String regTrailer ) { this.registroTrailer = regTrailer; } public String getConta() { return conta; } public void setConta( String codConta ) { this.conta = codConta; } @ Override public String getLine( String padraocnab ) throws ExceptionCnab { StringBuilder line = new StringBuilder(); try { if ( padraocnab.equals( CNAB_240 ) ) { line.append( format( getCodBanco(), ETipo.$9, 3, 0 ) ); line.append( format( getLoteServico(), ETipo.$9, 4, 0 ) ); line.append( format( getRegistroTrailer(), ETipo.$9, 1, 0 ) ); line.append( StringFunctions.replicate( " ", 9 ) ); line.append( format( getQtdLotes(), ETipo.$9, 6, 0 ) ); line.append( format( getQtdRegistros(), ETipo.$9, 6, 0 ) ); line.append( format( getQtdConsilacoes(), ETipo.$9, 6, 0 ) ); line.append( StringFunctions.replicate( " ", 205 ) ); } else if ( padraocnab.equals( CNAB_400 ) ) { line.append( StringFunctions.replicate( "9", 1 ) ); // Posição 001 a 001 - Identificação do registro if( getCodBanco().equals( Banco.SICRED )){ line.append( "1" ); line.append( getCodBanco() ); line.append( format( getConta(), ETipo.$9, 5, 0 ) ); line.append( StringFunctions.replicate( " ", 384 ) ); } else { line.append( StringFunctions.replicate( " ", 393 ) ); // Posição 002 a 394 - Branco } line.append( format( seqregistro, ETipo.$9, 6, 0 ) ); // Posição 395 a 400 - Nro Sequancial do ultimo registro } } catch ( Exception e ) { throw new ExceptionCnab( "CNAB registro trailer.\nErro ao escrever registro.\n" + e.getMessage() ); } line.append( (char) 13 ); line.append( (char) 10 ); return line.toString(); } /* * (non-Javadoc) * * @see org.freedom.modulos.fnc.CnabUtil.Reg#parseLine(java.lang.String) */ @ Override public void parseLine( String line ) throws ExceptionCnab { try { if ( line == null ) { throw new ExceptionCnab( "Linha nula." ); } else { setCodBanco( line.substring( 0, 3 ) ); setLoteServico( line.substring( 3, 7 ) ); setRegistroTrailer( line.substring( 7, 8 ) ); setQtdRegistros( line.substring( 17, 23 ).trim().length() > 0 ? Integer.parseInt( line.substring( 17, 23 ).trim() ) : 0 ); setQtdLotes( line.substring( 23, 29 ).trim().length() > 0 ? Integer.parseInt( line.substring( 23, 29 ).trim() ) : 0 ); setQtdRegistros( line.substring( 29, 35 ).trim().length() > 0 ? Integer.parseInt( line.substring( 29, 35 ).trim() ) : 0 ); } } catch ( Exception e ) { throw new ExceptionCnab( "CNAB registro trailer.\nErro ao ler registro.\n" + e.getMessage() ); } } }
cams7/erp
freedom/src/main/java/org/freedom/modulos/fnc/business/component/cnab/RegTrailer.java
Java
gpl-3.0
4,314
[ 30522, 7427, 8917, 1012, 4071, 1012, 16913, 18845, 2015, 1012, 1042, 12273, 1012, 2449, 1012, 6922, 1012, 27166, 7875, 1025, 12324, 8917, 1012, 4071, 1012, 1999, 27843, 1012, 4972, 1012, 5164, 11263, 27989, 2015, 1025, 12324, 8917, 1012, 40...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.datavaultplatform.worker.tasks; import java.io.File; import java.lang.reflect.Constructor; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.datavaultplatform.common.event.Error; import org.datavaultplatform.common.event.InitStates; import org.datavaultplatform.common.event.UpdateProgress; import org.datavaultplatform.common.event.delete.DeleteComplete; import org.datavaultplatform.common.event.delete.DeleteStart; import org.datavaultplatform.common.io.Progress; import org.datavaultplatform.common.storage.ArchiveStore; import org.datavaultplatform.common.storage.Device; import org.datavaultplatform.common.task.Context; import org.datavaultplatform.common.task.Task; import org.datavaultplatform.worker.operations.FileSplitter; import org.datavaultplatform.worker.operations.ProgressTracker; import org.datavaultplatform.worker.queue.EventSender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Delete extends Task{ private static final Logger logger = LoggerFactory.getLogger(Delete.class); private String archiveId = null; private String userID = null; private int numOfChunks = 0; private String depositId = null; private String bagID = null; private long archiveSize = 0; private EventSender eventStream = null; // Maps the model ArchiveStore Id to the storage equivalent HashMap<String, ArchiveStore> archiveStores = new HashMap<>(); @Override public void performAction(Context context) { this.eventStream = (EventSender)context.getEventStream(); logger.info("Delete job - performAction()"); Map<String, String> properties = getProperties(); this.depositId = properties.get("depositId"); this.bagID = properties.get("bagId"); this.userID = properties.get("userId"); this.numOfChunks = Integer.parseInt(properties.get("numOfChunks")); this.archiveSize = Long.parseLong(properties.get("archiveSize")); if (this.isRedeliver()) { eventStream.send(new Error(this.jobID, this.depositId, "Delete stopped: the message had been redelivered, please investigate") .withUserId(this.userID)); return; } this.initStates(); logger.info("bagID: " + this.bagID); //userStores = this.setupUserFileStores(); this.setupArchiveFileStores(); try { String tarFileName = this.bagID + ".tar"; Path tarPath = context.getTempDir().resolve(tarFileName); File tarFile = tarPath.toFile(); eventStream.send(new DeleteStart(this.jobID, this.depositId).withNextState(0) .withUserId(this.userID)); eventStream.send(new UpdateProgress(this.jobID, this.depositId, 0, this.archiveSize, "Deposit delete started ...") .withUserId(this.userID)); for (String archiveStoreId : archiveStores.keySet() ) { ArchiveStore archiveStore = archiveStores.get(archiveStoreId); this.archiveId = properties.get(archiveStoreId); logger.info("archiveId: " + this.archiveId); Device archiveFs = ((Device)archiveStore); if(archiveFs.hasMultipleCopies()) { deleteMultipleCopiesFromArchiveStorage(context, archiveFs, tarFileName, tarFile); } else { deleteFromArchiveStorage(context, archiveFs, tarFileName, tarFile); } } eventStream.send(new DeleteComplete(this.jobID, this.depositId).withNextState(1) .withUserId(this.userID)); } catch (Exception e) { String msg = "Deposit delete failed: " + e.getMessage(); logger.error(msg, e); eventStream.send(new Error(jobID, depositId, msg) .withUserId(userID)); throw new RuntimeException(e); } } private void initStates() { ArrayList<String> states = new ArrayList<>(); states.add("Deleting from archive"); // 0 states.add("Delete complete"); // 1 eventStream.send(new InitStates(this.jobID, this.depositId, states) .withUserId(userID)); } private void setupArchiveFileStores() { // Connect to the archive storage(s). Look out! There are two classes called archiveStore. for (org.datavaultplatform.common.model.ArchiveStore archiveFileStore : archiveFileStores ) { try { Class<?> clazz = Class.forName(archiveFileStore.getStorageClass()); Constructor<?> constructor = clazz.getConstructor(String.class, Map.class); Object instance = constructor.newInstance(archiveFileStore.getStorageClass(), archiveFileStore.getProperties()); archiveStores.put(archiveFileStore.getID(), (ArchiveStore)instance); } catch (Exception e) { String msg = "Deposit failed: could not access archive filesystem : " + archiveFileStore.getStorageClass(); logger.error(msg, e); eventStream.send(new Error(this.jobID, this.depositId, msg).withUserId(this.userID)); throw new RuntimeException(e); } } } private void deleteMultipleCopiesFromArchiveStorage(Context context, Device archiveFs, String tarFileName, File tarFile) throws Exception { Progress progress = new Progress(); ProgressTracker tracker = new ProgressTracker(progress, this.jobID, this.depositId, this.archiveSize, this.eventStream); Thread trackerThread = new Thread(tracker); trackerThread.start(); logger.info("deleteMultipleCopiesFromArchiveStorage for deposit : {}",this.depositId); List<String> locations = archiveFs.getLocations(); for(String location : locations) { logger.info("Delete from location : {}",location); try { if (context.isChunkingEnabled()) { for( int chunkNum = 1; chunkNum <= this.numOfChunks; chunkNum++) { Path chunkPath = context.getTempDir().resolve(tarFileName+FileSplitter.CHUNK_SEPARATOR+chunkNum); File chunkFile = chunkPath.toFile(); String chunkArchiveId = this.archiveId+FileSplitter.CHUNK_SEPARATOR+chunkNum; archiveFs.delete(chunkArchiveId,chunkFile, progress,location); logger.info("---------deleteMultipleCopiesFromArchiveStorage ------chunkArchiveId Deleted---- {} ",chunkArchiveId); } } else { archiveFs.delete(this.archiveId,tarFile, progress,location); logger.info("---------deleteMultipleCopiesFromArchiveStorage ------archiveId Deleted---- {} ",this.archiveId); } } finally { // Stop the tracking thread tracker.stop(); trackerThread.join(); } } } private void deleteFromArchiveStorage(Context context, Device archiveFs, String tarFileName, File tarFile) throws Exception { Progress progress = new Progress(); ProgressTracker tracker = new ProgressTracker(progress, this.jobID, this.depositId, this.archiveSize, this.eventStream); Thread trackerThread = new Thread(tracker); trackerThread.start(); logger.info("deleteFromArchiveStorage for deposit : {}",this.depositId); try { if (context.isChunkingEnabled()) { for( int chunkNum = 1; chunkNum <= this.numOfChunks; chunkNum++) { Path chunkPath = context.getTempDir().resolve(tarFileName+FileSplitter.CHUNK_SEPARATOR+chunkNum); File chunkFile = chunkPath.toFile(); String chunkArchiveId = this.archiveId+FileSplitter.CHUNK_SEPARATOR+chunkNum; archiveFs.delete(chunkArchiveId,chunkFile, progress); logger.info("---------deleteFromArchiveStorage ------chunkArchiveId Deleted---- {} ",chunkArchiveId); } } else { archiveFs.delete(this.archiveId,tarFile, progress); logger.info("---------deleteFromArchiveStorage ------archiveId Deleted---- {} ",this.archiveId); } } finally { // Stop the tracking thread tracker.stop(); trackerThread.join(); } } }
DataVault/datavault
datavault-worker/src/main/java/org/datavaultplatform/worker/tasks/Delete.java
Java
mit
8,550
[ 30522, 7427, 8917, 1012, 2951, 3567, 11314, 24759, 4017, 14192, 1012, 7309, 1012, 8518, 1025, 12324, 9262, 1012, 22834, 1012, 30524, 1012, 11374, 1012, 8339, 1012, 9570, 2953, 1025, 12324, 9262, 1012, 9152, 2080, 1012, 5371, 1012, 4130, 102...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package de.uks.beast.editor.util; public enum Fonts { //@formatter:off HADOOP_MASTER_TITEL ("Arial", 10, true, true), HADOOP_SLAVE_TITEL ("Arial", 10, true, true), NETWORK_TITEL ("Arial", 10, true, true), CONTROL_CENTER_TITEL ("Arial", 10, true, true), HADOOP_MASTER_PROPERTY ("Arial", 8, false, true), HADOOP_SLAVE_PROPERTY ("Arial", 8, false, true), NETWORK_PROPERTY ("Arial", 8, false, true), CONTROL_CENTER_PROPERTY ("Arial", 8, false, true), ;//@formatter:on private final String name; private final int size; private final boolean italic; private final boolean bold; private Fonts(final String name, final int size, final boolean italic, final boolean bold) { this.name = name; this.size = size; this.italic = italic; this.bold = bold; } /** * @return the name */ public String getName() { return name; } /** * @return the size */ public int getSize() { return size; } /** * @return the italic */ public boolean isItalic() { return italic; } /** * @return the bold */ public boolean isBold() { return bold; } }
fujaba/BeAST
de.uks.beast.editor/src/de/uks/beast/editor/util/Fonts.java
Java
epl-1.0
1,163
[ 30522, 7427, 2139, 1012, 2866, 2015, 1012, 6841, 1012, 3559, 1012, 21183, 4014, 1025, 2270, 4372, 2819, 15489, 2015, 1063, 1013, 1013, 1030, 4289, 3334, 1024, 2125, 2018, 18589, 1035, 3040, 1035, 14841, 9834, 1006, 1000, 9342, 2140, 1000, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * @package Pkb Shortcodes * @author Zhukov Sergey <zom688@gmail.com> * @copyright Copyright © 2016 - 2017 NorrNext. All rights reserved. * @license GNU General Public License version 3 or later; see license.txt */ $view->style('admin', 'nxtshc/cms:assets/css/admin.css', 'uikit'); $view->script('settings', 'nxtshc/cms:app/bundle/settings.js', ['vue', 'jquery']); $view->script('platform.js', '//apis.google.com/js/platform.js'); ?> <div id="settings" class="uk-form uk-form-horizontal"> <h3>{{ 'Description' | trans }}</h3> <p> {{ 'PKB Shortcodes allows you to easily add complex HTML with shortcodes (macros). The widget changes the preset syntax, such as [example] to the relevant HTML code during the rendering of the Pagekit content on the front-end side.' | trans }} </p> <h3>{{ 'Example of use:' | trans }}</h3> <p>{{ 'In the Shortcode Macros field, enter:' | trans }}<br> <b>[span class="{class}"]{text}[/span]</b> </p> <p> {{ 'In the HTML Macros field, enter:' | trans }}<br> <b>&lt;span class="{class}"&gt;{text}&lt;/span&gt;</b> </p> <p>{{ 'For more information, please read the ' | trans }}<a href="https://www.norrnext.com/docs/pagekit-free-widgets/pkb-shortcodes">{{ 'Documentation' | trans }}</a>.</p> <div class="uk-width-medium-1-1 uk-container-center uk-margin-top"> <div class="uk-panel uk-panel-box uk-panel-box-primary"> <p class="uk-text-center">{{ 'Extensions made with love by NorrNext.' | trans }}</p> <ul class="uk-text-center social-share-list"> <li> <iframe src="//www.facebook.com/plugins/like.php?href=https%3A%2F%2Ffacebook.com%2Fnorrnext&amp;width&amp;layout=button_count&amp;action=like&amp;show_faces=false&amp;share=false&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:20px; width:120px" allowTransparency="true"> </iframe> </li> <li class="share-google"> <div class="g-follow" data-href="https://plus.google.com/108999239898392136664" data-rel="author"></div> </li> <li> <a href="https://twitter.com/norrnext" class="twitter-follow-button" data-show-count="true">Follow @norrnext</a> </li> <script>window.twttr = (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], t = window.twttr || {}; if (d.getElementById(id)) return t; js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); t._e = []; t.ready = function(f) { t._e.push(f); }; return t; }(document, "script", "twitter-wjs"));</script> </ul> <p class="uk-text-center"> <a href="https://www.norrnext.com/pagekit-extensions/pkb-shortcodes" target="_blank">{{ 'Home page' | trans }}</a> | <a href="https://www.norrnext.com/downloads/free-pagekit/pkb-shortcodes" target="_blank">{{ 'Download' | trans }}</a> | <a href="https://www.norrnext.com/docs/pagekit-free-widgets/pkb-shortcodes" target="_blank">{{ 'Documentation' | trans }}</a> | <a href="https://www.norrnext.com/forums/categories/listings/pkb-shortcodes" target="_blank">{{ 'Support' | trans }}</a> </p> </div> <div class="uk-text-center"><small>Dashboard icon by <a href="https://www.iconfinder.com/justui">Denis Stelmah</a></small></div> </div> </div>
yaelduckwen/entretelas
web/packages/norrnext/shortcodes/cms/views/admin/settings.php
PHP
mit
3,395
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 1030, 7427, 1052, 2243, 2497, 2460, 23237, 1008, 1030, 3166, 15503, 7724, 22703, 1026, 1062, 5358, 2575, 2620, 2620, 1030, 20917, 4014, 1012, 4012, 1028, 1008, 1030, 9385, 9385, 1075, 2355, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package indep_screen3; import com.navid.nifty.flow.ScreenFlowManager; import com.navid.nifty.flow.ScreenFlowManagerImpl; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; /** * Created by alberto on 08/07/15. */ public class Controller3 implements ScreenController { private final ScreenFlowManager screenFlowManager; private Nifty nifty; public Controller3(ScreenFlowManager screenFlowManager) { this.screenFlowManager = screenFlowManager; } @Override public void bind(Nifty nifty, Screen screen) { this.nifty = nifty; } @Override public void onStartScreen() { } @Override public void onEndScreen() { } public void back() { screenFlowManager.setNextScreenHint(ScreenFlowManagerImpl.PREV); nifty.gotoScreen("redirector"); } public void next() { screenFlowManager.setNextScreenHint(ScreenFlowManagerImpl.NEXT); nifty.gotoScreen("redirector"); } }
albertonavarro/nifty-flow
examples/ex1/src/main/java/indep_screen3/Controller3.java
Java
apache-2.0
1,048
[ 30522, 7427, 27427, 13699, 1035, 3898, 2509, 1025, 12324, 4012, 1012, 6583, 17258, 1012, 9152, 6199, 2100, 1012, 4834, 1012, 3898, 12314, 24805, 4590, 1025, 12324, 4012, 1012, 6583, 17258, 1012, 9152, 6199, 2100, 1012, 4834, 1012, 3898, 123...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** @file mlan_11n.c * * @brief This file contains functions for 11n handling. * * Copyright (C) 2008-2010, Marvell International Ltd. * All Rights Reserved */ /******************************************************** Change log: 11/10/2008: initial version ********************************************************/ #include "mlan.h" #include "mlan_join.h" #include "mlan_util.h" #include "mlan_fw.h" #include "mlan_main.h" #include "mlan_wmm.h" #include "mlan_11n.h" /******************************************************** Local Variables ********************************************************/ /******************************************************** Global Variables ********************************************************/ /******************************************************** Local Functions ********************************************************/ /** * * @brief set/get max tx buf size * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_max_tx_buf_size(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { mlan_status ret = MLAN_STATUS_SUCCESS; mlan_ds_11n_cfg *cfg = MNULL; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_SET) { if ((cfg->param.tx_buf_size == MLAN_TX_DATA_BUF_SIZE_2K) || (cfg->param.tx_buf_size == MLAN_TX_DATA_BUF_SIZE_4K) || (cfg->param.tx_buf_size == MLAN_TX_DATA_BUF_SIZE_8K)) { pmadapter->max_tx_buf_size = (t_u16) cfg->param.tx_buf_size; } else ret = MLAN_STATUS_FAILURE; } else cfg->param.tx_buf_size = (t_u32) pmadapter->max_tx_buf_size; pioctl_req->data_read_written = sizeof(t_u32) + MLAN_SUB_COMMAND_SIZE; LEAVE(); return ret; } /** * @brief Set/get htcapinfo configuration * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_htusrcfg(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { mlan_status ret = MLAN_STATUS_SUCCESS; mlan_private *pmpriv = pmadapter->priv[pioctl_req->bss_num]; mlan_ds_11n_cfg *cfg = MNULL; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_SET) { if (((cfg->param.htcap_cfg & ~IGN_HW_DEV_CAP) & pmpriv->adapter->hw_dot_11n_dev_cap) != (cfg->param.htcap_cfg & ~IGN_HW_DEV_CAP)) ret = MLAN_STATUS_FAILURE; else pmadapter->usr_dot_11n_dev_cap = cfg->param.htcap_cfg; PRINTM(MINFO, "Set: UsrDot11nCap 0x%x\n", pmadapter->usr_dot_11n_dev_cap); } else { cfg->param.htcap_cfg = pmadapter->usr_dot_11n_dev_cap; PRINTM(MINFO, "Get: UsrDot11nCap 0x%x\n", cfg->param.htcap_cfg); } LEAVE(); return ret; } /** * @brief Enable/Disable AMSDU AGGR CTRL * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_amsdu_aggr_ctrl(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { mlan_status ret = MLAN_STATUS_SUCCESS; mlan_private *pmpriv = pmadapter->priv[pioctl_req->bss_num]; mlan_ds_11n_cfg *cfg = MNULL; t_u16 cmd_action = 0; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_SET) cmd_action = HostCmd_ACT_GEN_SET; else cmd_action = HostCmd_ACT_GEN_GET; /* Send request to firmware */ ret = wlan_prepare_cmd(pmpriv, HostCmd_CMD_AMSDU_AGGR_CTRL, cmd_action, 0, (t_void *) pioctl_req, (t_void *) & cfg->param.amsdu_aggr_ctrl); if (ret == MLAN_STATUS_SUCCESS) ret = MLAN_STATUS_PENDING; LEAVE(); return ret; } /** * @brief Set/get 11n configuration * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_httxcfg(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { mlan_status ret = MLAN_STATUS_SUCCESS; mlan_private *pmpriv = pmadapter->priv[pioctl_req->bss_num]; mlan_ds_11n_cfg *cfg = MNULL; t_u16 cmd_action = 0; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_SET) cmd_action = HostCmd_ACT_GEN_SET; else cmd_action = HostCmd_ACT_GEN_GET; /* Send request to firmware */ ret = wlan_prepare_cmd(pmpriv, HostCmd_CMD_11N_CFG, cmd_action, 0, (t_void *) pioctl_req, (t_void *) & cfg->param.tx_cfg); if (ret == MLAN_STATUS_SUCCESS) ret = MLAN_STATUS_PENDING; LEAVE(); return ret; } /** * @brief Set/get addba parameter * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_addba_param(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { mlan_status ret = MLAN_STATUS_SUCCESS; mlan_private *pmpriv = pmadapter->priv[pioctl_req->bss_num]; mlan_ds_11n_cfg *cfg = MNULL; t_u32 timeout; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_GET) { cfg->param.addba_param.timeout = pmpriv->add_ba_param.timeout; cfg->param.addba_param.txwinsize = pmpriv->add_ba_param.tx_win_size; cfg->param.addba_param.rxwinsize = pmpriv->add_ba_param.rx_win_size; } else { timeout = pmpriv->add_ba_param.timeout; pmpriv->add_ba_param.timeout = cfg->param.addba_param.timeout; pmpriv->add_ba_param.tx_win_size = cfg->param.addba_param.txwinsize; pmpriv->add_ba_param.rx_win_size = cfg->param.addba_param.rxwinsize; if (timeout != pmpriv->add_ba_param.timeout) { wlan_11n_update_addba_request(pmpriv); } } LEAVE(); return ret; } /** * @brief Set/get addba reject set * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_addba_reject(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { int i = 0; mlan_status ret = MLAN_STATUS_SUCCESS; mlan_private *pmpriv = pmadapter->priv[pioctl_req->bss_num]; mlan_ds_11n_cfg *cfg = MNULL; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_GET) { PRINTM(MINFO, "Get Addba reject\n"); memcpy(pmadapter, cfg->param.addba_reject, pmpriv->addba_reject, MAX_NUM_TID); } else { if (pmpriv->media_connected == MTRUE) { PRINTM(MERROR, "Can not set aggr priority table in connected" " state\n"); LEAVE(); return MLAN_STATUS_FAILURE; } for (i = 0; i < MAX_NUM_TID; i++) { /* For AMPDU */ if (cfg->param.addba_reject[i] > ADDBA_RSP_STATUS_REJECT) { ret = MLAN_STATUS_FAILURE; break; } pmpriv->addba_reject[i] = cfg->param.addba_reject[i]; } } LEAVE(); return ret; } /** * @brief Set/get aggr_prio_tbl * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ static mlan_status wlan_11n_ioctl_aggr_prio_tbl(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { int i = 0; mlan_status ret = MLAN_STATUS_SUCCESS; mlan_private *pmpriv = pmadapter->priv[pioctl_req->bss_num]; mlan_ds_11n_cfg *cfg = MNULL; ENTER(); cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; if (pioctl_req->action == MLAN_ACT_GET) { for (i = 0; i < MAX_NUM_TID; i++) { cfg->param.aggr_prio_tbl.ampdu[i] = pmpriv->aggr_prio_tbl[i].ampdu_user; cfg->param.aggr_prio_tbl.amsdu[i] = pmpriv->aggr_prio_tbl[i].amsdu; } } else { if (pmpriv->media_connected == MTRUE) { PRINTM(MERROR, "Can not set aggr priority table in connected" " state\n"); LEAVE(); return MLAN_STATUS_FAILURE; } for (i = 0; i < MAX_NUM_TID; i++) { /* For AMPDU */ if ((cfg->param.aggr_prio_tbl.ampdu[i] > HIGH_PRIO_TID) && (cfg->param.aggr_prio_tbl.ampdu[i] != BA_STREAM_NOT_ALLOWED)) { ret = MLAN_STATUS_FAILURE; break; } pmpriv->aggr_prio_tbl[i].ampdu_ap = pmpriv->aggr_prio_tbl[i].ampdu_user = cfg->param.aggr_prio_tbl.ampdu[i]; /* For AMSDU */ if ((cfg->param.aggr_prio_tbl.amsdu[i] > HIGH_PRIO_TID && cfg->param.aggr_prio_tbl.amsdu[i] != BA_STREAM_NOT_ALLOWED)) { ret = MLAN_STATUS_FAILURE; break; } else { pmpriv->aggr_prio_tbl[i].amsdu = cfg->param.aggr_prio_tbl.amsdu[i]; } } } LEAVE(); return ret; } #ifdef STA_SUPPORT /** * @brief This function fills the cap info * * @param priv A pointer to mlan_private structure * @param pht_cap A pointer to MrvlIETypes_HTCap_t structure * * @return N/A */ void wlan_fill_cap_info(mlan_private * priv, MrvlIETypes_HTCap_t * pht_cap) { mlan_adapter *pmadapter = priv->adapter; int rx_mcs_supp; ENTER(); if (ISSUPP_CHANWIDTH40(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_CHANWIDTH40(pmadapter->usr_dot_11n_dev_cap)) SETHT_SUPPCHANWIDTH(pht_cap->ht_cap.ht_cap_info); else RESETHT_SUPPCHANWIDTH(pht_cap->ht_cap.ht_cap_info); if (ISSUPP_GREENFIELD(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_GREENFIELD(pmadapter->usr_dot_11n_dev_cap)) SETHT_GREENFIELD(pht_cap->ht_cap.ht_cap_info); else RESETHT_GREENFIELD(pht_cap->ht_cap.ht_cap_info); if (ISSUPP_SHORTGI20(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_SHORTGI20(pmadapter->usr_dot_11n_dev_cap)) SETHT_SHORTGI20(pht_cap->ht_cap.ht_cap_info); else RESETHT_SHORTGI20(pht_cap->ht_cap.ht_cap_info); if (ISSUPP_SHORTGI40(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_SHORTGI40(pmadapter->usr_dot_11n_dev_cap)) SETHT_SHORTGI40(pht_cap->ht_cap.ht_cap_info); else RESETHT_SHORTGI40(pht_cap->ht_cap.ht_cap_info); /* No user config for RX STBC yet */ if (ISSUPP_RXSTBC(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_RXSTBC(pmadapter->usr_dot_11n_dev_cap)) SETHT_RXSTBC(pht_cap->ht_cap.ht_cap_info, 1); else RESETHT_RXSTBC(pht_cap->ht_cap.ht_cap_info); /* No user config for TX STBC yet */ if (ISSUPP_TXSTBC(pmadapter->hw_dot_11n_dev_cap)) SETHT_TXSTBC(pht_cap->ht_cap.ht_cap_info); else RESETHT_TXSTBC(pht_cap->ht_cap.ht_cap_info); /* No user config for Delayed BACK yet */ if (GET_DELAYEDBACK(pmadapter->hw_dot_11n_dev_cap)) SETHT_DELAYEDBACK(pht_cap->ht_cap.ht_cap_info); else RESETHT_DELAYEDBACK(pht_cap->ht_cap.ht_cap_info); if (ISENABLED_40MHZ_INTOLARENT(pmadapter->usr_dot_11n_dev_cap)) SETHT_40MHZ_INTOLARANT(pht_cap->ht_cap.ht_cap_info); else RESETHT_40MHZ_INTOLARANT(pht_cap->ht_cap.ht_cap_info); SETAMPDU_SIZE(pht_cap->ht_cap.ampdu_param, AMPDU_FACTOR_64K); SETAMPDU_SPACING(pht_cap->ht_cap.ampdu_param, 0); /* Need change to support 8k AMSDU receive */ RESETHT_MAXAMSDU(pht_cap->ht_cap.ht_cap_info); rx_mcs_supp = GET_RXMCSSUPP(pmadapter->hw_dev_mcs_support); /** Maximum MCS */ #define NUM_MCS_FIELD 16 /* Set MCS for 1x1 */ memset(pmadapter, (t_u8 *) pht_cap->ht_cap.supported_mcs_set, 0xff, rx_mcs_supp); /* Clear all the other values */ memset(pmadapter, (t_u8 *) & pht_cap->ht_cap.supported_mcs_set[rx_mcs_supp], 0, NUM_MCS_FIELD - rx_mcs_supp); if (priv->bss_mode == MLAN_BSS_MODE_INFRA || (ISSUPP_CHANWIDTH40(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_CHANWIDTH40(pmadapter->usr_dot_11n_dev_cap))) /* Set MCS32 for infra mode or ad-hoc mode with 40MHz support */ SETHT_MCS32(pht_cap->ht_cap.supported_mcs_set); /* Clear RD responder bit */ RESETHT_EXTCAP_RDG(pht_cap->ht_cap.ht_ext_cap); LEAVE(); } #endif /* STA_SUPPORT */ /******************************************************** Global Functions ********************************************************/ /** * @brief This function prints the 802.11n device capability * * @param pmadapter A pointer to mlan_adapter structure * @param cap Capability value * * @return N/A */ void wlan_show_dot11ndevcap(pmlan_adapter pmadapter, t_u32 cap) { ENTER(); PRINTM(MINFO, "GET_HW_SPEC: Maximum MSDU length = %s octets\n", (ISSUPP_MAXAMSDU(cap) ? "7935" : "3839")); PRINTM(MINFO, "GET_HW_SPEC: Beam forming %s\n", (ISSUPP_BEAMFORMING(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: Greenfield preamble %s\n", (ISSUPP_GREENFIELD(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: AMPDU %s\n", (ISSUPP_AMPDU(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: MIMO Power Save %s\n", (ISSUPP_MIMOPS(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: Rx STBC %s\n", (ISSUPP_RXSTBC(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: Tx STBC %s\n", (ISSUPP_TXSTBC(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: Short GI for 40 Mhz %s\n", (ISSUPP_SHORTGI40(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: Short GI for 20 Mhz %s\n", (ISSUPP_SHORTGI20(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: LDPC coded packet receive %s\n", (ISSUPP_RXLDPC(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: Number of Delayed Block Ack streams = %d\n", GET_DELAYEDBACK(cap)); PRINTM(MINFO, "GET_HW_SPEC: Number of Immediate Block Ack streams = %d\n", GET_IMMEDIATEBACK(cap)); PRINTM(MINFO, "GET_HW_SPEC: 40 Mhz channel width %s\n", (ISSUPP_CHANWIDTH40(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: 20 Mhz channel width %s\n", (ISSUPP_CHANWIDTH20(cap) ? "supported" : "not supported")); PRINTM(MINFO, "GET_HW_SPEC: 10 Mhz channel width %s\n", (ISSUPP_CHANWIDTH10(cap) ? "supported" : "not supported")); if (ISSUPP_RXANTENNAA(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Rx antenna A\n"); } if (ISSUPP_RXANTENNAB(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Rx antenna B\n"); } if (ISSUPP_RXANTENNAC(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Rx antenna C\n"); } if (ISSUPP_RXANTENNAD(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Rx antenna D\n"); } if (ISSUPP_TXANTENNAA(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Tx antenna A\n"); } if (ISSUPP_TXANTENNAB(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Tx antenna B\n"); } if (ISSUPP_TXANTENNAC(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Tx antenna C\n"); } if (ISSUPP_TXANTENNAD(cap)) { PRINTM(MINFO, "GET_HW_SPEC: Presence of Tx antenna D\n"); } LEAVE(); return; } /** * @brief This function prints the 802.11n device MCS * * @param pmadapter A pointer to mlan_adapter structure * @param support Support value * * @return N/A */ void wlan_show_devmcssupport(pmlan_adapter pmadapter, t_u8 support) { ENTER(); PRINTM(MINFO, "GET_HW_SPEC: MCSs for %dx%d MIMO\n", GET_RXMCSSUPP(support), GET_TXMCSSUPP(support)); LEAVE(); return; } /** * @brief This function handles the command response of * delete a block ack request * * @param priv A pointer to mlan_private structure * @param resp A pointer to HostCmd_DS_COMMAND * * @return MLAN_STATUS_SUCCESS */ mlan_status wlan_ret_11n_delba(mlan_private * priv, HostCmd_DS_COMMAND * resp) { int tid; TxBAStreamTbl *ptx_ba_tbl; HostCmd_DS_11N_DELBA *pdel_ba = (HostCmd_DS_11N_DELBA *) & resp->params.del_ba; ENTER(); pdel_ba->del_ba_param_set = wlan_le16_to_cpu(pdel_ba->del_ba_param_set); pdel_ba->reason_code = wlan_le16_to_cpu(pdel_ba->reason_code); tid = pdel_ba->del_ba_param_set >> DELBA_TID_POS; if (pdel_ba->del_result == BA_RESULT_SUCCESS) { mlan_11n_delete_bastream_tbl(priv, tid, pdel_ba->peer_mac_addr, TYPE_DELBA_SENT, INITIATOR_BIT(pdel_ba->del_ba_param_set)); if ((ptx_ba_tbl = wlan_11n_get_txbastream_status(priv, BA_STREAM_SETUP_INPROGRESS))) { wlan_send_addba(priv, ptx_ba_tbl->tid, ptx_ba_tbl->ra); } } else { /* * In case of failure, recreate the deleted stream in * case we initiated the ADDBA */ if (INITIATOR_BIT(pdel_ba->del_ba_param_set)) { wlan_11n_create_txbastream_tbl(priv, pdel_ba->peer_mac_addr, tid, BA_STREAM_SETUP_INPROGRESS); if ((ptx_ba_tbl = wlan_11n_get_txbastream_status(priv, BA_STREAM_SETUP_INPROGRESS))) { mlan_11n_delete_bastream_tbl(priv, ptx_ba_tbl->tid, ptx_ba_tbl->ra, TYPE_DELBA_SENT, MTRUE); } } } LEAVE(); return MLAN_STATUS_SUCCESS; } /** * @brief This function handles the command response of * add a block ack request * * @param priv A pointer to mlan_private structure * @param resp A pointer to HostCmd_DS_COMMAND * * @return MLAN_STATUS_SUCCESS */ mlan_status wlan_ret_11n_addba_req(mlan_private * priv, HostCmd_DS_COMMAND * resp) { int tid; HostCmd_DS_11N_ADDBA_RSP *padd_ba_rsp = (HostCmd_DS_11N_ADDBA_RSP *) & resp->params.add_ba_rsp; TxBAStreamTbl *ptx_ba_tbl; ENTER(); padd_ba_rsp->block_ack_param_set = wlan_le16_to_cpu(padd_ba_rsp->block_ack_param_set); padd_ba_rsp->block_ack_tmo = wlan_le16_to_cpu(padd_ba_rsp->block_ack_tmo); padd_ba_rsp->ssn = (wlan_le16_to_cpu(padd_ba_rsp->ssn)) & SSN_MASK; padd_ba_rsp->status_code = wlan_le16_to_cpu(padd_ba_rsp->status_code); tid = (padd_ba_rsp->block_ack_param_set & BLOCKACKPARAM_TID_MASK) >> BLOCKACKPARAM_TID_POS; if (padd_ba_rsp->status_code == BA_RESULT_SUCCESS) { if ((ptx_ba_tbl = wlan_11n_get_txbastream_tbl(priv, tid, padd_ba_rsp-> peer_mac_addr))) { PRINTM(MINFO, "BA stream complete\n"); ptx_ba_tbl->ba_status = BA_STREAM_SETUP_COMPLETE; } else { PRINTM(MERROR, "BA stream not created\n"); } } else { mlan_11n_delete_bastream_tbl(priv, tid, padd_ba_rsp->peer_mac_addr, TYPE_DELBA_SENT, MTRUE); if (padd_ba_rsp->add_rsp_result != BA_RESULT_TIMEOUT) { #ifdef UAP_SUPPORT if (priv->bss_type == MLAN_BSS_TYPE_UAP) disable_station_ampdu(priv, tid, padd_ba_rsp->peer_mac_addr); #endif /* UAP_SUPPORT */ priv->aggr_prio_tbl[tid].ampdu_ap = BA_STREAM_NOT_ALLOWED; } } LEAVE(); return MLAN_STATUS_SUCCESS; } /** * @brief This function handles the command response of 11ncfg * * @param pmpriv A pointer to mlan_private structure * @param resp A pointer to HostCmd_DS_COMMAND * @param pioctl_buf A pointer to mlan_ioctl_req structure * * @return MLAN_STATUS_SUCCESS */ mlan_status wlan_ret_11n_cfg(IN pmlan_private pmpriv, IN HostCmd_DS_COMMAND * resp, IN mlan_ioctl_req * pioctl_buf) { mlan_ds_11n_cfg *cfg = MNULL; HostCmd_DS_11N_CFG *htcfg = &resp->params.htcfg; ENTER(); if (pioctl_buf) { cfg = (mlan_ds_11n_cfg *) pioctl_buf->pbuf; cfg->param.tx_cfg.httxcap = wlan_le16_to_cpu(htcfg->ht_tx_cap); cfg->param.tx_cfg.httxinfo = wlan_le16_to_cpu(htcfg->ht_tx_info); } LEAVE(); return MLAN_STATUS_SUCCESS; } /** * @brief This function prepares command of reconfigure tx buf * * @param priv A pointer to mlan_private structure * @param cmd A pointer to HostCmd_DS_COMMAND structure * @param cmd_action The action: GET or SET * @param pdata_buf A pointer to data buffer * * @return MLAN_STATUS_SUCCESS */ mlan_status wlan_cmd_recfg_tx_buf(mlan_private * priv, HostCmd_DS_COMMAND * cmd, int cmd_action, void *pdata_buf) { HostCmd_DS_TXBUF_CFG *ptx_buf = &cmd->params.tx_buf; t_u16 action = (t_u16) cmd_action; t_u16 buf_size = *((t_u16 *) pdata_buf); ENTER(); cmd->command = wlan_cpu_to_le16(HostCmd_CMD_RECONFIGURE_TX_BUFF); cmd->size = wlan_cpu_to_le16(sizeof(HostCmd_DS_TXBUF_CFG) + S_DS_GEN); ptx_buf->action = wlan_cpu_to_le16(action); switch (action) { case HostCmd_ACT_GEN_SET: PRINTM(MCMND, "set tx_buf = %d\n", buf_size); ptx_buf->buff_size = wlan_cpu_to_le16(buf_size); break; case HostCmd_ACT_GEN_GET: default: ptx_buf->buff_size = 0; break; } LEAVE(); return MLAN_STATUS_SUCCESS; } /** * @brief This function prepares command of amsdu aggr control * * @param priv A pointer to mlan_private structure * @param cmd A pointer to HostCmd_DS_COMMAND structure * @param cmd_action The action: GET or SET * @param pdata_buf A pointer to data buffer * * @return MLAN_STATUS_SUCCESS */ mlan_status wlan_cmd_amsdu_aggr_ctrl(mlan_private * priv, HostCmd_DS_COMMAND * cmd, int cmd_action, void *pdata_buf) { HostCmd_DS_AMSDU_AGGR_CTRL *pamsdu_ctrl = &cmd->params.amsdu_aggr_ctrl; t_u16 action = (t_u16) cmd_action; mlan_ds_11n_amsdu_aggr_ctrl *aa_ctrl = (mlan_ds_11n_amsdu_aggr_ctrl *) pdata_buf; ENTER(); cmd->command = wlan_cpu_to_le16(HostCmd_CMD_AMSDU_AGGR_CTRL); cmd->size = wlan_cpu_to_le16(sizeof(HostCmd_DS_AMSDU_AGGR_CTRL) + S_DS_GEN); pamsdu_ctrl->action = wlan_cpu_to_le16(action); switch (action) { case HostCmd_ACT_GEN_SET: pamsdu_ctrl->enable = wlan_cpu_to_le16(aa_ctrl->enable); pamsdu_ctrl->curr_buf_size = 0; break; case HostCmd_ACT_GEN_GET: default: pamsdu_ctrl->curr_buf_size = 0; break; } LEAVE(); return MLAN_STATUS_SUCCESS; } /** * @brief This function handles the command response of amsdu aggr ctrl * * @param pmpriv A pointer to mlan_private structure * @param resp A pointer to HostCmd_DS_COMMAND * @param pioctl_buf A pointer to mlan_ioctl_req structure * * @return MLAN_STATUS_SUCCESS */ mlan_status wlan_ret_amsdu_aggr_ctrl(IN pmlan_private pmpriv, IN HostCmd_DS_COMMAND * resp, IN mlan_ioctl_req * pioctl_buf) { mlan_ds_11n_cfg *cfg = MNULL; HostCmd_DS_AMSDU_AGGR_CTRL *amsdu_ctrl = &resp->params.amsdu_aggr_ctrl; ENTER(); if (pioctl_buf) { cfg = (mlan_ds_11n_cfg *) pioctl_buf->pbuf; cfg->param.amsdu_aggr_ctrl.enable = wlan_le16_to_cpu(amsdu_ctrl->enable); cfg->param.amsdu_aggr_ctrl.curr_buf_size = wlan_le16_to_cpu(amsdu_ctrl->curr_buf_size); } LEAVE(); return MLAN_STATUS_SUCCESS; } /** * @brief This function prepares 11n cfg command * * @param pmpriv A pointer to mlan_private structure * @param cmd A pointer to HostCmd_DS_COMMAND structure * @param cmd_action the action: GET or SET * @param pdata_buf A pointer to data buffer * @return MLAN_STATUS_SUCCESS or MLAN_STATUS_FAILURE */ mlan_status wlan_cmd_11n_cfg(IN pmlan_private pmpriv, IN HostCmd_DS_COMMAND * cmd, IN t_u16 cmd_action, IN t_void * pdata_buf) { HostCmd_DS_11N_CFG *htcfg = &cmd->params.htcfg; mlan_ds_11n_tx_cfg *txcfg = (mlan_ds_11n_tx_cfg *) pdata_buf; cmd->command = wlan_cpu_to_le16(HostCmd_CMD_11N_CFG); cmd->size = wlan_cpu_to_le16(sizeof(HostCmd_DS_11N_CFG) + S_DS_GEN); htcfg->action = wlan_cpu_to_le16(cmd_action); htcfg->ht_tx_cap = wlan_cpu_to_le16(txcfg->httxcap); htcfg->ht_tx_info = wlan_cpu_to_le16(txcfg->httxinfo); return MLAN_STATUS_SUCCESS; } #ifdef STA_SUPPORT /** * @brief This function append the 802_11N tlv * * @param pmpriv A pointer to mlan_private structure * @param pbss_desc A pointer to BSSDescriptor_t structure * @param ppbuffer A Pointer to command buffer pointer * * @return bytes added to the buffer */ int wlan_cmd_append_11n_tlv(IN mlan_private * pmpriv, IN BSSDescriptor_t * pbss_desc, OUT t_u8 ** ppbuffer) { pmlan_adapter pmadapter = pmpriv->adapter; MrvlIETypes_HTCap_t *pht_cap; MrvlIETypes_HTInfo_t *pht_info; MrvlIEtypes_ChanListParamSet_t *pchan_list; MrvlIETypes_2040BSSCo_t *p2040_bss_co; MrvlIETypes_ExtCap_t *pext_cap; int ret_len = 0; ENTER(); /* Null Checks */ if (ppbuffer == 0) { LEAVE(); return 0; } if (*ppbuffer == 0) { LEAVE(); return 0; } if (pbss_desc->pht_cap) { pht_cap = (MrvlIETypes_HTCap_t *) * ppbuffer; memset(pmadapter, pht_cap, 0, sizeof(MrvlIETypes_HTCap_t)); pht_cap->header.type = wlan_cpu_to_le16(HT_CAPABILITY); pht_cap->header.len = sizeof(HTCap_t); memcpy(pmadapter, (t_u8 *) pht_cap + sizeof(MrvlIEtypesHeader_t), (t_u8 *) pbss_desc->pht_cap + sizeof(IEEEtypes_Header_t), pht_cap->header.len); pht_cap->ht_cap.ht_cap_info = wlan_le16_to_cpu(pht_cap->ht_cap.ht_cap_info); wlan_fill_cap_info(pmpriv, pht_cap); pht_cap->ht_cap.ht_cap_info = wlan_cpu_to_le16(pht_cap->ht_cap.ht_cap_info); HEXDUMP("HT_CAPABILITIES IE", (t_u8 *) pht_cap, sizeof(MrvlIETypes_HTCap_t)); *ppbuffer += sizeof(MrvlIETypes_HTCap_t); ret_len += sizeof(MrvlIETypes_HTCap_t); pht_cap->header.len = wlan_cpu_to_le16(pht_cap->header.len); } if (pbss_desc->pht_info) { if (pmpriv->bss_mode == MLAN_BSS_MODE_IBSS) { pht_info = (MrvlIETypes_HTInfo_t *) * ppbuffer; memset(pmadapter, pht_info, 0, sizeof(MrvlIETypes_HTInfo_t)); pht_info->header.type = wlan_cpu_to_le16(HT_OPERATION); pht_info->header.len = sizeof(HTInfo_t); memcpy(pmadapter, (t_u8 *) pht_info + sizeof(MrvlIEtypesHeader_t), (t_u8 *) pbss_desc->pht_info + sizeof(IEEEtypes_Header_t), pht_info->header.len); if (!ISSUPP_CHANWIDTH40(pmadapter->hw_dot_11n_dev_cap) || !ISSUPP_CHANWIDTH40(pmadapter->usr_dot_11n_dev_cap)) { RESET_CHANWIDTH40(pht_info->ht_info.field2); } *ppbuffer += sizeof(MrvlIETypes_HTInfo_t); ret_len += sizeof(MrvlIETypes_HTInfo_t); pht_info->header.len = wlan_cpu_to_le16(pht_info->header.len); } pchan_list = (MrvlIEtypes_ChanListParamSet_t *) * ppbuffer; memset(pmadapter, pchan_list, 0, sizeof(MrvlIEtypes_ChanListParamSet_t)); pchan_list->header.type = wlan_cpu_to_le16(TLV_TYPE_CHANLIST); pchan_list->header.len = sizeof(MrvlIEtypes_ChanListParamSet_t) - sizeof(MrvlIEtypesHeader_t); pchan_list->chan_scan_param[0].chan_number = pbss_desc->pht_info->ht_info.pri_chan; pchan_list->chan_scan_param[0].radio_type = wlan_band_to_radio_type((t_u8) pbss_desc->bss_band); if ((ISSUPP_CHANWIDTH40(pmadapter->hw_dot_11n_dev_cap) && ISSUPP_CHANWIDTH40(pmadapter->usr_dot_11n_dev_cap)) && ISALLOWED_CHANWIDTH40(pbss_desc->pht_info->ht_info.field2)) SET_SECONDARYCHAN(pchan_list->chan_scan_param[0].radio_type, GET_SECONDARYCHAN(pbss_desc->pht_info->ht_info. field2)); HEXDUMP("ChanList", (t_u8 *) pchan_list, sizeof(MrvlIEtypes_ChanListParamSet_t)); HEXDUMP("pht_info", (t_u8 *) pbss_desc->pht_info, sizeof(MrvlIETypes_HTInfo_t) - 2); *ppbuffer += sizeof(MrvlIEtypes_ChanListParamSet_t); ret_len += sizeof(MrvlIEtypes_ChanListParamSet_t); pchan_list->header.len = wlan_cpu_to_le16(pchan_list->header.len); } if (pbss_desc->pbss_co_2040) { p2040_bss_co = (MrvlIETypes_2040BSSCo_t *) * ppbuffer; memset(pmadapter, p2040_bss_co, 0, sizeof(MrvlIETypes_2040BSSCo_t)); p2040_bss_co->header.type = wlan_cpu_to_le16(BSSCO_2040); p2040_bss_co->header.len = sizeof(BSSCo2040_t); memcpy(pmadapter, (t_u8 *) p2040_bss_co + sizeof(MrvlIEtypesHeader_t), (t_u8 *) pbss_desc->pbss_co_2040 + sizeof(IEEEtypes_Header_t), p2040_bss_co->header.len); HEXDUMP("20/40 BSS Coexistence IE", (t_u8 *) p2040_bss_co, sizeof(MrvlIETypes_2040BSSCo_t)); *ppbuffer += sizeof(MrvlIETypes_2040BSSCo_t); ret_len += sizeof(MrvlIETypes_2040BSSCo_t); p2040_bss_co->header.len = wlan_cpu_to_le16(p2040_bss_co->header.len); } if (pbss_desc->pext_cap) { pext_cap = (MrvlIETypes_ExtCap_t *) * ppbuffer; memset(pmadapter, pext_cap, 0, sizeof(MrvlIETypes_ExtCap_t)); pext_cap->header.type = wlan_cpu_to_le16(EXT_CAPABILITY); pext_cap->header.len = sizeof(ExtCap_t); memcpy(pmadapter, (t_u8 *) pext_cap + sizeof(MrvlIEtypesHeader_t), (t_u8 *) pbss_desc->pext_cap + sizeof(IEEEtypes_Header_t), pext_cap->header.len); HEXDUMP("Extended Capabilities IE", (t_u8 *) pext_cap, sizeof(MrvlIETypes_ExtCap_t)); *ppbuffer += sizeof(MrvlIETypes_ExtCap_t); ret_len += sizeof(MrvlIETypes_ExtCap_t); pext_cap->header.len = wlan_cpu_to_le16(pext_cap->header.len); } LEAVE(); return ret_len; } /** * @brief This function reconfigure the tx buf size in firmware. * * @param pmpriv A pointer to mlan_private structure * @param pbss_desc BSSDescriptor_t from the scan table to assoc * * @return N/A */ void wlan_cfg_tx_buf(mlan_private * pmpriv, BSSDescriptor_t * pbss_desc) { t_u16 max_amsdu = MLAN_TX_DATA_BUF_SIZE_2K; t_u16 tx_buf = 0; t_u16 curr_tx_buf_size = 0; ENTER(); if (pbss_desc->pht_cap) { if (GETHT_MAXAMSDU(pbss_desc->pht_cap->ht_cap.ht_cap_info)) max_amsdu = MLAN_TX_DATA_BUF_SIZE_8K; else max_amsdu = MLAN_TX_DATA_BUF_SIZE_4K; } tx_buf = MIN(pmpriv->adapter->max_tx_buf_size, max_amsdu); PRINTM(MINFO, "max_amsdu=%d, maxTxBuf=%d\n", max_amsdu, pmpriv->adapter->max_tx_buf_size); if (pmpriv->adapter->curr_tx_buf_size <= MLAN_TX_DATA_BUF_SIZE_2K) curr_tx_buf_size = MLAN_TX_DATA_BUF_SIZE_2K; else if (pmpriv->adapter->curr_tx_buf_size <= MLAN_TX_DATA_BUF_SIZE_4K) curr_tx_buf_size = MLAN_TX_DATA_BUF_SIZE_4K; else if (pmpriv->adapter->curr_tx_buf_size <= MLAN_TX_DATA_BUF_SIZE_8K) curr_tx_buf_size = MLAN_TX_DATA_BUF_SIZE_8K; if (curr_tx_buf_size != tx_buf) { wlan_prepare_cmd(pmpriv, HostCmd_CMD_RECONFIGURE_TX_BUFF, HostCmd_ACT_GEN_SET, 0, MNULL, &tx_buf); } LEAVE(); return; } #endif /* STA_SUPPORT */ /** * @brief 11n configuration handler * * @param pmadapter A pointer to mlan_adapter structure * @param pioctl_req A pointer to ioctl request buffer * * @return MLAN_STATUS_SUCCESS --success, otherwise fail */ mlan_status wlan_11n_cfg_ioctl(IN pmlan_adapter pmadapter, IN pmlan_ioctl_req pioctl_req) { mlan_status status = MLAN_STATUS_SUCCESS; mlan_ds_11n_cfg *cfg = MNULL; ENTER(); if (pioctl_req->buf_len < sizeof(mlan_ds_11n_cfg)) { PRINTM(MINFO, "MLAN bss IOCTL length is too short.\n"); pioctl_req->data_read_written = 0; pioctl_req->buf_len_needed = sizeof(mlan_ds_11n_cfg); LEAVE(); return MLAN_STATUS_RESOURCE; } cfg = (mlan_ds_11n_cfg *) pioctl_req->pbuf; switch (cfg->sub_command) { case MLAN_OID_11N_CFG_TX: status = wlan_11n_ioctl_httxcfg(pmadapter, pioctl_req); break; case MLAN_OID_11N_HTCAP_CFG: status = wlan_11n_ioctl_htusrcfg(pmadapter, pioctl_req); break; case MLAN_OID_11N_CFG_AGGR_PRIO_TBL: status = wlan_11n_ioctl_aggr_prio_tbl(pmadapter, pioctl_req); break; case MLAN_OID_11N_CFG_ADDBA_REJECT: status = wlan_11n_ioctl_addba_reject(pmadapter, pioctl_req); break; case MLAN_OID_11N_CFG_ADDBA_PARAM: status = wlan_11n_ioctl_addba_param(pmadapter, pioctl_req); break; case MLAN_OID_11N_CFG_MAX_TX_BUF_SIZE: status = wlan_11n_ioctl_max_tx_buf_size(pmadapter, pioctl_req); break; case MLAN_OID_11N_CFG_AMSDU_AGGR_CTRL: status = wlan_11n_ioctl_amsdu_aggr_ctrl(pmadapter, pioctl_req); break; default: status = MLAN_STATUS_FAILURE; break; } LEAVE(); return status; } /** * @brief This function checks if the given pointer is valid entry of * Tx BA Stream table * * @param priv Pointer to mlan_private * @param ptxtblptr Pointer to tx ba stream entry * * @return MTRUE or MFALSE */ int wlan_is_txbastreamptr_valid(mlan_private * priv, TxBAStreamTbl * ptxtblptr) { TxBAStreamTbl *ptx_tbl; ENTER(); if (! (ptx_tbl = (TxBAStreamTbl *) util_peek_list(priv->adapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, MNULL, MNULL))) { LEAVE(); return MFALSE; } while (ptx_tbl != (TxBAStreamTbl *) & priv->tx_ba_stream_tbl_ptr) { if (ptx_tbl == ptxtblptr) { LEAVE(); return MTRUE; } ptx_tbl = ptx_tbl->pnext; } LEAVE(); return MFALSE; } /** * @brief This function will delete the given entry in Tx BA Stream table * * @param priv Pointer to mlan_private * @param ptx_tbl Pointer to tx ba stream entry to delete * * @return N/A */ void wlan_11n_delete_txbastream_tbl_entry(mlan_private * priv, TxBAStreamTbl * ptx_tbl) { pmlan_adapter pmadapter = priv->adapter; ENTER(); pmadapter->callbacks.moal_spin_lock(pmadapter->pmoal_handle, priv->tx_ba_stream_tbl_ptr.plock); if (!ptx_tbl && wlan_is_txbastreamptr_valid(priv, ptx_tbl)) { goto exit; } PRINTM(MINFO, "Delete BA stream table entry: %p\n", ptx_tbl); util_unlink_list(pmadapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, (pmlan_linked_list) ptx_tbl, MNULL, MNULL); pmadapter->callbacks.moal_mfree(pmadapter->pmoal_handle, (t_u8 *) ptx_tbl); exit: pmadapter->callbacks.moal_spin_unlock(pmadapter->pmoal_handle, priv->tx_ba_stream_tbl_ptr.plock); LEAVE(); } /** * @brief This function will delete all the entries in Tx BA Stream table * * @param priv A pointer to mlan_private * * @return N/A */ void wlan_11n_deleteall_txbastream_tbl(mlan_private * priv) { int i; TxBAStreamTbl *del_tbl_ptr = MNULL; ENTER(); while ((del_tbl_ptr = (TxBAStreamTbl *) util_peek_list(priv->adapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, priv->adapter->callbacks.moal_spin_lock, priv->adapter->callbacks.moal_spin_unlock))) { wlan_11n_delete_txbastream_tbl_entry(priv, del_tbl_ptr); } util_init_list((pmlan_linked_list) & priv->tx_ba_stream_tbl_ptr); for (i = 0; i < MAX_NUM_TID; ++i) { priv->aggr_prio_tbl[i].ampdu_ap = priv->aggr_prio_tbl[i].ampdu_user; } LEAVE(); } /** * @brief This function will return the pointer to a entry in BA Stream * table which matches the ba_status requested * * @param priv A pointer to mlan_private * @param ba_status Current status of the BA stream * * @return A pointer to first entry matching status in BA stream */ TxBAStreamTbl * wlan_11n_get_txbastream_status(mlan_private * priv, baStatus_e ba_status) { TxBAStreamTbl *ptx_tbl; ENTER(); if (! (ptx_tbl = (TxBAStreamTbl *) util_peek_list(priv->adapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, priv->adapter->callbacks. moal_spin_lock, priv->adapter->callbacks. moal_spin_unlock))) { LEAVE(); return MNULL; } while (ptx_tbl != (TxBAStreamTbl *) & priv->tx_ba_stream_tbl_ptr) { if (ptx_tbl->ba_status == ba_status) { LEAVE(); return ptx_tbl; } ptx_tbl = ptx_tbl->pnext; } LEAVE(); return MNULL; } /** * @brief This function will return the pointer to a entry in BA Stream * table which matches the give RA/TID pair * * @param priv A pointer to mlan_private * @param tid TID to find in reordering table * @param ra RA to find in reordering table * * @return A pointer to first entry matching RA/TID in BA stream */ TxBAStreamTbl * wlan_11n_get_txbastream_tbl(mlan_private * priv, int tid, t_u8 * ra) { TxBAStreamTbl *ptx_tbl; pmlan_adapter pmadapter = priv->adapter; ENTER(); if (!(ptx_tbl = (TxBAStreamTbl *) util_peek_list(pmadapter->pmoal_handle, &priv-> tx_ba_stream_tbl_ptr, pmadapter->callbacks. moal_spin_lock, pmadapter->callbacks. moal_spin_unlock))) { LEAVE(); return MNULL; } while (ptx_tbl != (TxBAStreamTbl *) & priv->tx_ba_stream_tbl_ptr) { PRINTM(MDAT_D, "get_txbastream_tbl TID %d\n", ptx_tbl->tid); DBG_HEXDUMP(MDAT_D, "RA", ptx_tbl->ra, MLAN_MAC_ADDR_LENGTH); if ((!memcmp(pmadapter, ptx_tbl->ra, ra, MLAN_MAC_ADDR_LENGTH)) && (ptx_tbl->tid == tid)) { LEAVE(); return ptx_tbl; } ptx_tbl = ptx_tbl->pnext; } LEAVE(); return MNULL; } /** * @brief This function will create a entry in tx ba stream table for the * given RA/TID. * * @param priv A pointer to mlan_private * @param ra RA to find in reordering table * @param tid TID to find in reordering table * @param ba_status BA stream status to create the stream with * * @return N/A */ void wlan_11n_create_txbastream_tbl(mlan_private * priv, t_u8 * ra, int tid, baStatus_e ba_status) { TxBAStreamTbl *newNode = MNULL; pmlan_adapter pmadapter = priv->adapter; ENTER(); if (!wlan_11n_get_txbastream_tbl(priv, tid, ra)) { PRINTM(MDAT_D, "get_txbastream_tbl TID %d", tid); DBG_HEXDUMP(MDAT_D, "RA", ra, MLAN_MAC_ADDR_LENGTH); pmadapter->callbacks.moal_malloc(pmadapter->pmoal_handle, sizeof(TxBAStreamTbl), MLAN_MEM_DEF, (t_u8 **) & newNode); util_init_list((pmlan_linked_list) newNode); newNode->tid = tid; newNode->ba_status = ba_status; memcpy(pmadapter, newNode->ra, ra, MLAN_MAC_ADDR_LENGTH); util_enqueue_list_tail(pmadapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, (pmlan_linked_list) newNode, pmadapter->callbacks.moal_spin_lock, pmadapter->callbacks.moal_spin_unlock); } LEAVE(); } /** * @brief This function will send a block ack to given tid/ra * * @param priv A pointer to mlan_private * @param tid TID to send the ADDBA * @param peer_mac MAC address to send the ADDBA * * @return MLAN_STATUS_SUCCESS or MLAN_STATUS_FAILURE */ int wlan_send_addba(mlan_private * priv, int tid, t_u8 * peer_mac) { HostCmd_DS_11N_ADDBA_REQ add_ba_req; static t_u8 dialog_tok; mlan_status ret; ENTER(); PRINTM(MCMND, "Send addba: TID %d\n", tid); DBG_HEXDUMP(MCMD_D, "Send addba RA", peer_mac, MLAN_MAC_ADDR_LENGTH); add_ba_req.block_ack_param_set = (t_u16) ((tid << BLOCKACKPARAM_TID_POS) | (priv->add_ba_param.tx_win_size << BLOCKACKPARAM_WINSIZE_POS) | IMMEDIATE_BLOCK_ACK); add_ba_req.block_ack_tmo = (t_u16) priv->add_ba_param.timeout; ++dialog_tok; if (dialog_tok == 0) dialog_tok = 1; add_ba_req.dialog_token = dialog_tok; memcpy(priv->adapter, &add_ba_req.peer_mac_addr, peer_mac, MLAN_MAC_ADDR_LENGTH); /* We don't wait for the response of this command */ ret = wlan_prepare_cmd(priv, HostCmd_CMD_11N_ADDBA_REQ, 0, 0, MNULL, &add_ba_req); LEAVE(); return ret; } /** * @brief This function will delete a block ack to given tid/ra * * @param priv A pointer to mlan_private * @param tid TID to send the ADDBA * @param peer_mac MAC address to send the ADDBA * @param initiator MTRUE if we have initiated ADDBA, MFALSE otherwise * * @return MLAN_STATUS_SUCCESS or MLAN_STATUS_FAILURE */ int wlan_send_delba(mlan_private * priv, int tid, t_u8 * peer_mac, int initiator) { HostCmd_DS_11N_DELBA delba; mlan_status ret; ENTER(); memset(priv->adapter, &delba, 0, sizeof(delba)); delba.del_ba_param_set = (tid << DELBA_TID_POS); if (initiator) DELBA_INITIATOR(delba.del_ba_param_set); else DELBA_RECIPIENT(delba.del_ba_param_set); memcpy(priv->adapter, &delba.peer_mac_addr, peer_mac, MLAN_MAC_ADDR_LENGTH); /* We don't wait for the response of this command */ ret = wlan_prepare_cmd(priv, HostCmd_CMD_11N_DELBA, HostCmd_ACT_GEN_SET, 0, MNULL, &delba); LEAVE(); return ret; } /** * @brief This function handles the command response of * delete a block ack request * * @param priv A pointer to mlan_private structure * @param del_ba A pointer to command response buffer * * @return N/A */ void wlan_11n_delete_bastream(mlan_private * priv, t_u8 * del_ba) { HostCmd_DS_11N_DELBA *pdel_ba = (HostCmd_DS_11N_DELBA *) del_ba; int tid; ENTER(); DBG_HEXDUMP(MCMD_D, "Delba:", (t_u8 *) pdel_ba, 20); pdel_ba->del_ba_param_set = wlan_le16_to_cpu(pdel_ba->del_ba_param_set); pdel_ba->reason_code = wlan_le16_to_cpu(pdel_ba->reason_code); tid = pdel_ba->del_ba_param_set >> DELBA_TID_POS; mlan_11n_delete_bastream_tbl(priv, tid, pdel_ba->peer_mac_addr, TYPE_DELBA_RECEIVE, INITIATOR_BIT(pdel_ba->del_ba_param_set)); LEAVE(); } /** * @brief This function will resend addba request to all * the peer in the TxBAStreamTbl * * @param priv A pointer to mlan_private * * @return N/A */ void wlan_11n_update_addba_request(mlan_private * priv) { TxBAStreamTbl *ptx_tbl; ENTER(); if (! (ptx_tbl = (TxBAStreamTbl *) util_peek_list(priv->adapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, priv->adapter->callbacks. moal_spin_lock, priv->adapter->callbacks. moal_spin_unlock))) { LEAVE(); return; } while (ptx_tbl != (TxBAStreamTbl *) & priv->tx_ba_stream_tbl_ptr) { wlan_send_addba(priv, ptx_tbl->tid, ptx_tbl->ra); ptx_tbl = ptx_tbl->pnext; } mlan_main_process(priv->adapter); LEAVE(); return; } /** * @brief Get Rx reordering table * * @param priv A pointer to mlan_private structure * @param buf A pointer to rx_reorder_tbl structure * @return number of rx reorder table entry */ int wlan_get_rxreorder_tbl(mlan_private * priv, rx_reorder_tbl * buf) { int i; rx_reorder_tbl *ptbl = buf; RxReorderTbl *rxReorderTblPtr; int count = 0; ENTER(); if (! (rxReorderTblPtr = (RxReorderTbl *) util_peek_list(priv->adapter->pmoal_handle, &priv->rx_reorder_tbl_ptr, priv->adapter->callbacks. moal_spin_lock, priv->adapter->callbacks. moal_spin_unlock))) { LEAVE(); return count; } while (rxReorderTblPtr != (RxReorderTbl *) & priv->rx_reorder_tbl_ptr) { ptbl->tid = (t_u16) rxReorderTblPtr->tid; memcpy(priv->adapter, ptbl->ta, rxReorderTblPtr->ta, MLAN_MAC_ADDR_LENGTH); ptbl->start_win = rxReorderTblPtr->start_win; ptbl->win_size = rxReorderTblPtr->win_size; for (i = 0; i < rxReorderTblPtr->win_size; ++i) { if (rxReorderTblPtr->rx_reorder_ptr[i]) ptbl->buffer[i] = MTRUE; else ptbl->buffer[i] = MFALSE; } rxReorderTblPtr = rxReorderTblPtr->pnext; ptbl++; count++; if (count >= MLAN_MAX_RX_BASTREAM_SUPPORTED) break; } LEAVE(); return count; } /** * @brief Get transmit BA stream table * * @param priv A pointer to mlan_private structure * @param buf A pointer to tx_ba_stream_tbl structure * @return number of ba stream table entry */ int wlan_get_txbastream_tbl(mlan_private * priv, tx_ba_stream_tbl * buf) { TxBAStreamTbl *ptxtbl; tx_ba_stream_tbl *ptbl = buf; int count = 0; ENTER(); if (!(ptxtbl = (TxBAStreamTbl *) util_peek_list(priv->adapter->pmoal_handle, &priv->tx_ba_stream_tbl_ptr, priv->adapter->callbacks. moal_spin_lock, priv->adapter->callbacks. moal_spin_unlock))) { LEAVE(); return count; } while (ptxtbl != (TxBAStreamTbl *) & priv->tx_ba_stream_tbl_ptr) { ptbl->tid = (t_u16) ptxtbl->tid; PRINTM(MINFO, "tid=%d\n", ptbl->tid); memcpy(priv->adapter, ptbl->ra, ptxtbl->ra, MLAN_MAC_ADDR_LENGTH); ptxtbl = ptxtbl->pnext; ptbl++; count++; if (count >= MLAN_MAX_TX_BASTREAM_SUPPORTED) break; } LEAVE(); return count; } #ifdef UAP_SUPPORT /** * @brief This function cleans up txbastream_tbl for specific station * * @param priv A pointer to mlan_private * @param ra RA to find in txbastream_tbl * @return N/A */ void wlan_uap_11n_cleanup_txbastream_tbl(mlan_private * priv, t_u8 * ra) { TxBAStreamTbl *ptx_tbl = MNULL; t_u8 i; ENTER(); for (i = 0; i < MAX_NUM_TID; ++i) { if ((ptx_tbl = wlan_11n_get_txbastream_tbl(priv, i, ra))) { wlan_11n_delete_txbastream_tbl_entry(priv, ptx_tbl); } } LEAVE(); return; } #endif /* UAP_SUPPORT */
uplusplus/ls300_smdkc110
drivers/net/wireless/w8787/wlan_src/mlan/mlan_11n.c
C
gpl-2.0
49,979
[ 30522, 1013, 1008, 1008, 1030, 5371, 18619, 2078, 1035, 2340, 2078, 1012, 1039, 1008, 1008, 1030, 4766, 2023, 5371, 3397, 4972, 2005, 2340, 2078, 8304, 1012, 1008, 1008, 9385, 1006, 1039, 1007, 2263, 1011, 2230, 1010, 8348, 2140, 2248, 51...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <title>Blog Randson</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <style type="text/css">@import url(//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css);</style> <link href='//fonts.googleapis.com/css?family=Roboto:400,300,500' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="styles/main.css"> <script src="scripts/vendor/modernizr.js"></script> </head> <body> <!--[if lt IE 10]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div id="hubpress"></div> <script src="scripts/vendor.js?v=0.3.0"></script> <script src="scripts/app.js?v=0.3.0"></script> </body> </html>
randhson/Blog
hubpress/index.html
HTML
mit
1,463
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 999, 1011, 1011, 1031, 2065, 8318, 29464, 1021, 1033, 1028, 1026, 16129, 2465, 1027, 1000, 2053, 1011, 1046, 2015, 8318, 1011, 29464, 2683, 8318, 1011, 29464, 2620, 8318, 1011, 29464, 2581, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { /** * @Route("/", name="homepage") * @Template */ public function indexAction(Request $request) { return $this->getHostInfo(); } /** * @Route("/cached", name="cached") * @Template("AppBundle:Default:index.html.twig") * @Cache(smaxage=3600) */ public function cachedAction(Request $request) { return $this->getHostInfo(); } /** * @Route("/keepalive", name="keepalive") */ public function keepalveAction() { if(file_exists(__DIR__ . '/../../../app/lock/keepalive.lock')) { return new Response("Unavailable", 503); } return new Response("Ok", 200); } private function getHostInfo() { return [ 'hostname' => $host = gethostname(), 'ip' => exec( "ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'" ), 'load_avg' => sys_getloadavg() ]; } }
ibrows/symfony-ha-example-app
src/AppBundle/Controller/DefaultController.php
PHP
mit
1,451
[ 30522, 1026, 1029, 25718, 3415, 15327, 10439, 27265, 2571, 1032, 11486, 1025, 2224, 12411, 20763, 1032, 14012, 1032, 7705, 10288, 6494, 27265, 2571, 1032, 9563, 1032, 2799, 1025, 2224, 12411, 20763, 1032, 14012, 1032, 7705, 10288, 6494, 27265...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * C++ Primer * Chap. 9 Ex. 9.18 * Hao Zhang * 2016.09.17 * main.cpp */ #include <deque> using std::deque; #include <string> using std::string; #include <iostream> using std::cout; using std::endl; using std::cin; int main() { deque<string> deq; string val; while (cin >> val) { deq.push_back(val); } for (auto iter = deq.cbegin(); iter != deq.cend(); ++iter) { cout << *iter << " "; } cout << endl; return 0; }
HaoMood/cpp-primer
ch09/ex9.18/main.cpp
C++
gpl-3.0
473
[ 30522, 1013, 1008, 1008, 1039, 1009, 1009, 3539, 2099, 1008, 15775, 2361, 1012, 1023, 4654, 1012, 1023, 1012, 2324, 1008, 5292, 2080, 9327, 1008, 2355, 1012, 5641, 1012, 2459, 1008, 2364, 1012, 18133, 2361, 1008, 1013, 1001, 2421, 1026, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module.exports={A:{A:{"2":"L H G E A B jB"},B:{"2":"8 C D e K I N J"},C:{"2":"0 1 2 3 4 5 7 9 gB BB F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB aB ZB"},D:{"2":"0 1 2 3 4 5 7 8 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB"},E:{"1":"6 E A B C D XB YB p bB","2":"4 F L H G SB KB UB VB WB"},F:{"2":"0 1 2 3 5 6 7 E B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z cB dB eB fB p AB hB"},G:{"1":"D oB pB qB rB sB tB uB vB","2":"G KB iB FB kB lB MB nB"},H:{"2":"wB"},I:{"2":"BB F O xB yB zB 0B FB 1B 2B"},J:{"2":"H A"},K:{"2":"6 A B C M p AB"},L:{"2":"LB"},M:{"2":"O"},N:{"2":"A B"},O:{"2":"3B"},P:{"2":"F 4B 5B 6B 7B 8B"},Q:{"2":"9B"},R:{"2":"AC"},S:{"2":"BC"}},B:7,C:"selector list argument of :nth-child and :nth-last-child CSS pseudo-classes"};
Dans-labs/dariah
client/node_modules/caniuse-lite/data/features/css-nth-child-of.js
JavaScript
mit
960
[ 30522, 11336, 1012, 14338, 1027, 1063, 1037, 1024, 1063, 1037, 1024, 1063, 1000, 1016, 1000, 1024, 1000, 1048, 1044, 1043, 1041, 1037, 1038, 1046, 2497, 1000, 1065, 1010, 1038, 1024, 1063, 1000, 1016, 1000, 1024, 1000, 1022, 1039, 1040, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include "stdafx.h" #include "NET_Common.h" #include "net_client.h" #include "net_server.h" #include "net_messages.h" #include "NET_Log.h" #include "../xr_3da/xrGame/battleye.h" #pragma warning(push) #pragma warning(disable:4995) #include <malloc.h> #include "dxerr.h" //#pragma warning(pop) static INetLog* pClNetLog = NULL; #define BASE_PORT_LAN_SV 5445 #define BASE_PORT_LAN_CL 5446 #define BASE_PORT 0 #define END_PORT 65535 void dump_URL (LPCSTR p, IDirectPlay8Address* A) { string256 aaaa; DWORD aaaa_s = sizeof(aaaa); R_CHK (A->GetURLA(aaaa,&aaaa_s)); Log (p,aaaa); } // INetQueue::INetQueue() #ifdef PROFILE_CRITICAL_SECTIONS :cs(MUTEX_PROFILE_ID(INetQueue)) #endif // PROFILE_CRITICAL_SECTIONS { unused.reserve (128); for (int i=0; i<16; i++) unused.push_back (xr_new<NET_Packet>()); } INetQueue::~INetQueue() { cs.Enter (); u32 it; for (it=0; it<unused.size(); it++) xr_delete(unused[it]); for (it=0; it<ready.size(); it++) xr_delete(ready[it]); cs.Leave (); } static u32 LastTimeCreate = 0; void INetQueue::CreateCommit(NET_Packet* P) { cs.Enter (); ready.push_back (P); cs.Leave (); } NET_Packet* INetQueue::CreateGet() { NET_Packet* P = 0; cs.Enter (); if (unused.empty()) { P = xr_new<NET_Packet> (); //. ready.push_back (xr_new<NET_Packet> ()); //. P = ready.back (); LastTimeCreate = GetTickCount(); } else { P = unused.back(); //. ready.push_back (unused.back()); unused.pop_back (); //. P = ready.back (); } cs.Leave (); return P; } /* NET_Packet* INetQueue::Create (const NET_Packet& _other) { NET_Packet* P = 0; cs.Enter (); //#ifdef _DEBUG // Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); //#endif if (unused.empty()) { ready.push_back (xr_new<NET_Packet> ()); P = ready.back (); //--------------------------------------------- LastTimeCreate = GetTickCount(); //--------------------------------------------- } else { ready.push_back (unused.back()); unused.pop_back (); P = ready.back (); } CopyMemory (P,&_other,sizeof(NET_Packet)); cs.Leave (); return P; } */ NET_Packet* INetQueue::Retreive () { NET_Packet* P = 0; cs.Enter (); //#ifdef _DEBUG // Msg ("INetQueue::Retreive - ready %d, unused %d", ready.size(), unused.size()); //#endif if (!ready.empty()) P = ready.front(); //--------------------------------------------- else { u32 tmp_time = GetTickCount()-60000; u32 size = unused.size(); if ((LastTimeCreate < tmp_time) && (size > 32)) { xr_delete(unused.back()); unused.pop_back(); } } //--------------------------------------------- cs.Leave (); return P; } void INetQueue::Release () { cs.Enter (); //#ifdef _DEBUG // Msg ("INetQueue::Release - ready %d, unused %d", ready.size(), unused.size()); //#endif VERIFY (!ready.empty()); //--------------------------------------------- u32 tmp_time = GetTickCount()-60000; u32 size = unused.size(); if ((LastTimeCreate < tmp_time) && (size > 32)) { xr_delete(ready.front()); } else unused.push_back(ready.front()); //--------------------------------------------- ready.pop_front (); cs.Leave (); } // const u32 syncQueueSize = 512; const int syncSamples = 256; class XRNETSERVER_API syncQueue { u32 table [syncQueueSize]; u32 write; u32 count; public: syncQueue() { clear(); } IC void push (u32 value) { table[write++] = value; if (write == syncQueueSize) write = 0; if (count <= syncQueueSize) count++; } IC u32* begin () { return table; } IC u32* end () { return table+count; } IC u32 size () { return count; } IC void clear () { write=0; count=0; } } net_DeltaArray; //------- XRNETSERVER_API Flags32 psNET_Flags = {0}; XRNETSERVER_API int psNET_ClientUpdate = 30; // FPS XRNETSERVER_API int psNET_ClientPending = 2; XRNETSERVER_API char psNET_Name[32] = "Player"; XRNETSERVER_API BOOL psNET_direct_connect = FALSE; // {0218FA8B-515B-4bf2-9A5F-2F079D1759F3} static const GUID NET_GUID = { 0x218fa8b, 0x515b, 0x4bf2, { 0x9a, 0x5f, 0x2f, 0x7, 0x9d, 0x17, 0x59, 0xf3 } }; // {8D3F9E5E-A3BD-475b-9E49-B0E77139143C} static const GUID CLSID_NETWORKSIMULATOR_DP8SP_TCPIP = { 0x8d3f9e5e, 0xa3bd, 0x475b, { 0x9e, 0x49, 0xb0, 0xe7, 0x71, 0x39, 0x14, 0x3c } }; static HRESULT WINAPI Handler (PVOID pvUserContext, DWORD dwMessageType, PVOID pMessage) { IPureClient* C = (IPureClient*)pvUserContext; return C->net_Handler(dwMessageType,pMessage); } //------------------------------------------------------------------------------ void IPureClient::_SendTo_LL( const void* data, u32 size, u32 flags, u32 timeout ) { IPureClient::SendTo_LL( const_cast<void*>(data), size, flags, timeout ); } //------------------------------------------------------------------------------ void IPureClient::_Recieve( const void* data, u32 data_size, u32 /*param*/ ) { MSYS_PING* cfg = (MSYS_PING*)data; if( (data_size>2*sizeof(u32)) && (cfg->sign1==0x12071980) && (cfg->sign2==0x26111975) ) { // Internal system message if( (data_size == sizeof(MSYS_PING)) ) { // It is reverted(server) ping u32 time = TimerAsync( device_timer ); u32 ping = time - (cfg->dwTime_ClientSend); u32 delta = cfg->dwTime_Server + ping/2 - time; net_DeltaArray.push ( delta ); Sync_Average (); return; } if ( data_size == sizeof(MSYS_CONFIG) ) { MSYS_CONFIG* msys_cfg = (MSYS_CONFIG*)data; if ( msys_cfg->is_battleye ) { #ifdef BATTLEYE if ( !TestLoadBEClient() ) { net_Connected = EnmConnectionFails; return; } #endif // BATTLEYE } net_Connected = EnmConnectionCompleted; return; } Msg( "! Unknown system message" ); return; } else if( net_Connected == EnmConnectionCompleted ) { // one of the messages - decompress it if( psNET_Flags.test( NETFLAG_LOG_CL_PACKETS ) ) { if( !pClNetLog ) pClNetLog = xr_new<INetLog>("logs\\net_cl_log.log", timeServer()); if( pClNetLog ) pClNetLog->LogData( timeServer(), const_cast<void*>(data), data_size, TRUE ); } OnMessage( const_cast<void*>(data), data_size ); } } //============================================================================== IPureClient::IPureClient (CTimer* timer): net_Statistic(timer) #ifdef PROFILE_CRITICAL_SECTIONS ,net_csEnumeration(MUTEX_PROFILE_ID(IPureClient::net_csEnumeration)) #endif // PROFILE_CRITICAL_SECTIONS { NET = NULL; net_Address_server = NULL; net_Address_device = NULL; device_timer = timer; net_TimeDelta_User = 0; net_Time_LastUpdate = 0; net_TimeDelta = 0; net_TimeDelta_Calculated = 0; pClNetLog = NULL;//xr_new<INetLog>("logs\\net_cl_log.log", timeServer()); } IPureClient::~IPureClient () { xr_delete(pClNetLog); pClNetLog = NULL; psNET_direct_connect = FALSE; } void gen_auth_code(); BOOL IPureClient::Connect (LPCSTR options) { R_ASSERT (options); net_Disconnected = FALSE; if(!psNET_direct_connect && !strstr(options,"localhost") ) { gen_auth_code (); } if(!psNET_direct_connect) { // string256 server_name = ""; // strcpy (server_name,options); if (strchr(options, '/')) strncpy(server_name,options, strchr(options, '/')-options); if (strchr(server_name,'/')) *strchr(server_name,'/') = 0; string64 password_str = ""; if (strstr(options, "psw=")) { const char* PSW = strstr(options, "psw=") + 4; if (strchr(PSW, '/')) strncpy(password_str, PSW, strchr(PSW, '/') - PSW); else strcpy(password_str, PSW); } string64 user_name_str = ""; if (strstr(options, "name=")) { const char* NM = strstr(options, "name=") + 5; if (strchr(NM, '/')) strncpy(user_name_str, NM, strchr(NM, '/') - NM); else strcpy(user_name_str, NM); } string64 user_pass = ""; if (strstr(options, "pass=")) { const char* UP = strstr(options, "pass=") + 5; if (strchr(UP, '/')) strncpy(user_pass, UP, strchr(UP, '/') - UP); else strcpy(user_pass, UP); } int psSV_Port = BASE_PORT_LAN_SV; if (strstr(options, "port=")) { string64 portstr; strcpy(portstr, strstr(options, "port=")+5); if (strchr(portstr,'/')) *strchr(portstr,'/') = 0; psSV_Port = atol(portstr); clamp(psSV_Port, int(BASE_PORT), int(END_PORT)); }; BOOL bPortWasSet = FALSE; int psCL_Port = BASE_PORT_LAN_CL; if (strstr(options, "portcl=")) { string64 portstr; strcpy(portstr, strstr(options, "portcl=")+7); if (strchr(portstr,'/')) *strchr(portstr,'/') = 0; psCL_Port = atol(portstr); clamp(psCL_Port, int(BASE_PORT), int(END_PORT)); bPortWasSet = TRUE; }; // Msg("* Client connect on port %d\n",psNET_Port); // net_Connected = EnmConnectionWait; net_Syncronised = FALSE; net_Disconnected= FALSE; //--------------------------- string1024 tmp=""; // HRESULT CoInitializeExRes = CoInitializeEx(NULL, 0); // if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE) // { // DXTRACE_ERR(tmp, CoInitializeExRes); // CHK_DX(CoInitializeExRes); // }; //--------------------------- // Create the IDirectPlay8Client object. HRESULT CoCreateInstanceRes = CoCreateInstance (CLSID_DirectPlay8Client, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Client, (LPVOID*) &NET); //--------------------------- if (CoCreateInstanceRes != S_OK) { DXTRACE_ERR(tmp, CoCreateInstanceRes ); CHK_DX(CoCreateInstanceRes ); } //--------------------------- // Initialize IDirectPlay8Client object. #ifdef DEBUG R_CHK(NET->Initialize (this, Handler, 0)); #else R_CHK(NET->Initialize (this, Handler, DPNINITIALIZE_DISABLEPARAMVAL )); #endif BOOL bSimulator = FALSE; if (strstr(Core.Params,"-netsim")) bSimulator = TRUE; // Create our IDirectPlay8Address Device Address, --- Set the SP for our Device Address net_Address_device = NULL; R_CHK(CoCreateInstance (CLSID_DirectPlay8Address,NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address,(LPVOID*) &net_Address_device )); R_CHK(net_Address_device->SetSP(bSimulator? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP )); // Create our IDirectPlay8Address Server Address, --- Set the SP for our Server Address WCHAR ServerNameUNICODE [256]; R_CHK(MultiByteToWideChar(CP_ACP, 0, server_name, -1, ServerNameUNICODE, 256 )); net_Address_server = NULL; R_CHK(CoCreateInstance (CLSID_DirectPlay8Address,NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address,(LPVOID*) &net_Address_server )); R_CHK(net_Address_server->SetSP (bSimulator? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP )); R_CHK(net_Address_server->AddComponent (DPNA_KEY_HOSTNAME, ServerNameUNICODE, 2*u32(wcslen(ServerNameUNICODE) + 1), DPNA_DATATYPE_STRING )); R_CHK(net_Address_server->AddComponent (DPNA_KEY_PORT, &psSV_Port, sizeof(psSV_Port), DPNA_DATATYPE_DWORD )); // Debug // dump_URL ("! cl ", net_Address_device); // dump_URL ("! en ", net_Address_server); // Now set up the Application Description DPN_APPLICATION_DESC dpAppDesc; ZeroMemory (&dpAppDesc, sizeof(DPN_APPLICATION_DESC)); dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC); dpAppDesc.guidApplication = NET_GUID; // Setup client info /*strcpy_s( tmp, server_name ); strcat_s( tmp, "/name=" ); strcat_s( tmp, user_name_str ); strcat_s( tmp, "/" );*/ WCHAR ClientNameUNICODE [256]; R_CHK(MultiByteToWideChar (CP_ACP, 0, user_name_str, -1, ClientNameUNICODE, 256 )); { DPN_PLAYER_INFO Pinfo; ZeroMemory (&Pinfo,sizeof(Pinfo)); Pinfo.dwSize = sizeof(Pinfo); Pinfo.dwInfoFlags = DPNINFO_NAME|DPNINFO_DATA; Pinfo.pwszName = ClientNameUNICODE; SClientConnectData cl_data; cl_data.process_id = GetCurrentProcessId(); strcpy_s( cl_data.name, user_name_str ); strcpy_s( cl_data.pass, user_pass ); Pinfo.pvData = &cl_data; Pinfo.dwDataSize = sizeof(cl_data); R_CHK(NET->SetClientInfo (&Pinfo,0,0,DPNSETCLIENTINFO_SYNC)); } if ( stricmp( server_name, "localhost" ) == 0 ) { WCHAR SessionPasswordUNICODE[4096]; if ( xr_strlen( password_str ) ) { CHK_DX(MultiByteToWideChar (CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096 )); dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; dpAppDesc.pwszPassword = SessionPasswordUNICODE; }; u32 c_port = u32(psCL_Port); HRESULT res = S_FALSE; while (res != S_OK && c_port <=u32(psCL_Port+100)) { R_CHK(net_Address_device->AddComponent (DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD )); res = NET->Connect( &dpAppDesc, // pdnAppDesc net_Address_server, // pHostAddr net_Address_device, // pDeviceInfo NULL, // pdnSecurity NULL, // pdnCredentials NULL, 0, // pvUserConnectData/Size NULL, // pvAsyncContext NULL, // pvAsyncHandle DPNCONNECT_SYNC); // dwFlags if (res != S_OK) { // xr_string res = Debug.error2string(HostSuccess); if (bPortWasSet) { Msg("! IPureClient : port %d is BUSY!", c_port); return FALSE; } #ifdef DEBUG else Msg("! IPureClient : port %d is BUSY!", c_port); #endif c_port++; } else { Msg("- IPureClient : created on port %d!", c_port); } }; // R_CHK(res); if (res != S_OK) return FALSE; // Create ONE node HOST_NODE NODE; ZeroMemory (&NODE, sizeof(HOST_NODE)); // Copy the Host Address R_CHK (net_Address_server->Duplicate(&NODE.pHostAddress ) ); // Retreive session name char desc[4096]; ZeroMemory (desc,sizeof(desc)); DPN_APPLICATION_DESC* dpServerDesc=(DPN_APPLICATION_DESC*)desc; DWORD dpServerDescSize=sizeof(desc); dpServerDesc->dwSize = sizeof(DPN_APPLICATION_DESC); R_CHK (NET->GetApplicationDesc(dpServerDesc,&dpServerDescSize,0)); if( dpServerDesc->pwszSessionName) { string4096 dpSessionName; R_CHK(WideCharToMultiByte(CP_ACP,0,dpServerDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0)); NODE.dpSessionName = (char*)(&dpSessionName[0]); } net_Hosts.push_back (NODE); } else { string64 EnumData; EnumData[0] = 0; strcat (EnumData, "ToConnect"); DWORD EnumSize = xr_strlen(EnumData) + 1; // We now have the host address so lets enum u32 c_port = psCL_Port; HRESULT res = S_FALSE; while (res != S_OK && c_port <=END_PORT) { R_CHK(net_Address_device->AddComponent (DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD )); res = NET->EnumHosts( &dpAppDesc, // pApplicationDesc net_Address_server, // pdpaddrHost net_Address_device, // pdpaddrDeviceInfo EnumData, EnumSize, // pvUserEnumData, size 10, // dwEnumCount 1000, // dwRetryInterval 1000, // dwTimeOut NULL, // pvUserContext NULL, // pAsyncHandle DPNENUMHOSTS_SYNC // dwFlags ); if (res != S_OK) { // xr_string res = Debug.error2string(HostSuccess); switch (res) { case DPNERR_INVALIDHOSTADDRESS: { OnInvalidHost(); return FALSE; }break; case DPNERR_SESSIONFULL: { OnSessionFull(); return FALSE; }break; }; if (bPortWasSet) { Msg("! IPureClient : port %d is BUSY!", c_port); return FALSE; } #ifdef DEBUG else Msg("! IPureClient : port %d is BUSY!", c_port); // const char* x = DXGetErrorString9(res); string1024 tmp = ""; DXTRACE_ERR(tmp, res); #endif c_port++; } else { Msg("- IPureClient : created on port %d!", c_port); } }; // ****** Connection IDirectPlay8Address* pHostAddress = NULL; if (net_Hosts.empty()) { OnInvalidHost(); return FALSE; }; WCHAR SessionPasswordUNICODE[4096]; if ( xr_strlen( password_str) ) { CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096 )); dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; dpAppDesc.pwszPassword = SessionPasswordUNICODE; }; net_csEnumeration.Enter (); // real connect for (u32 I=0; I<net_Hosts.size(); I++) Msg("* HOST #%d: %s\n",I+1,*net_Hosts[I].dpSessionName); R_CHK(net_Hosts.front().pHostAddress->Duplicate(&pHostAddress ) ); // dump_URL ("! c2s ", pHostAddress); res = NET->Connect( &dpAppDesc, // pdnAppDesc pHostAddress, // pHostAddr net_Address_device, // pDeviceInfo NULL, // pdnSecurity NULL, // pdnCredentials NULL, 0, // pvUserConnectData/Size NULL, // pvAsyncContext NULL, // pvAsyncHandle DPNCONNECT_SYNC); // dwFlags // R_CHK(res); net_csEnumeration.Leave (); _RELEASE (pHostAddress); #ifdef DEBUG // const char* x = DXGetErrorString9(res); string1024 tmp = ""; DXTRACE_ERR(tmp, res); #endif switch (res) { case DPNERR_INVALIDPASSWORD: { OnInvalidPassword(); }break; case DPNERR_SESSIONFULL: { OnSessionFull(); }break; case DPNERR_CANTCREATEPLAYER: { Msg("! Error: Can\'t create player"); }break; } if (res != S_OK) return FALSE; } // Caps /* GUID sp_guid; DPN_SP_CAPS sp_caps; net_Address_device->GetSP(&sp_guid); ZeroMemory (&sp_caps,sizeof(sp_caps)); sp_caps.dwSize = sizeof(sp_caps); R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); sp_caps.dwSystemBufferSize = 0; R_CHK (NET->SetSPCaps(&sp_guid,&sp_caps,0)); R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); */ } //psNET_direct_connect // Sync net_TimeDelta = 0; return TRUE; } void IPureClient::Disconnect() { if( NET ) NET->Close(0); // Clean up Host _list_ net_csEnumeration.Enter (); for (u32 i=0; i<net_Hosts.size(); i++) { HOST_NODE& N = net_Hosts[i]; _RELEASE (N.pHostAddress); } net_Hosts.clear (); net_csEnumeration.Leave (); // Release interfaces _SHOW_REF ("cl_netADR_Server",net_Address_server); _RELEASE (net_Address_server); _SHOW_REF ("cl_netADR_Device",net_Address_device); _RELEASE (net_Address_device); _SHOW_REF ("cl_netCORE",NET); _RELEASE (NET); net_Connected = EnmConnectionWait; net_Syncronised = FALSE; } HRESULT IPureClient::net_Handler(u32 dwMessageType, PVOID pMessage) { // HRESULT hr = S_OK; switch (dwMessageType) { case DPN_MSGID_ENUM_HOSTS_RESPONSE: { PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponseMsg; const DPN_APPLICATION_DESC* pDesc; // HOST_NODE* pHostNode = NULL; // WCHAR* pwszSession = NULL; pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE) pMessage; pDesc = pEnumHostsResponseMsg->pApplicationDescription; // Insert each host response if it isn't already present net_csEnumeration.Enter (); BOOL bHostRegistered = FALSE; for (u32 I=0; I<net_Hosts.size(); I++) { HOST_NODE& N = net_Hosts [I]; if ( pDesc->guidInstance == N.dpAppDesc.guidInstance) { // This host is already in the list bHostRegistered = TRUE; break; } } if (!bHostRegistered) { // This host session is not in the list then so insert it. HOST_NODE NODE; ZeroMemory (&NODE, sizeof(HOST_NODE)); // Copy the Host Address R_CHK (pEnumHostsResponseMsg->pAddressSender->Duplicate(&NODE.pHostAddress ) ); CopyMemory(&NODE.dpAppDesc,pDesc,sizeof(DPN_APPLICATION_DESC)); // Null out all the pointers we aren't copying NODE.dpAppDesc.pwszSessionName = NULL; NODE.dpAppDesc.pwszPassword = NULL; NODE.dpAppDesc.pvReservedData = NULL; NODE.dpAppDesc.dwReservedDataSize = 0; NODE.dpAppDesc.pvApplicationReservedData = NULL; NODE.dpAppDesc.dwApplicationReservedDataSize = 0; if( pDesc->pwszSessionName) { string4096 dpSessionName; R_CHK (WideCharToMultiByte(CP_ACP,0,pDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0)); NODE.dpSessionName = (char*)(&dpSessionName[0]); } net_Hosts.push_back (NODE); } net_csEnumeration.Leave (); } break; case DPN_MSGID_RECEIVE: { PDPNMSG_RECEIVE pMsg = (PDPNMSG_RECEIVE) pMessage; MultipacketReciever::RecievePacket( pMsg->pReceiveData, pMsg->dwReceiveDataSize ); } break; case DPN_MSGID_TERMINATE_SESSION: { PDPNMSG_TERMINATE_SESSION pMsg = (PDPNMSG_TERMINATE_SESSION ) pMessage; char* m_data = (char*)pMsg->pvTerminateData; u32 m_size = pMsg->dwTerminateDataSize; HRESULT m_hResultCode = pMsg->hResultCode; net_Disconnected = TRUE; if (m_size != 0) { OnSessionTerminate(m_data); //Msg("- Session terminated : %s", m_data); } else { OnSessionTerminate( (::Debug.error2string(m_hResultCode))); //Msg("- Session terminated : %s", (::Debug.error2string(m_hResultCode))); } }; break; default: { #if 1 LPSTR msg = ""; switch (dwMessageType) { case DPN_MSGID_ADD_PLAYER_TO_GROUP: msg = "DPN_MSGID_ADD_PLAYER_TO_GROUP"; break; case DPN_MSGID_ASYNC_OP_COMPLETE: msg = "DPN_MSGID_ASYNC_OP_COMPLETE"; break; case DPN_MSGID_CLIENT_INFO: msg = "DPN_MSGID_CLIENT_INFO"; break; case DPN_MSGID_CONNECT_COMPLETE: { PDPNMSG_CONNECT_COMPLETE pMsg = (PDPNMSG_CONNECT_COMPLETE)pMessage; #ifdef DEBUG // const char* x = DXGetErrorString9(pMsg->hResultCode); if (pMsg->hResultCode != S_OK) { string1024 tmp=""; DXTRACE_ERR(tmp, pMsg->hResultCode); } #endif if (pMsg->dwApplicationReplyDataSize) { string256 ResStr = ""; strncpy(ResStr, (char*)(pMsg->pvApplicationReplyData), pMsg->dwApplicationReplyDataSize); Msg("Connection result : %s", ResStr); } else msg = "DPN_MSGID_CONNECT_COMPLETE"; }break; case DPN_MSGID_CREATE_GROUP: msg = "DPN_MSGID_CREATE_GROUP"; break; case DPN_MSGID_CREATE_PLAYER: msg = "DPN_MSGID_CREATE_PLAYER"; break; case DPN_MSGID_DESTROY_GROUP: msg = "DPN_MSGID_DESTROY_GROUP"; break; case DPN_MSGID_DESTROY_PLAYER: msg = "DPN_MSGID_DESTROY_PLAYER"; break; case DPN_MSGID_ENUM_HOSTS_QUERY: msg = "DPN_MSGID_ENUM_HOSTS_QUERY"; break; case DPN_MSGID_GROUP_INFO: msg = "DPN_MSGID_GROUP_INFO"; break; case DPN_MSGID_HOST_MIGRATE: msg = "DPN_MSGID_HOST_MIGRATE"; break; case DPN_MSGID_INDICATE_CONNECT: msg = "DPN_MSGID_INDICATE_CONNECT"; break; case DPN_MSGID_INDICATED_CONNECT_ABORTED: msg = "DPN_MSGID_INDICATED_CONNECT_ABORTED"; break; case DPN_MSGID_PEER_INFO: msg = "DPN_MSGID_PEER_INFO"; break; case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP: msg = "DPN_MSGID_REMOVE_PLAYER_FROM_GROUP"; break; case DPN_MSGID_RETURN_BUFFER: msg = "DPN_MSGID_RETURN_BUFFER"; break; case DPN_MSGID_SEND_COMPLETE: msg = "DPN_MSGID_SEND_COMPLETE"; break; case DPN_MSGID_SERVER_INFO: msg = "DPN_MSGID_SERVER_INFO"; break; case DPN_MSGID_TERMINATE_SESSION: msg = "DPN_MSGID_TERMINATE_SESSION"; break; default: msg = "???"; break; } //Msg("! ************************************ : %s",msg); #endif } break; } return S_OK; } void IPureClient::OnMessage(void* data, u32 size) { // One of the messages - decompress it NET_Packet* P = net_Queue.CreateGet(); P->construct (data, size); P->timeReceive = timeServer_Async(); u16 tmp_type; P->r_begin (tmp_type); net_Queue.CreateCommit (P); } void IPureClient::timeServer_Correct(u32 sv_time, u32 cl_time) { u32 ping = net_Statistic.getPing(); u32 delta = sv_time + ping/2 - cl_time; net_DeltaArray.push (delta); Sync_Average (); } void IPureClient::SendTo_LL(void* data, u32 size, u32 dwFlags, u32 dwTimeout) { if( net_Disconnected ) return; if( psNET_Flags.test(NETFLAG_LOG_CL_PACKETS) ) { if( !pClNetLog) pClNetLog = xr_new<INetLog>( "logs\\net_cl_log.log", timeServer() ); if( pClNetLog ) pClNetLog->LogData( timeServer(), data, size ); } DPN_BUFFER_DESC desc; desc.dwBufferSize = size; desc.pBufferData = (BYTE*)data; net_Statistic.dwBytesSended += size; // verify VERIFY(desc.dwBufferSize); VERIFY(desc.pBufferData); VERIFY(NET); DPNHANDLE hAsync = 0; HRESULT hr = NET->Send( &desc, 1, dwTimeout, 0, &hAsync, dwFlags | DPNSEND_COALESCE ); // Msg("- Client::SendTo_LL [%d]", size); if( FAILED(hr) ) { Msg ("! ERROR: Failed to send net-packet, reason: %s",::Debug.error2string(hr)); // const char* x = DXGetErrorString9(hr); string1024 tmp=""; DXTRACE_ERR(tmp, hr); } // UpdateStatistic(); } void IPureClient::Send( NET_Packet& packet, u32 dwFlags, u32 dwTimeout ) { MultipacketSender::SendPacket( packet.B.data, packet.B.count, dwFlags, dwTimeout ); } void IPureClient::Flush_Send_Buffer () { MultipacketSender::FlushSendBuffer( 0 ); } BOOL IPureClient::net_HasBandwidth () { u32 dwTime = TimeGlobal(device_timer); u32 dwInterval = 0; if (net_Disconnected) return FALSE; if (psNET_ClientUpdate != 0) dwInterval = 1000/psNET_ClientUpdate; if (psNET_Flags.test(NETFLAG_MINIMIZEUPDATES)) dwInterval = 1000; // approx 3 times per second if(psNET_direct_connect) { if( 0 != psNET_ClientUpdate && (dwTime-net_Time_LastUpdate)>dwInterval) { net_Time_LastUpdate = dwTime; return TRUE; }else return FALSE; }else if (0 != psNET_ClientUpdate && (dwTime-net_Time_LastUpdate)>dwInterval) { HRESULT hr; R_ASSERT (NET); // check queue for "empty" state DWORD dwPending=0; hr = NET->GetSendQueueInfo(&dwPending,0,0); if (FAILED(hr)) return FALSE; if (dwPending > u32(psNET_ClientPending)) { net_Statistic.dwTimesBlocked++; return FALSE; }; UpdateStatistic(); // ok net_Time_LastUpdate = dwTime; return TRUE; } return FALSE; } void IPureClient::UpdateStatistic() { // Query network statistic for this client DPN_CONNECTION_INFO CI; ZeroMemory (&CI,sizeof(CI)); CI.dwSize = sizeof(CI); HRESULT hr = NET->GetConnectionInfo(&CI,0); if (FAILED(hr)) return; net_Statistic.Update(CI); } void IPureClient::Sync_Thread () { MSYS_PING clPing; //***** Ping server net_DeltaArray.clear(); R_ASSERT (NET); for (; NET && !net_Disconnected; ) { // Waiting for queue empty state if (net_Syncronised) break; // Sleep(2000); else { DWORD dwPending=0; do { R_CHK (NET->GetSendQueueInfo(&dwPending,0,0)); Sleep (1); } while (dwPending); } // Construct message clPing.sign1 = 0x12071980; clPing.sign2 = 0x26111975; clPing.dwTime_ClientSend = TimerAsync(device_timer); // Send it __try { DPN_BUFFER_DESC desc; DPNHANDLE hAsync=0; desc.dwBufferSize = sizeof(clPing); desc.pBufferData = LPBYTE(&clPing); if (0==NET || net_Disconnected) break; if (FAILED(NET->Send(&desc,1,0,0,&hAsync,net_flags(FALSE,FALSE,TRUE)))) { Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); break; } } __except (EXCEPTION_EXECUTE_HANDLER) { Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); break; } // Waiting for reply-packet to arrive if (!net_Syncronised) { u32 old_size = net_DeltaArray.size(); u32 timeBegin = TimerAsync(device_timer); while ((net_DeltaArray.size()==old_size)&&(TimerAsync(device_timer)-timeBegin<5000)) Sleep(1); if (net_DeltaArray.size()>=syncSamples) { net_Syncronised = TRUE; net_TimeDelta = net_TimeDelta_Calculated; // Msg ("* CL_TimeSync: DELTA: %d",net_TimeDelta); } } } } void IPureClient::Sync_Average () { //***** Analyze results s64 summary_delta = 0; s32 size = net_DeltaArray.size(); u32* I = net_DeltaArray.begin(); u32* E = I+size; for (; I!=E; I++) summary_delta += *((int*)I); s64 frac = s64(summary_delta) % s64(size); if (frac<0) frac=-frac; summary_delta /= s64(size); if (frac>s64(size/2)) summary_delta += (summary_delta<0)?-1:1; net_TimeDelta_Calculated= s32(summary_delta); net_TimeDelta = (net_TimeDelta*5+net_TimeDelta_Calculated)/6; // Msg("* CLIENT: d(%d), dc(%d), s(%d)",net_TimeDelta,net_TimeDelta_Calculated,size); } void sync_thread(void* P) { SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); IPureClient* C = (IPureClient*)P; C->Sync_Thread (); } void IPureClient::net_Syncronize () { net_Syncronised = FALSE; net_DeltaArray.clear(); thread_spawn (sync_thread,"network-time-sync",0,this); } void IPureClient::ClearStatistic() { net_Statistic.Clear(); } BOOL IPureClient::net_IsSyncronised() { return net_Syncronised; } #include <WINSOCK2.H> #include <Ws2tcpip.h> bool IPureClient::GetServerAddress (ip_address& pAddress, DWORD* pPort) { *pPort = 0; if (!net_Address_server) return false; WCHAR wstrHostname[ 2048 ] = {0}; DWORD dwHostNameSize = sizeof(wstrHostname); DWORD dwHostNameDataType = DPNA_DATATYPE_STRING; CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_HOSTNAME, wstrHostname, &dwHostNameSize, &dwHostNameDataType )); string2048 HostName; CHK_DX(WideCharToMultiByte(CP_ACP,0,wstrHostname,-1,HostName,sizeof(HostName),0,0)); hostent* pHostEnt = gethostbyname(HostName); char* localIP; localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list); pHostEnt = gethostbyname(pHostEnt->h_name); localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list); pAddress.set (localIP); //. pAddress[0] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_net; //. pAddress[1] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_host; //. pAddress[2] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_lh; //. pAddress[3] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_impno; DWORD dwPort = 0; DWORD dwPortSize = sizeof(dwPort); DWORD dwPortDataType = DPNA_DATATYPE_DWORD; CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType )); *pPort = dwPort; return true; };
OLR-xray/OLR-3.0
src/xray/xrNetServer/NET_Client.cpp
C++
apache-2.0
30,074
[ 30522, 1001, 2421, 1000, 2358, 2850, 2546, 2595, 1012, 1044, 1000, 1001, 2421, 1000, 5658, 1035, 2691, 1012, 1044, 1000, 1001, 2421, 1000, 5658, 1035, 7396, 1012, 1044, 1000, 1001, 2421, 1000, 5658, 1035, 8241, 1012, 1044, 1000, 1001, 242...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- title: Gayaku date: 2011-09-16 11:08:00 +07:00 nohibah: 409 inisiator: Ifan Maulana lokasi: Depok dana: 2 Miliar Rupiah topik: Meretas batas – kebhinekaan bermedia lama: November 2011 – unlimited time deskripsi: Portal informasi dan jejaring sosial mengenai fashion dan gaya hidup orang-orang Indonesia masalah: Indonesia memiliki keberagaman budaya dan seni, serta terdapatnya persinggahan kebudayaan dan seni dari banyak negara lain. Perkembangan kehidupan sosial manusia indonesia kini merambah menuju kehidupan maju dimana kebutuhan primer bukan lagi yang menjadi utama, melainkan pola hidup modern, tuntutan menjadi manusia modern, serta dunia hiburan (*entertaintment) yang menjadi utama . Kebutuhan tentang gaya hidup, fashion dan hiburan kini menjadi prioritas utama, namun hal ini kurang dibarengi oleh sarana dan prasarana serta wadah yang cukup untuk pemenuhan kebutuhan tersebut solusi: Gayaku menghubungkan elemen2 konten, informasi, aplikasi dan implementasi menjadi satu bagian dalam pemenuhan kebutuhan tentang gaya hidup, fashion dan hiburan dengan cara menyalurkan konten dari user sehingga terdapat interaksi langsung dari user dan antar user. Pihak yang diuntungkan melalui proyek ini adalah user ( pencari konten, pemberi konten), praktisi fashion, praktisi dunia hiburan, industri, dan perdagangan terkait, serta Pemerintah Indonesia keberhasilan: Berdasarkan tingkat kunjungan terhadap portal informasi dana sarana/media dan acara penunjang, tingkat kunjungan dan minat masyarakat terhadap fashion, gaya hidup dan hiburan, transaksi yang terjadi, tingkat pemanfaatan aplikasi dan konten gayaku, dan peningkatan kepercayaan mitra bisnis dengan gayaku organisasi: NA diuntungkan: "- user ( pencari konten, pemberi konten, ), - Praktisi fashion, - Praktisi dunia hiburan, - industri dan perdagangan terkait, - Pemerintah Indonesia" layout: hibahcmb --- ![409](/static/img/hibahcmb/409.png){: .img-responsive }{: width="409" } ### {{ page.nohibah }} - {{ page.title }} ---
RioSatria/ciptamedia
hibahcmb/409.md
Markdown
mit
2,049
[ 30522, 1011, 1011, 1011, 2516, 1024, 5637, 4817, 2226, 3058, 1024, 2249, 1011, 5641, 1011, 2385, 2340, 1024, 5511, 1024, 4002, 1009, 5718, 1024, 4002, 2053, 4048, 24206, 1024, 2871, 2683, 1999, 17417, 8844, 1024, 2065, 2319, 5003, 7068, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import queue import logging import platform import threading import datetime as dt import serial import serial.threaded import serial_device from .or_event import OrEvent logger = logging.getLogger(__name__) # Flag to indicate whether queues should be polled. # XXX Note that polling performance may vary by platform. POLL_QUEUES = (platform.system() == 'Windows') class EventProtocol(serial.threaded.Protocol): def __init__(self): self.transport = None self.connected = threading.Event() self.disconnected = threading.Event() self.port = None def connection_made(self, transport): """Called when reader thread is started""" self.port = transport.serial.port logger.debug('connection_made: `%s` `%s`', self.port, transport) self.transport = transport self.connected.set() self.disconnected.clear() def data_received(self, data): """Called with snippets received from the serial port""" raise NotImplementedError def connection_lost(self, exception): """\ Called when the serial port is closed or the reader loop terminated otherwise. """ if isinstance(exception, Exception): logger.debug('Connection to port `%s` lost: %s', self.port, exception) else: logger.debug('Connection to port `%s` closed', self.port) self.connected.clear() self.disconnected.set() class KeepAliveReader(threading.Thread): ''' Keep a serial connection alive (as much as possible). Parameters ---------- state : dict State dictionary to share ``protocol`` object reference. comport : str Name of com port to connect to. default_timeout_s : float, optional Default time to wait for serial operation (e.g., connect). By default, block (i.e., no time out). **kwargs Keyword arguments passed to ``serial_for_url`` function, e.g., ``baudrate``, etc. ''' def __init__(self, protocol_class, comport, **kwargs): super(KeepAliveReader, self).__init__() self.daemon = True self.protocol_class = protocol_class self.comport = comport self.kwargs = kwargs self.protocol = None self.default_timeout_s = kwargs.pop('default_timeout_s', None) # Event to indicate serial connection has been established. self.connected = threading.Event() # Event to request a break from the run loop. self.close_request = threading.Event() # Event to indicate thread has been closed. self.closed = threading.Event() # Event to indicate an exception has occurred. self.error = threading.Event() # Event to indicate that the thread has connected to the specified port # **at least once**. self.has_connected = threading.Event() @property def alive(self): return not self.closed.is_set() def run(self): # Verify requested serial port is available. try: if self.comport not in (serial_device .comports(only_available=True).index): raise NameError('Port `%s` not available. Available ports: ' '`%s`' % (self.comport, ', '.join(serial_device.comports() .index))) except NameError as exception: self.error.exception = exception self.error.set() self.closed.set() return while True: # Wait for requested serial port to become available. while self.comport not in (serial_device .comports(only_available=True).index): # Assume serial port was disconnected temporarily. Wait and # periodically check again. self.close_request.wait(2) if self.close_request.is_set(): # No connection is open, so nothing to close. Just quit. self.closed.set() return try: # Try to open serial device and monitor connection status. logger.debug('Open `%s` and monitor connection status', self.comport) device = serial.serial_for_url(self.comport, **self.kwargs) except serial.SerialException as exception: self.error.exception = exception self.error.set() self.closed.set() return except Exception as exception: self.error.exception = exception self.error.set() self.closed.set() return else: with serial.threaded.ReaderThread(device, self .protocol_class) as protocol: self.protocol = protocol connected_event = OrEvent(protocol.connected, self.close_request) disconnected_event = OrEvent(protocol.disconnected, self.close_request) # Wait for connection. connected_event.wait(None if self.has_connected.is_set() else self.default_timeout_s) if self.close_request.is_set(): # Quit run loop. Serial connection will be closed by # `ReaderThread` context manager. self.closed.set() return self.connected.set() self.has_connected.set() # Wait for disconnection. disconnected_event.wait() if self.close_request.is_set(): # Quit run loop. self.closed.set() return self.connected.clear() # Loop to try to reconnect to serial device. def write(self, data, timeout_s=None): ''' Write to serial port. Waits for serial connection to be established before writing. Parameters ---------- data : str or bytes Data to write to serial port. timeout_s : float, optional Maximum number of seconds to wait for serial connection to be established. By default, block until serial connection is ready. ''' self.connected.wait(timeout_s) self.protocol.transport.write(data) def request(self, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in seconds) for response. By default, block until response is ready. poll : bool, optional If ``True``, poll response queue in a busy loop until response is ready (or timeout occurs). Polling is much more processor intensive, but (at least on Windows) results in faster response processing. On Windows, polling is enabled by default. ''' self.connected.wait(timeout_s) return request(self, response_queue, payload, timeout_s=timeout_s, poll=poll) def close(self): self.close_request.set() # - - context manager, returns protocol def __enter__(self): """\ Enter context handler. May raise RuntimeError in case the connection could not be created. """ self.start() # Wait for protocol to connect. event = OrEvent(self.connected, self.closed) event.wait(self.default_timeout_s) return self def __exit__(self, *args): """Leave context: close port""" self.close() self.closed.wait() def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES): ''' Send payload to serial device and wait for response. Parameters ---------- device : serial.Serial Serial instance. response_queue : Queue.Queue Queue to wait for response on. payload : str or bytes Payload to send. timeout_s : float, optional Maximum time to wait (in seconds) for response. By default, block until response is ready. poll : bool, optional If ``True``, poll response queue in a busy loop until response is ready (or timeout occurs). Polling is much more processor intensive, but (at least on Windows) results in faster response processing. On Windows, polling is enabled by default. ''' device.write(payload) if poll: # Polling enabled. Wait for response in busy loop. start = dt.datetime.now() while not response_queue.qsize(): if (dt.datetime.now() - start).total_seconds() > timeout_s: raise queue.Empty('No response received.') return response_queue.get() else: # Polling disabled. Use blocking `Queue.get()` method to wait for # response. return response_queue.get(timeout=timeout_s)
wheeler-microfluidics/serial_device
serial_device/threaded.py
Python
gpl-3.0
9,719
[ 30522, 12324, 24240, 12324, 15899, 12324, 4132, 12324, 11689, 2075, 12324, 3058, 7292, 2004, 26718, 12324, 7642, 12324, 7642, 1012, 26583, 12324, 7642, 1035, 5080, 2013, 1012, 2030, 1035, 2724, 12324, 10848, 15338, 8833, 4590, 1027, 15899, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: <hex>, * opacity: <float>, * * map: new THREE.Texture( <Image> ), * * lightMap: new THREE.Texture( <Image> ), * lightMapIntensity: <float> * * aoMap: new THREE.Texture( <Image> ), * aoMapIntensity: <float> * * emissive: <hex>, * emissiveIntensity: <float> * emissiveMap: new THREE.Texture( <Image> ), * * specularMap: new THREE.Texture( <Image> ), * * alphaMap: new THREE.Texture( <Image> ), * * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: <float>, * refractionRatio: <float>, * * wireframe: <boolean>, * wireframeLinewidth: <float>, * * skinning: <bool>, * morphTargets: <bool>, * morphNormals: <bool> * } */ THREE.MeshLambertMaterial = function ( parameters ) { THREE.Material.call( this ); this.type = 'MeshLambertMaterial'; this.color = new THREE.Color( 0xffffff ); // diffuse this.map = null; this.lightMap = null; this.lightMapIntensity = 1.0; this.aoMap = null; this.aoMapIntensity = 1.0; this.emissive = new THREE.Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; this.specularMap = null; this.alphaMap = null; this.envMap = null; this.combine = THREE.MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); }; THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype ); THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial; THREE.MeshLambertMaterial.prototype.copy = function ( source ) { THREE.Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.emissive.copy( source.emissive ); this.emissiveMap = source.emissiveMap; this.emissiveIntensity = source.emissiveIntensity; this.specularMap = source.specularMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; };
reliableJARED/WebGL
static/three.js/src/materials/MeshLambertMaterial.js
JavaScript
gpl-3.0
2,863
[ 30522, 1013, 1008, 1008, 1008, 1030, 3166, 2720, 3527, 16429, 1013, 8299, 1024, 1013, 1013, 2720, 3527, 16429, 1012, 4012, 1013, 1008, 1030, 3166, 8776, 4160, 1013, 8299, 1024, 1013, 1013, 8776, 26426, 2401, 1012, 4012, 1013, 1008, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
\chapter{Funci'on Gamma}\label{app-Gamma} \begin{equation} \Gamma(z):=\lim_{n\to\infty}\frac{1\cdot 2\cdot 3\cdots n}{z(z+1)(z+2)\cdots (z+n)}n^z, \end{equation} \begin{equation} \Gamma(z):=\int_0^\infty e^{-t}t^{z-1}dt, \qquad \Re(z)>0, \end{equation} \begin{equation} \frac{1}{\Gamma(z)}:=ze^{\gamma z}\prod_{n=1}^\infty \left(1+\frac{z}{n}\right)e^{-z/n}, \end{equation} donde $\gamma=0.577216\cdots$ es la constante de Euler-Mascheroni\footnote{$\gamma:=\lim_{n\to\infty}\left(1+{1}/{2}+{1}/{3}+\cdots {1}/{n}-\ln n\right)$.}. \begin{equation} \Gamma(z+1)=z\Gamma(z), \end{equation} \begin{equation} \Gamma(1+n)=n!, \qquad n=0,1,2,\cdots , \end{equation} \begin{equation}\label{GzG1-z} \Gamma(z)\Gamma(1-z)=\frac{\pi}{\sen(z\pi)}. \end{equation} \begin{equation} \Gamma(-n)\to\pm\infty, \qquad n=0,1,2,\cdots . \end{equation} \begin{equation} \Gamma(1/2)=\sqrt{\pi}. \end{equation} \begin{figure}[H] \centering \includegraphics[angle=0,width=0.7\textwidth]{figs/fig-funcion-Gamma.pdf} \caption{La funci'on $\Gamma$ con argumento real. C'odigo Python \href{https://github.com/gfrubi/FM2/blob/master/figuras-editables/fig-Gamma.py}{aqu\'i}.} \label{fig-Gamma} \end{figure}
gfrubi/FM2
app-Gamma.tex
TeX
gpl-3.0
1,175
[ 30522, 1032, 3127, 1063, 4569, 6895, 1005, 2006, 13091, 1065, 1032, 3830, 1063, 10439, 1011, 13091, 1065, 1032, 4088, 1063, 8522, 1065, 1032, 13091, 1006, 1062, 1007, 1024, 1027, 1032, 18525, 1035, 1063, 1050, 1032, 2000, 1032, 1999, 6199, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Foundatio.Disposables.Internals { /// <summary> /// A field containing a bound action. /// </summary> /// <typeparam name="T">The type of context for the action.</typeparam> public sealed class BoundActionField<T> { private BoundAction _field; /// <summary> /// Initializes the field with the specified action and context. /// </summary> /// <param name="action">The action delegate.</param> /// <param name="context">The context.</param> public BoundActionField(Action<T> action, T context) { _field = new BoundAction(action, context); } /// <summary> /// Whether the field is empty. /// </summary> public bool IsEmpty => Interlocked.CompareExchange(ref _field, null, null) == null; /// <summary> /// Atomically retrieves the bound action from the field and sets the field to <c>null</c>. May return <c>null</c>. /// </summary> public IBoundAction TryGetAndUnset() { return Interlocked.Exchange(ref _field, null); } /// <summary> /// Attempts to update the context of the bound action stored in the field. Returns <c>false</c> if the field is <c>null</c>. /// </summary> /// <param name="contextUpdater">The function used to update an existing context. This may be called more than once if more than one thread attempts to simultaneously update the context.</param> public bool TryUpdateContext(Func<T, T> contextUpdater) { while (true) { var original = Interlocked.CompareExchange(ref _field, _field, _field); if (original == null) return false; var updatedContext = new BoundAction(original, contextUpdater); var result = Interlocked.CompareExchange(ref _field, updatedContext, original); if (ReferenceEquals(original, result)) return true; } } /// <summary> /// An action delegate bound with its context. /// </summary> public interface IBoundAction { /// <summary> /// Executes the action. This should only be done after the bound action is retrieved from a field by <see cref="TryGetAndUnset"/>. /// </summary> void Invoke(); } private sealed class BoundAction : IBoundAction { private readonly Action<T> _action; private readonly T _context; public BoundAction(Action<T> action, T context) { _action = action; _context = context; } public BoundAction(BoundAction originalBoundAction, Func<T, T> contextUpdater) { _action = originalBoundAction._action; _context = contextUpdater(originalBoundAction._context); } public void Invoke() => _action?.Invoke(_context); } } }
exceptionless/Foundatio
src/Foundatio/Nito.Disposables/Internals/BoundAction.cs
C#
apache-2.0
3,197
[ 30522, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 11689, 2075, 1025, 3415, 15327, 2179, 10450, 2080, 1012, 4487, 13102, 8820, 13510, 1012, 4722, 2015, 1063, 1013, 1013...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php defined('SYSPATH') or die('No direct script access.'); /*********************************************************** * add1.php - View * This software is copy righted by Etherton Technologies Ltd. 2011 * Writen by John Etherton <john@ethertontech.com> * Started on 12/06/2011 *************************************************************/ ?> </br> <?php if($map->large_file) { ?> <div class="slug"> <ul> <li> <?php echo __('Your map has a large data file, loading might be slow.');?> </li> </ul> </div> <?php }?> <h2><?php echo __('Add Map - Data Structure'). ' - '.$map->title; ?></h2> <h3><?php echo __('Now tell us about the structure of your data');?></h3> <ul> <li> <strong><?php echo __('Header Rows');?></strong> - <?php echo __('Tell us which row is used as the header. This is the row that denotes the geographic areas. You can only specify one row as a header.')?> </li> <li> <strong><?php echo __('Data Rows');?></strong> - <?php echo __('Tell us which rows are used to store data for an indicator. You can specify as many data rows as needed, but there must be at least one.')?> </li> <li> <strong><?php echo __('Indicator Columns');?></strong> - <?php echo __('Tell us which columns are used to specify the indicators or questions that the data in the rest of the spreadsheet shows. You can have mutliple columns that represent mulitple levels. You can specify multiple indicator columns')?> </li> <li> <strong><?php echo __('Region Columns');?></strong> - <?php echo __('Tell us which columns are used to hold the information that pertains to a specific geographic region. You can speicfy mulitple region columns.')?> </li> <li> <strong><?php echo __('Total Column - Optional');?></strong> - <?php echo __('Which column represents the total for all geographic regions. You can only specify one total column')?> </li> <li> <strong><?php echo __('Total Label Column - Optional');?></strong> - <?php echo __('Which column presents the lable for the total column for each indicator (for example, this would not have to be labeled "total"). ')?> </li> <li> <strong><?php echo __('Unit Column - Optional');?></strong> - <?php echo __('Which column stores the units for each indicator. You can only specify one unit column.')?> </li> <li> <strong><?php echo __('Source Column - Optional');?></strong> - <?php echo __('Which column stores the name of the source for each indicator. You can only specify one source column.')?> </li> <li> <strong><?php echo __('Source Link Column - Optional');?></strong> - <?php echo __('Which column stores the link to the source for each indicator. You can only specify one source link column.')?> </li> <li> <strong><?php echo __('Ignore - Optional');?></strong> - <?php echo __('Set any column or row to ignore if it should not be taken into consideration when rendering the map. You can set multiple columns and rows to ignore.')?> </li> </ul> <?php if(count($errors) > 0 ) { ?> <div class="errors"> <?php echo __("error"); ?> <ul> <?php foreach($errors as $error) { ?> <li> <?php echo $error; ?></li> <?php } ?> </ul> </div> <?php } ?> <?php if(count($messages) > 0 ) { ?> <div class="messages"> <ul> <?php foreach($messages as $message) { ?> <li> <?php echo $message; ?></li> <?php } ?> </ul> </div> <?php } ?> <div> <?php echo Form::open(NULL, array('id'=>'add_map_form', 'enctype'=>'multipart/form-data')); echo Form::hidden('action','edit', array('id'=>'action')); echo Form::hidden('map_id',$map_id, array('id'=>'map_id')); echo Form::hidden('sheet_position',$sheet_position, array('id'=>'sheet_position')); foreach($sheets as $sheet_model) { echo '<div class="data_specify">'; //sheet holding div echo '<p>'; echo '<h2>'.__('Sheet').': '.$sheet_model->name; //this doesn't work right now, so turning it off //echo Form::input('sheet_id['.$sheet_model->id.']', $sheet_model->name, array('id'=>'sheet_name')); echo '</h2>'; echo __('Ignore this sheet?:'); echo Form::checkbox('is_ignored['.$sheet_model->id.']', null, 1==$sheet_model->is_ignored, array('id'=>'ignore_checkbox_'.$sheet_model->id, 'onclick'=>'toggleTable("'.'ignore_checkbox_'.$sheet_model->id.'")')); echo '</p>'; if($sheet_model->is_ignored == 1) { $display_style = "display:none"; } else { $display_style = ""; } echo '<div style="'.$display_style.'" >'; $sheet = $sheet_data[$sheet_model->name]; echo '<div class="q1"></div>'; echo '<div class="q2"></div>'; echo '<div class="q3"></div>'; echo '<div class="q4" id="data_specify_div_'.$sheet_model->id.'" >'; echo '<table class="data_specify_table" id="data_specify_table_'.$sheet_model->id.'">'; $sheet = $sheet_data[$sheet_model->name]; foreach($sheet as $row_index=>$row) { //do this if it's the first row if($row_index == 1) { $i = 0; echo '<thead><tr><th class="header firstCol"></th>'; foreach($row as $column_index=>$column) { $i++; //set a default for each drop down $column_default = $data['column'][$sheet_model->id][$column_index]; if($column_default == null OR $column_default == "") { if($i <= 3) { $column_default = 'indicator'; } if(trim(strtolower($column)) == "unit") { $column_default = 'unit'; } else if(trim(strtolower($column)) == "source") { $column_default = 'source'; } else if(trim(strtolower($column)) == "source link") { $column_default = 'source link'; } else if(trim(strtolower($column)) == "total") { $column_default = 'total'; } else if(trim(strtolower($column)) == "total label") { $column_default = 'total_label'; } } echo '<th class="header"><div class="width">'; echo $column_index . '<br/>'; echo Form::select('column['.$sheet_model->id.']['.$column_index.']', $column_types, $column_default, array('id'=>'column_'.$sheet_model->id.'_'.$column_index)); echo '</div></th>'; } echo '</tr></thead>'; } echo '<tr><td class="header"><div class="width">'.$row_index. '<br/>'; //set a default for each drop down $row_default = trim($data['row'][$sheet_model->id][$row_index]); if($row_index == 1 AND ($row_default == null OR $row_default == "")) { $row_default = 'header'; } echo Form::select('row['.$sheet_model->id.']['.$row_index.']', $row_types, $row_default, array('id'=>'row_'.$sheet_model->id.'_'.$row_index)); echo '</div></td>'; foreach($row as $column_index=>$column) { echo '<td class="sheet_'.$sheet_model->id.' row_'.$row_index.' column_'.$column_index.'"><div class="width">'.$column; echo '</div></td>'; } echo '</tr>'; } echo '</table>'; echo '</div>'; echo '</div>'; echo '</div>'; } echo "<br/>"; echo __('All following sheets have the same data structure?'); echo Form::checkbox('same_structure', null, false, array('id'=>'same_structure' )); echo "<br/>"; echo "<br/>"; echo Form::submit('Submit', 'Submit'); echo Form::close(); ?> </div>
kobotoolbox/kobomaps
application/views/mymaps/add2.php
PHP
agpl-3.0
7,188
[ 30522, 1026, 1029, 25718, 4225, 1006, 1005, 25353, 13102, 8988, 1005, 1007, 2030, 3280, 1006, 1005, 2053, 3622, 5896, 3229, 1012, 1005, 1007, 1025, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <!-- Any copyright is dedicated to the Public Domain. - http://creativecommons.org/publicdomain/zero/1.0/ --> <html> <meta charset="utf-8"> <title>CSS Shape Test: sideways-lr, float left, circle(50% at right 40px bottom 40px)</title> <link rel="author" title="Ting-Yu Lin" href="mailto:tlin@mozilla.com"> <link rel="author" title="Mozilla" href="http://www.mozilla.org/"> <link rel="help" href="https://drafts.csswg.org/css-shapes-1/#supported-basic-shapes"> <link rel="match" href="reference/shape-outside-circle-052-ref.html"> <meta name="flags" content=""> <meta name="assert" content="Test the boxes are wrapping around the left float shape defined by circle(50% at right 40px bottom 40px) value under sideways-lr writing-mode."> <style> .container { writing-mode: sideways-lr; inline-size: 200px; line-height: 0; } .shape { float: left; shape-outside: circle(50% at right 40px bottom 40px) border-box; clip-path: circle(50% at right 40px bottom 40px) border-box; box-sizing: content-box; block-size: 40px; inline-size: 40px; padding: 20px; border: 20px solid lightgreen; margin-inline-start: 20px; margin-inline-end: 20px; background-color: orange; } .box { display: inline-block; inline-size: 60px; background-color: blue; } .long { inline-size: 200px; } </style> <main class="container"> <div class="shape"></div> <div class="long box" style="block-size: 20px;"></div> <!-- Fill the border area due to the circle shifted --> <div class="box" style="block-size: 12px;"></div> <!-- Box at corner --> <div class="box" style="block-size: 12px;"></div> <!-- Box at corner --> <div class="box" style="block-size: 36px;"></div> <div class="box" style="block-size: 36px;"></div> <div class="box" style="block-size: 12px;"></div> <!-- Box at corner --> <div class="long box" style="block-size: 20px;"></div> </main> </html>
scheib/chromium
third_party/blink/web_tests/external/wpt/css/css-shapes/shape-outside/supported-shapes/circle/shape-outside-circle-052.html
HTML
bsd-3-clause
1,990
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 999, 1011, 1011, 2151, 9385, 2003, 4056, 2000, 1996, 2270, 5884, 1012, 1011, 8299, 1024, 1013, 1013, 5541, 9006, 16563, 1012, 8917, 1013, 2270, 9527, 8113, 1013, 5717, 1013, 1015, 1012, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package xqt.model.functions.aggregates; import xqt.model.functions.AggregateFunction; /** * * @author Javad Chamanara <chamanara@gmail.com> */ public class Count implements AggregateFunction{ long counter = 0; @Override public Long move(Object data) { // Long is a subclass of Object, hence, compatible... if(data != null) counter++; return counter; } }
javadch/quis
xqt.model/src/main/java/xqt/model/functions/aggregates/Count.java
Java
gpl-3.0
589
[ 30522, 1013, 1008, 1008, 2000, 2689, 2023, 6105, 20346, 1010, 5454, 6105, 20346, 2015, 1999, 2622, 5144, 1012, 1008, 2000, 2689, 2023, 23561, 5371, 1010, 5454, 5906, 1064, 23561, 2015, 1008, 1998, 2330, 1996, 23561, 1999, 1996, 3559, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*! \file btGenericPoolAllocator.cpp \author Francisco Leon Najera. email projectileman@yahoo.com General purpose allocator class */ /* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans https://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btGenericPoolAllocator.h" /// *************** btGenericMemoryPool ******************/////////// size_t btGenericMemoryPool::allocate_from_free_nodes(size_t num_elements) { size_t ptr = BT_UINT_MAX; if (m_free_nodes_count == 0) return BT_UINT_MAX; // find an avaliable free node with the correct size size_t revindex = m_free_nodes_count; while (revindex-- && ptr == BT_UINT_MAX) { if (m_allocated_sizes[m_free_nodes[revindex]] >= num_elements) { ptr = revindex; } } if (ptr == BT_UINT_MAX) return BT_UINT_MAX; // not found revindex = ptr; ptr = m_free_nodes[revindex]; // post: ptr contains the node index, and revindex the index in m_free_nodes size_t finalsize = m_allocated_sizes[ptr]; finalsize -= num_elements; m_allocated_sizes[ptr] = num_elements; // post: finalsize>=0, m_allocated_sizes[ptr] has the requested size if (finalsize > 0) // preserve free node, there are some free memory { m_free_nodes[revindex] = ptr + num_elements; m_allocated_sizes[ptr + num_elements] = finalsize; } else // delete free node { // swap with end m_free_nodes[revindex] = m_free_nodes[m_free_nodes_count - 1]; m_free_nodes_count--; } return ptr; } size_t btGenericMemoryPool::allocate_from_pool(size_t num_elements) { if (m_allocated_count + num_elements > m_max_element_count) return BT_UINT_MAX; size_t ptr = m_allocated_count; m_allocated_sizes[m_allocated_count] = num_elements; m_allocated_count += num_elements; return ptr; } void btGenericMemoryPool::init_pool(size_t element_size, size_t element_count) { m_allocated_count = 0; m_free_nodes_count = 0; m_element_size = element_size; m_max_element_count = element_count; m_pool = (unsigned char *)btAlignedAlloc(m_element_size * m_max_element_count, 16); m_free_nodes = (size_t *)btAlignedAlloc(sizeof(size_t) * m_max_element_count, 16); m_allocated_sizes = (size_t *)btAlignedAlloc(sizeof(size_t) * m_max_element_count, 16); for (size_t i = 0; i < m_max_element_count; i++) { m_allocated_sizes[i] = 0; } } void btGenericMemoryPool::end_pool() { btAlignedFree(m_pool); btAlignedFree(m_free_nodes); btAlignedFree(m_allocated_sizes); m_allocated_count = 0; m_free_nodes_count = 0; } //! Allocates memory in pool /*! \param size_bytes size in bytes of the buffer */ void *btGenericMemoryPool::allocate(size_t size_bytes) { size_t module = size_bytes % m_element_size; size_t element_count = size_bytes / m_element_size; if (module > 0) element_count++; size_t alloc_pos = allocate_from_free_nodes(element_count); // a free node is found if (alloc_pos != BT_UINT_MAX) { return get_element_data(alloc_pos); } // allocate directly on pool alloc_pos = allocate_from_pool(element_count); if (alloc_pos == BT_UINT_MAX) return NULL; // not space return get_element_data(alloc_pos); } bool btGenericMemoryPool::freeMemory(void *pointer) { unsigned char *pointer_pos = (unsigned char *)pointer; unsigned char *pool_pos = (unsigned char *)m_pool; // calc offset if (pointer_pos < pool_pos) return false; //other pool size_t offset = size_t(pointer_pos - pool_pos); if (offset >= get_pool_capacity()) return false; // far away // find free position m_free_nodes[m_free_nodes_count] = offset / m_element_size; m_free_nodes_count++; return true; } /// *******************! btGenericPoolAllocator *******************!/// btGenericPoolAllocator::~btGenericPoolAllocator() { // destroy pools size_t i; for (i = 0; i < m_pool_count; i++) { m_pools[i]->end_pool(); btAlignedFree(m_pools[i]); } } // creates a pool btGenericMemoryPool *btGenericPoolAllocator::push_new_pool() { if (m_pool_count >= BT_DEFAULT_MAX_POOLS) return NULL; btGenericMemoryPool *newptr = (btGenericMemoryPool *)btAlignedAlloc(sizeof(btGenericMemoryPool), 16); m_pools[m_pool_count] = newptr; m_pools[m_pool_count]->init_pool(m_pool_element_size, m_pool_element_count); m_pool_count++; return newptr; } void *btGenericPoolAllocator::failback_alloc(size_t size_bytes) { btGenericMemoryPool *pool = NULL; if (size_bytes <= get_pool_capacity()) { pool = push_new_pool(); } if (pool == NULL) // failback { return btAlignedAlloc(size_bytes, 16); } return pool->allocate(size_bytes); } bool btGenericPoolAllocator::failback_free(void *pointer) { btAlignedFree(pointer); return true; } //! Allocates memory in pool /*! \param size_bytes size in bytes of the buffer */ void *btGenericPoolAllocator::allocate(size_t size_bytes) { void *ptr = NULL; size_t i = 0; while (i < m_pool_count && ptr == NULL) { ptr = m_pools[i]->allocate(size_bytes); ++i; } if (ptr) return ptr; return failback_alloc(size_bytes); } bool btGenericPoolAllocator::freeMemory(void *pointer) { bool result = false; size_t i = 0; while (i < m_pool_count && result == false) { result = m_pools[i]->freeMemory(pointer); ++i; } if (result) return true; return failback_free(pointer); } /// ************** STANDARD ALLOCATOR ***************************/// #define BT_DEFAULT_POOL_SIZE 32768 #define BT_DEFAULT_POOL_ELEMENT_SIZE 8 // main allocator class GIM_STANDARD_ALLOCATOR : public btGenericPoolAllocator { public: GIM_STANDARD_ALLOCATOR() : btGenericPoolAllocator(BT_DEFAULT_POOL_ELEMENT_SIZE, BT_DEFAULT_POOL_SIZE) { } }; // global allocator GIM_STANDARD_ALLOCATOR g_main_allocator; void *btPoolAlloc(size_t size) { return g_main_allocator.allocate(size); } void *btPoolRealloc(void *ptr, size_t oldsize, size_t newsize) { void *newptr = btPoolAlloc(newsize); size_t copysize = oldsize < newsize ? oldsize : newsize; memcpy(newptr, ptr, copysize); btPoolFree(ptr); return newptr; } void btPoolFree(void *ptr) { g_main_allocator.freeMemory(ptr); }
niello/deusexmachina
Deps/bullet/src/BulletCollision/Gimpact/btGenericPoolAllocator.cpp
C++
mit
6,796
[ 30522, 1013, 1008, 999, 1032, 5371, 18411, 6914, 22420, 16869, 8095, 24755, 4263, 1012, 18133, 2361, 1032, 3166, 3799, 6506, 6583, 20009, 2050, 1012, 10373, 25921, 2386, 1030, 20643, 1012, 4012, 2236, 3800, 2035, 24755, 4263, 2465, 1008, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.bcel.internal.generic; import java.io.DataOutputStream; import java.io.IOException; import com.sun.org.apache.bcel.internal.Const; import com.sun.org.apache.bcel.internal.ExceptionConst; import com.sun.org.apache.bcel.internal.classfile.ConstantPool; import com.sun.org.apache.bcel.internal.util.ByteSequence; /** * INVOKEINTERFACE - Invoke interface method * <PRE>Stack: ..., objectref, [arg1, [arg2 ...]] -&gt; ...</PRE> * * @see * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokeinterface"> * The invokeinterface instruction in The Java Virtual Machine Specification</a> */ public final class INVOKEINTERFACE extends InvokeInstruction { private int nargs; // Number of arguments on stack (number of stack slots), called "count" in vmspec2 /** * Empty constructor needed for Instruction.readInstruction. * Not to be used otherwise. */ INVOKEINTERFACE() { } public INVOKEINTERFACE(final int index, final int nargs) { super(Const.INVOKEINTERFACE, index); super.setLength(5); if (nargs < 1) { throw new ClassGenException("Number of arguments must be > 0 " + nargs); } this.nargs = nargs; } /** * Dump instruction as byte code to stream out. * @param out Output stream */ @Override public void dump( final DataOutputStream out ) throws IOException { out.writeByte(super.getOpcode()); out.writeShort(super.getIndex()); out.writeByte(nargs); out.writeByte(0); } /** * The <B>count</B> argument according to the Java Language Specification, * Second Edition. */ public int getCount() { return nargs; } /** * Read needed data (i.e., index) from file. */ @Override protected void initFromFile( final ByteSequence bytes, final boolean wide ) throws IOException { super.initFromFile(bytes, wide); super.setLength(5); nargs = bytes.readUnsignedByte(); bytes.readByte(); // Skip 0 byte } /** * @return mnemonic for instruction with symbolic references resolved */ @Override public String toString( final ConstantPool cp ) { return super.toString(cp) + " " + nargs; } @Override public int consumeStack( final ConstantPoolGen cpg ) { // nargs is given in byte-code return nargs; // nargs includes this reference } @Override public Class<?>[] getExceptions() { return ExceptionConst.createExceptions(ExceptionConst.EXCS.EXCS_INTERFACE_METHOD_RESOLUTION, ExceptionConst.UNSATISFIED_LINK_ERROR, ExceptionConst.ABSTRACT_METHOD_ERROR, ExceptionConst.ILLEGAL_ACCESS_ERROR, ExceptionConst.INCOMPATIBLE_CLASS_CHANGE_ERROR); } /** * Call corresponding visitor method(s). The order is: * Call visitor methods of implemented interfaces first, then * call methods according to the class hierarchy in descending order, * i.e., the most specific visitXXX() call comes last. * * @param v Visitor object */ @Override public void accept( final Visitor v ) { v.visitExceptionThrower(this); v.visitTypedInstruction(this); v.visitStackConsumer(this); v.visitStackProducer(this); v.visitLoadClass(this); v.visitCPInstruction(this); v.visitFieldOrMethod(this); v.visitInvokeInstruction(this); v.visitINVOKEINTERFACE(this); } }
mirkosertic/Bytecoder
classlib/java.xml/src/main/resources/META-INF/modules/java.xml/classes/com/sun/org/apache/bcel/internal/generic/INVOKEINTERFACE.java
Java
apache-2.0
4,443
[ 30522, 1013, 1008, 1008, 9235, 7615, 3796, 1008, 2079, 2025, 6366, 2030, 11477, 999, 1008, 1013, 1013, 1008, 1008, 7000, 2000, 1996, 15895, 4007, 3192, 1006, 2004, 2546, 1007, 2104, 2028, 2030, 2062, 1008, 12130, 6105, 10540, 1012, 2156, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** #******************************************************************************* # Projet : VOR-005 # Sous projet : calibrateur de servo moteurs # Auteurs: Gille De Bussy # # Classe potar: fichier d'entete Classe qui s'utilise avec un timer Elle filtre les faibles variations jusqu'a ce qu'elles soient suffisement significatives #******************************************************************************* J.Soranzo 13/10/2016: commentaire */ #ifndef potar_h #define potar_h #include <Arduino.h> class potar { public: potar(byte pin); void init(); //parce que dans le constructeur lire la pin anlogique //ne marche pas (=0sytématiquement) void refresh(); bool hasBeenMovedALot(); void acquit(); //remet les etat a zero (moved) int getValue();//retourne valeur reel du potar private: byte _pin; //numero de Pin pour le potar int _value; // Valeur reelle int _valueRef; // valeure de reference pour voir s'il bouge bool _movedALot; // si a bouge beaucoups }; #endif
gilles293/calibrateurServo
potar.h
C
mit
1,043
[ 30522, 1013, 1008, 1008, 1001, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
RSpec.describe AuthorizeIf do let(:controller) { double(:dummy_controller, controller_name: "dummy", action_name: "index"). extend(AuthorizeIf) } describe "#authorize_if" do context "when object is given" do it "returns true if truthy object is given" do expect(controller.authorize_if(true)).to eq true expect(controller.authorize_if(Object.new)).to eq true end it "raises NotAuthorizedError if falsey object is given" do expect { controller.authorize_if(false) }.to raise_error(AuthorizeIf::NotAuthorizedError) expect { controller.authorize_if(nil) }.to raise_error(AuthorizeIf::NotAuthorizedError) end end context "when object and block are given" do it "allows exception customization through the block" do expect { controller.authorize_if(false) do |exception| exception.message = "Custom Message" exception.context[:request_ip] = "192.168.1.1" end }.to raise_error(AuthorizeIf::NotAuthorizedError, "Custom Message") do |exception| expect(exception.message).to eq("Custom Message") expect(exception.context[:request_ip]).to eq("192.168.1.1") end end end context "when no arguments are given" do it "raises ArgumentError" do expect { controller.authorize_if }.to raise_error(ArgumentError) end end end describe "#authorize" do context "when corresponding authorization rule exists" do context "when rule does not accept parameters" do it "returns true if rule returns true" do controller.define_singleton_method(:authorize_index?) { true } expect(controller.authorize).to eq true end end context "when rule accepts parameters" do it "calls rule with given parameters" do class << controller def authorize_index?(param_1, param_2:) param_1 || param_2 end end expect(controller.authorize(false, param_2: true)).to eq true end end context "when block is given" do it "passes block through to `authorize_if` method" do controller.define_singleton_method(:authorize_index?) { false } expect { controller.authorize do |exception| exception.message = "passed through" end }.to raise_error(AuthorizeIf::NotAuthorizedError, "passed through") do |exception| expect(exception.message).to eq("passed through") end end end end context "when corresponding authorization rule does not exist" do it "raises MissingAuthorizationRuleError" do expect { controller.authorize }.to raise_error( AuthorizeIf::MissingAuthorizationRuleError, "No authorization rule defined for action dummy#index. Please define method #authorize_index? for #{controller.class.name}" ) end end end end
vrybas/authorize_if
spec/authorize_if_spec.rb
Ruby
mit
3,092
[ 30522, 12667, 5051, 2278, 1012, 6235, 3166, 4697, 10128, 2079, 2292, 1006, 1024, 11486, 1007, 1063, 3313, 1006, 1024, 24369, 1035, 11486, 1010, 11486, 1035, 2171, 1024, 1000, 24369, 1000, 1010, 2895, 1035, 2171, 1024, 1000, 5950, 1000, 1007...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
create table DBUserApiKey ( id bigserial not null, attempts INTEGER DEFAULT 0 not null, created TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP not null, lastAttempt TIMESTAMP WITHOUT TIME ZONE, lastSuccess TIMESTAMP WITHOUT TIME ZONE, successes INTEGER DEFAULT 0 not null, deadline TIMESTAMP WITHOUT TIME ZONE, deathMessage varchar(255), description varchar(255), hashedApiKey varchar(255) not null unique, name varchar(255), unhashedApiKey varchar(255), user_id int8 not null, primary key (id) ); ALTER TABLE Tenant ADD COLUMN apiAccess4All BOOLEAN DEFAULT 'f' NOT NULL; ALTER TABLE TenantUser ADD COLUMN apiAccess BOOLEAN DEFAULT 'f' NOT NULL; alter table DBUserApiKey add constraint FK24E9B0AEE4D1151E foreign key (user_id) references DBUser;
Osndok/qrauth
java/qrauth-server/src/main/resources/db/migration/V002__user_api_keys.sql
SQL
agpl-3.0
912
[ 30522, 3443, 2795, 16962, 20330, 9331, 17339, 2100, 1006, 8909, 2502, 8043, 4818, 2025, 19701, 1010, 4740, 16109, 12398, 1014, 2025, 19701, 1010, 2580, 2335, 15464, 2361, 2302, 2051, 4224, 12398, 2783, 1035, 2335, 15464, 2361, 2025, 19701, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Admin\Controller; use Common\Controller\BaseController; class IndexController extends BaseController { public function indexGet(){ if($_SESSION[MODULE_NAME.'_token']) {//已登陆 $this->display("Index:index"); } else {//未登陆 $this->redirect("Index/login"); } } public function homeGet() { $html = $this->fetch("Index:index"); $this->_result['data']['html'] = $html; $this->response($this->_result); } public function profileGet() { $this->_result['data']['html'] = 'Profile'; $this->response($this->_result, 'json', 200); } public function loginGet() { if($_SESSION[MODULE_NAME.'_token']) { $this->display("Index:index"); } else { $this->display("Index:login"); } } }
jelly074100209/gg_admin
Application/Admin/Controller/IndexController.class.php
PHP
apache-2.0
861
[ 30522, 1026, 1029, 25718, 3415, 15327, 4748, 10020, 1032, 11486, 1025, 2224, 2691, 1032, 11486, 1032, 2918, 8663, 13181, 10820, 1025, 2465, 5950, 8663, 13181, 10820, 8908, 2918, 8663, 13181, 10820, 1063, 2270, 3853, 5950, 18150, 1006, 1007, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: page permalink: /all-base-R/Sys-dot-time/ --- ## __Sys.time__ #### _Get Current Date and Time_ ### Usage ### Arguments ### Notes
rich-iannone/all-base-R
Sys-dot-time.md
Markdown
mit
146
[ 30522, 1011, 1011, 1011, 9621, 1024, 3931, 2566, 9067, 19839, 1024, 1013, 2035, 1011, 2918, 1011, 1054, 1013, 25353, 2015, 1011, 11089, 1011, 2051, 1013, 1011, 1011, 1011, 1001, 1001, 1035, 1035, 25353, 2015, 1012, 2051, 1035, 1035, 1001, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Asciidoctor 1.5.4"> <title>gitweb.conf(5)</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"> <style> /* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */ /* Remove comment around @import statement below when using as a custom stylesheet */ /*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/ article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block} audio,canvas,video{display:inline-block} audio:not([controls]){display:none;height:0} [hidden],template{display:none} script{display:none!important} html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%} body{margin:0} a{background:transparent} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} abbr[title]{border-bottom:1px dotted} b,strong{font-weight:bold} dfn{font-style:italic} hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0} input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box} input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} body{-webkit-font-smoothing:antialiased} img,object,svg{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} .center{margin-left:auto;margin-right:auto} .spread{width:100%} p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:none} p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em} ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit} ul.square{list-style-type:square} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ul.no-bullet{list-style:none} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help} abbr{text-transform:none} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)} blockquote cite:before{content:"\2014 \0020"} blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}} table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede} table thead,table tfoot{background:#f7f8f7;font-weight:bold} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6} body{tab-size:4} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table} .clearfix:after,.float-group:after{clear:both} *:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed} pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed} .keyseq{color:rgba(51,51,51,.8)} kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menu{color:rgba(0,0,0,.8)} b.button:before,b.button:after{position:relative;top:-1px;font-weight:400} b.button:before{content:"[";padding:0 3px 0 2px} b.button:after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table} #header:after,#content:after,#footnotes:after,#footer:after{clear:both} #content{margin-top:1.25em} #content:before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8} #header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px} #header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span:before{content:"\00a0\2013\00a0"} #header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark:before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber:after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #efefed;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc li{line-height:1.3334;margin-top:.3334em} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media only screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} #toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}} @media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}} #content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:rgba(255,255,255,.8);line-height:1.44} .sect1{padding-bottom:.625em} @media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}} .sect1+.sect1{border-top:1px solid #efefed} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} .audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0} .paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)} table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px} .exampleblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child{margin-bottom:0} .sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px} .sidebarblock>:first-child{margin-top:0} .sidebarblock>:last-child{margin-bottom:0} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8} .sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1} .literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em} .literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal} @media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}} @media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}} .literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .listingblock>.content{position:relative} .listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999} .listingblock:hover code[data-lang]:before{display:block} .listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999} .listingblock.terminal pre .command:not([data-prompt]):before{content:"$"} table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;line-height:1.45} table.pyhltable td.code{padding-left:.75em;padding-right:0} pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8} pre.pygments .lineno{display:inline-block;margin-right:.25em} table.pyhltable .linenodiv{background:none!important;padding-right:0!important} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right} .quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)} .quoteblock .quoteblock blockquote{padding:0 0 0 .75em} .quoteblock .quoteblock blockquote:before{display:none} .verseblock{margin:0 1em 1.25em 1em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)} .quoteblock.abstract{margin:0 0 1.25em 0;display:block} .quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0} .quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none} table.tableblock{max-width:100%;border-collapse:separate} table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0} table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0} table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0} table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0} table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0} table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0} table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0} table.frame-all{border-width:1px} table.frame-sides{border-width:0 1px} table.frame-topbot{border-width:1px 0} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} td>div.verse{white-space:pre} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none} ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em} ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em} ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px} ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden} ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block} ul.inline>li>*{display:block} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em} td.hdlist1{font-weight:bold;padding-bottom:1.25em} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist>table tr>td:first-of-type{padding:0 .75em;line-height:1} .colist>table tr>td:last-of-type{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd} .imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0} .imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none;display:inline-block} a.image object{pointer-events:none} sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super} sup.footnote a,sup.footnoteref a{text-decoration:none} sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0} #footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;text-indent:-1.05em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} .gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0} .gist .file-data>table td.line-data{width:99%} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background-color:#00fafa} .black{color:#000} .black-background{background-color:#000} .blue{color:#0000bf} .blue-background{background-color:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background-color:#fa00fa} .gray{color:#606060} .gray-background{background-color:#7d7d7d} .green{color:#006000} .green-background{background-color:#007d00} .lime{color:#00bf00} .lime-background{background-color:#00fa00} .maroon{color:#600000} .maroon-background{background-color:#7d0000} .navy{color:#000060} .navy-background{background-color:#00007d} .olive{color:#606000} .olive-background{background-color:#7d7d00} .purple{color:#600060} .purple-background{background-color:#7d007d} .red{color:#bf0000} .red-background{background-color:#fa0000} .silver{color:#909090} .silver-background{background-color:#bcbcbc} .teal{color:#006060} .teal-background{background-color:#007d7d} .white{color:#bfbfbf} .white-background{background-color:#fafafa} .yellow{color:#bfbf00} .yellow-background{background-color:#fafa00} span.icon>.fa{cursor:default} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]:after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility} h1,h2,p,td.content,span.alt{letter-spacing:-.01em} p strong,td.content strong,div.footnote strong{letter-spacing:-.005em} p,blockquote,dt,td.content,span.alt{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @media print{@page{margin:1.25cm .75cm} *{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]:after{content:" (" attr(title) ")"} pre,blockquote,tr,img,object,svg{page-break-inside:avoid} thead{display:table-header-group} svg{max-width:100%} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important} .sect1{padding-bottom:0!important} .sect1+.sect1{border:0!important} #header>h1:first-child{margin-top:1.25rem} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span:before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]:before{display:block} #footer{background:none!important;padding:0 .9375em} #footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} </style> </head> <body class="manpage"> <div id="header"> <h1>gitweb.conf(5) Manual Page</h1> <h2>NAME</h2> <div class="sectionbody"> <p>gitweb.conf - Gitweb (Git web interface) configuration file</p> </div> </div> <div id="content"> <div class="sect1"> <h2 id="_synopsis">SYNOPSIS</h2> <div class="sectionbody"> <div class="paragraph"> <p>/etc/gitweb.conf, /etc/gitweb-common.conf, $GITWEBDIR/gitweb_config.perl</p> </div> </div> </div> <div class="sect1"> <h2 id="_description">DESCRIPTION</h2> <div class="sectionbody"> <div class="paragraph"> <p>The gitweb CGI script for viewing Git repositories over the web uses a perl script fragment as its configuration file. You can set variables using "<code>our $variable = value</code>"; text from a "#" character until the end of a line is ignored. See <strong>perlsyn</strong>(1) for details.</p> </div> <div class="paragraph"> <p>An example:</p> </div> <div class="literalblock"> <div class="content"> <pre># gitweb configuration file for http://git.example.org # our $projectroot = "/srv/git"; # FHS recommendation our $site_name = 'Example.org &gt;&gt; Repos';</pre> </div> </div> <div class="paragraph"> <p>The configuration file is used to override the default settings that were built into gitweb at the time the <em>gitweb.cgi</em> script was generated.</p> </div> <div class="paragraph"> <p>While one could just alter the configuration settings in the gitweb CGI itself, those changes would be lost upon upgrade. Configuration settings might also be placed into a file in the same directory as the CGI script with the default name <em>gitweb_config.perl</em>&#8201;&#8212;&#8201;allowing one to have multiple gitweb instances with different configurations by the use of symlinks.</p> </div> <div class="paragraph"> <p>Note that some configuration can be controlled on per-repository rather than gitweb-wide basis: see "Per-repository gitweb configuration" subsection on <a href="gitweb.html">gitweb</a>(1) manpage.</p> </div> </div> </div> <div class="sect1"> <h2 id="_discussion">DISCUSSION</h2> <div class="sectionbody"> <div class="paragraph"> <p>Gitweb reads configuration data from the following sources in the following order:</p> </div> <div class="ulist"> <ul> <li> <p>built-in values (some set during build stage),</p> </li> <li> <p>common system-wide configuration file (defaults to <em>/etc/gitweb-common.conf</em>),</p> </li> <li> <p>either per-instance configuration file (defaults to <em>gitweb_config.perl</em> in the same directory as the installed gitweb), or if it does not exists then fallback system-wide configuration file (defaults to <em>/etc/gitweb.conf</em>).</p> </li> </ul> </div> <div class="paragraph"> <p>Values obtained in later configuration files override values obtained earlier in the above sequence.</p> </div> <div class="paragraph"> <p>Locations of the common system-wide configuration file, the fallback system-wide configuration file and the per-instance configuration file are defined at compile time using build-time Makefile configuration variables, respectively <code>GITWEB_CONFIG_COMMON</code>, <code>GITWEB_CONFIG_SYSTEM</code> and <code>GITWEB_CONFIG</code>.</p> </div> <div class="paragraph"> <p>You can also override locations of gitweb configuration files during runtime by setting the following environment variables: <code>GITWEB_CONFIG_COMMON</code>, <code>GITWEB_CONFIG_SYSTEM</code> and <code>GITWEB_CONFIG</code> to a non-empty value.</p> </div> <div class="paragraph"> <p>The syntax of the configuration files is that of Perl, since these files are handled by sourcing them as fragments of Perl code (the language that gitweb itself is written in). Variables are typically set using the <code>our</code> qualifier (as in "<code>our $variable = &lt;value&gt;;</code>") to avoid syntax errors if a new version of gitweb no longer uses a variable and therefore stops declaring it.</p> </div> <div class="paragraph"> <p>You can include other configuration file using read_config_file() subroutine. For example, one might want to put gitweb configuration related to access control for viewing repositories via Gitolite (one of Git repository management tools) in a separate file, e.g. in <em>/etc/gitweb-gitolite.conf</em>. To include it, put</p> </div> <div class="listingblock"> <div class="content"> <pre>read_config_file("/etc/gitweb-gitolite.conf");</pre> </div> </div> <div class="paragraph"> <p>somewhere in gitweb configuration file used, e.g. in per-installation gitweb configuration file. Note that read_config_file() checks itself that the file it reads exists, and does nothing if it is not found. It also handles errors in included file.</p> </div> <div class="paragraph"> <p>The default configuration with no configuration file at all may work perfectly well for some installations. Still, a configuration file is useful for customizing or tweaking the behavior of gitweb in many ways, and some optional features will not be present unless explicitly enabled using the configurable <code>%features</code> variable (see also "Configuring gitweb features" section below).</p> </div> </div> </div> <div class="sect1"> <h2 id="_configuration_variables">CONFIGURATION VARIABLES</h2> <div class="sectionbody"> <div class="paragraph"> <p>Some configuration variables have their default values (embedded in the CGI script) set during building gitweb&#8201;&#8212;&#8201;if that is the case, this fact is put in their description. See gitweb&#8217;s <em>INSTALL</em> file for instructions on building and installing gitweb.</p> </div> <div class="sect2"> <h3 id="_location_of_repositories">Location of repositories</h3> <div class="paragraph"> <p>The configuration variables described below control how gitweb finds Git repositories, and how repositories are displayed and accessed.</p> </div> <div class="paragraph"> <p>See also "Repositories" and later subsections in <a href="gitweb.html">gitweb</a>(1) manpage.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">$projectroot</dt> <dd> <p>Absolute filesystem path which will be prepended to project path; the path to repository is <code>$projectroot/$project</code>. Set to <code>$GITWEB_PROJECTROOT</code> during installation. This variable has to be set correctly for gitweb to find repositories.</p> <div class="paragraph"> <p>For example, if <code>$projectroot</code> is set to "/srv/git" by putting the following in gitweb config file:</p> </div> <div class="listingblock"> <div class="content"> <pre>our $projectroot = "/srv/git";</pre> </div> </div> <div class="paragraph"> <p>then</p> </div> <div class="listingblock"> <div class="content"> <pre>http://git.example.com/gitweb.cgi?p=foo/bar.git</pre> </div> </div> <div class="paragraph"> <p>and its path_info based equivalent</p> </div> <div class="listingblock"> <div class="content"> <pre>http://git.example.com/gitweb.cgi/foo/bar.git</pre> </div> </div> <div class="paragraph"> <p>will map to the path <em>/srv/git/foo/bar.git</em> on the filesystem.</p> </div> </dd> <dt class="hdlist1">$projects_list</dt> <dd> <p>Name of a plain text file listing projects, or a name of directory to be scanned for projects.</p> <div class="paragraph"> <p>Project list files should list one project per line, with each line having the following format</p> </div> <div class="listingblock"> <div class="content"> <pre>&lt;URI-encoded filesystem path to repository&gt; SP &lt;URI-encoded repository owner&gt;</pre> </div> </div> <div class="paragraph"> <p>The default value of this variable is determined by the <code>GITWEB_LIST</code> makefile variable at installation time. If this variable is empty, gitweb will fall back to scanning the <code>$projectroot</code> directory for repositories.</p> </div> </dd> <dt class="hdlist1">$project_maxdepth</dt> <dd> <p>If <code>$projects_list</code> variable is unset, gitweb will recursively scan filesystem for Git repositories. The <code>$project_maxdepth</code> is used to limit traversing depth, relative to <code>$projectroot</code> (starting point); it means that directories which are further from <code>$projectroot</code> than <code>$project_maxdepth</code> will be skipped.</p> <div class="paragraph"> <p>It is purely performance optimization, originally intended for MacOS X, where recursive directory traversal is slow. Gitweb follows symbolic links, but it detects cycles, ignoring any duplicate files and directories.</p> </div> <div class="paragraph"> <p>The default value of this variable is determined by the build-time configuration variable <code>GITWEB_PROJECT_MAXDEPTH</code>, which defaults to 2007.</p> </div> </dd> <dt class="hdlist1">$export_ok</dt> <dd> <p>Show repository only if this file exists (in repository). Only effective if this variable evaluates to true. Can be set when building gitweb by setting <code>GITWEB_EXPORT_OK</code>. This path is relative to <code>GIT_DIR</code>. git-daemon[1] uses <em>git-daemon-export-ok</em>, unless started with <code>--export-all</code>. By default this variable is not set, which means that this feature is turned off.</p> </dd> <dt class="hdlist1">$export_auth_hook</dt> <dd> <p>Function used to determine which repositories should be shown. This subroutine should take one parameter, the full path to a project, and if it returns true, that project will be included in the projects list and can be accessed through gitweb as long as it fulfills the other requirements described by $export_ok, $projects_list, and $projects_maxdepth. Example:</p> <div class="listingblock"> <div class="content"> <pre>our $export_auth_hook = sub { return -e "$_[0]/git-daemon-export-ok"; };</pre> </div> </div> <div class="paragraph"> <p>though the above might be done by using <code>$export_ok</code> instead</p> </div> <div class="listingblock"> <div class="content"> <pre>our $export_ok = "git-daemon-export-ok";</pre> </div> </div> <div class="paragraph"> <p>If not set (default), it means that this feature is disabled.</p> </div> <div class="paragraph"> <p>See also more involved example in "Controlling access to Git repositories" subsection on <a href="gitweb.html">gitweb</a>(1) manpage.</p> </div> </dd> <dt class="hdlist1">$strict_export</dt> <dd> <p>Only allow viewing of repositories also shown on the overview page. This for example makes <code>$gitweb_export_ok</code> file decide if repository is available and not only if it is shown. If <code>$gitweb_list</code> points to file with list of project, only those repositories listed would be available for gitweb. Can be set during building gitweb via <code>GITWEB_STRICT_EXPORT</code>. By default this variable is not set, which means that you can directly access those repositories that are hidden from projects list page (e.g. the are not listed in the $projects_list file).</p> </dd> </dl> </div> </div> <div class="sect2"> <h3 id="_finding_files">Finding files</h3> <div class="paragraph"> <p>The following configuration variables tell gitweb where to find files. The values of these variables are paths on the filesystem.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">$GIT</dt> <dd> <p>Core git executable to use. By default set to <code>$GIT_BINDIR/git</code>, which in turn is by default set to <code>$(bindir)/git</code>. If you use Git installed from a binary package, you should usually set this to "/usr/bin/git". This can just be "git" if your web server has a sensible PATH; from security point of view it is better to use absolute path to git binary. If you have multiple Git versions installed it can be used to choose which one to use. Must be (correctly) set for gitweb to be able to work.</p> </dd> <dt class="hdlist1">$mimetypes_file</dt> <dd> <p>File to use for (filename extension based) guessing of MIME types before trying <em>/etc/mime.types</em>. <strong>NOTE</strong> that this path, if relative, is taken as relative to the current Git repository, not to CGI script. If unset, only <em>/etc/mime.types</em> is used (if present on filesystem). If no mimetypes file is found, mimetype guessing based on extension of file is disabled. Unset by default.</p> </dd> <dt class="hdlist1">$highlight_bin</dt> <dd> <p>Path to the highlight executable to use (it must be the one from <a href="http://www.andre-simon.de" class="bare">http://www.andre-simon.de</a> due to assumptions about parameters and output). By default set to <em>highlight</em>; set it to full path to highlight executable if it is not installed on your web server&#8217;s PATH. Note that <em>highlight</em> feature must be set for gitweb to actually use syntax highlighting.</p> <div class="paragraph"> <p><strong>NOTE</strong>: if you want to add support for new file type (supported by "highlight" but not used by gitweb), you need to modify <code>%highlight_ext</code> or <code>%highlight_basename</code>, depending on whether you detect type of file based on extension (for example "sh") or on its basename (for example "Makefile"). The keys of these hashes are extension and basename, respectively, and value for given key is name of syntax to be passed via <code>--syntax &lt;syntax&gt;</code> to highlighter.</p> </div> <div class="paragraph"> <p>For example if repositories you are hosting use "phtml" extension for PHP files, and you want to have correct syntax-highlighting for those files, you can add the following to gitweb configuration:</p> </div> <div class="listingblock"> <div class="content"> <pre>our %highlight_ext; $highlight_ext{'phtml'} = 'php';</pre> </div> </div> </dd> </dl> </div> </div> <div class="sect2"> <h3 id="_links_and_their_targets">Links and their targets</h3> <div class="paragraph"> <p>The configuration variables described below configure some of gitweb links: their target and their look (text or image), and where to find page prerequisites (stylesheet, favicon, images, scripts). Usually they are left at their default values, with the possible exception of <code>@stylesheets</code> variable.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">@stylesheets</dt> <dd> <p>List of URIs of stylesheets (relative to the base URI of a page). You might specify more than one stylesheet, for example to use "gitweb.css" as base with site specific modifications in a separate stylesheet to make it easier to upgrade gitweb. For example, you can add a <code>site</code> stylesheet by putting</p> <div class="listingblock"> <div class="content"> <pre>push @stylesheets, "gitweb-site.css";</pre> </div> </div> <div class="paragraph"> <p>in the gitweb config file. Those values that are relative paths are relative to base URI of gitweb.</p> </div> <div class="paragraph"> <p>This list should contain the URI of gitweb&#8217;s standard stylesheet. The default URI of gitweb stylesheet can be set at build time using the <code>GITWEB_CSS</code> makefile variable. Its default value is <em>static/gitweb.css</em> (or <em>static/gitweb.min.css</em> if the <code>CSSMIN</code> variable is defined, i.e. if CSS minifier is used during build).</p> </div> <div class="paragraph"> <p><strong>Note</strong>: there is also a legacy <code>$stylesheet</code> configuration variable, which was used by older gitweb. If <code>$stylesheet</code> variable is defined, only CSS stylesheet given by this variable is used by gitweb.</p> </div> </dd> <dt class="hdlist1">$logo</dt> <dd> <p>Points to the location where you put <em>git-logo.png</em> on your web server, or to be more the generic URI of logo, 72x27 size). This image is displayed in the top right corner of each gitweb page and used as a logo for the Atom feed. Relative to the base URI of gitweb (as a path). Can be adjusted when building gitweb using <code>GITWEB_LOGO</code> variable By default set to <em>static/git-logo.png</em>.</p> </dd> <dt class="hdlist1">$favicon</dt> <dd> <p>Points to the location where you put <em>git-favicon.png</em> on your web server, or to be more the generic URI of favicon, which will be served as "image/png" type. Web browsers that support favicons (website icons) may display them in the browser&#8217;s URL bar and next to the site name in bookmarks. Relative to the base URI of gitweb. Can be adjusted at build time using <code>GITWEB_FAVICON</code> variable. By default set to <em>static/git-favicon.png</em>.</p> </dd> <dt class="hdlist1">$javascript</dt> <dd> <p>Points to the location where you put <em>gitweb.js</em> on your web server, or to be more generic the URI of JavaScript code used by gitweb. Relative to the base URI of gitweb. Can be set at build time using the <code>GITWEB_JS</code> build-time configuration variable.</p> <div class="paragraph"> <p>The default value is either <em>static/gitweb.js</em>, or <em>static/gitweb.min.js</em> if the <code>JSMIN</code> build variable was defined, i.e. if JavaScript minifier was used at build time. <strong>Note</strong> that this single file is generated from multiple individual JavaScript "modules".</p> </div> </dd> <dt class="hdlist1">$home_link</dt> <dd> <p>Target of the home link on the top of all pages (the first part of view "breadcrumbs"). By default it is set to the absolute URI of a current page (to the value of <code>$my_uri</code> variable, or to "/" if <code>$my_uri</code> is undefined or is an empty string).</p> </dd> <dt class="hdlist1">$home_link_str</dt> <dd> <p>Label for the "home link" at the top of all pages, leading to <code>$home_link</code> (usually the main gitweb page, which contains the projects list). It is used as the first component of gitweb&#8217;s "breadcrumb trail": <code>&lt;home link&gt; / &lt;project&gt; / &lt;action&gt;</code>. Can be set at build time using the <code>GITWEB_HOME_LINK_STR</code> variable. By default it is set to "projects", as this link leads to the list of projects. Another popular choice is to set it to the name of site. Note that it is treated as raw HTML so it should not be set from untrusted sources.</p> </dd> <dt class="hdlist1">@extra_breadcrumbs</dt> <dd> <p>Additional links to be added to the start of the breadcrumb trail before the home link, to pages that are logically "above" the gitweb projects list, such as the organization and department which host the gitweb server. Each element of the list is a reference to an array, in which element 0 is the link text (equivalent to <code>$home_link_str</code>) and element 1 is the target URL (equivalent to <code>$home_link</code>).</p> <div class="paragraph"> <p>For example, the following setting produces a breadcrumb trail like "home / dev / projects / &#8230;&#8203;" where "projects" is the home link.</p> </div> </dd> </dl> </div> <div class="listingblock"> <div class="content"> <pre> our @extra_breadcrumbs = ( [ 'home' =&gt; 'https://www.example.org/' ], [ 'dev' =&gt; 'https://dev.example.org/' ], );</pre> </div> </div> <div class="dlist"> <dl> <dt class="hdlist1">$logo_url</dt> <dt class="hdlist1">$logo_label</dt> <dd> <p>URI and label (title) for the Git logo link (or your site logo, if you chose to use different logo image). By default, these both refer to Git homepage, <a href="http://git-scm.com" class="bare">http://git-scm.com</a>; in the past, they pointed to Git documentation at <a href="http://www.kernel.org" class="bare">http://www.kernel.org</a>.</p> </dd> </dl> </div> </div> <div class="sect2"> <h3 id="_changing_gitweb_s_look">Changing gitweb&#8217;s look</h3> <div class="paragraph"> <p>You can adjust how pages generated by gitweb look using the variables described below. You can change the site name, add common headers and footers for all pages, and add a description of this gitweb installation on its main page (which is the projects list page), etc.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">$site_name</dt> <dd> <p>Name of your site or organization, to appear in page titles. Set it to something descriptive for clearer bookmarks etc. If this variable is not set or is, then gitweb uses the value of the <code>SERVER_NAME</code> <code>CGI</code> environment variable, setting site name to "$SERVER_NAME Git", or "Untitled Git" if this variable is not set (e.g. if running gitweb as standalone script).</p> <div class="paragraph"> <p>Can be set using the <code>GITWEB_SITENAME</code> at build time. Unset by default.</p> </div> </dd> <dt class="hdlist1">$site_html_head_string</dt> <dd> <p>HTML snippet to be included in the &lt;head&gt; section of each page. Can be set using <code>GITWEB_SITE_HTML_HEAD_STRING</code> at build time. No default value.</p> </dd> <dt class="hdlist1">$site_header</dt> <dd> <p>Name of a file with HTML to be included at the top of each page. Relative to the directory containing the <em>gitweb.cgi</em> script. Can be set using <code>GITWEB_SITE_HEADER</code> at build time. No default value.</p> </dd> <dt class="hdlist1">$site_footer</dt> <dd> <p>Name of a file with HTML to be included at the bottom of each page. Relative to the directory containing the <em>gitweb.cgi</em> script. Can be set using <code>GITWEB_SITE_FOOTER</code> at build time. No default value.</p> </dd> <dt class="hdlist1">$home_text</dt> <dd> <p>Name of a HTML file which, if it exists, is included on the gitweb projects overview page ("projects_list" view). Relative to the directory containing the gitweb.cgi script. Default value can be adjusted during build time using <code>GITWEB_HOMETEXT</code> variable. By default set to <em>indextext.html</em>.</p> </dd> <dt class="hdlist1">$projects_list_description_width</dt> <dd> <p>The width (in characters) of the "Description" column of the projects list. Longer descriptions will be truncated (trying to cut at word boundary); the full description is available in the <em>title</em> attribute (usually shown on mouseover). The default is 25, which might be too small if you use long project descriptions.</p> </dd> <dt class="hdlist1">$default_projects_order</dt> <dd> <p>Default value of ordering of projects on projects list page, which means the ordering used if you don&#8217;t explicitly sort projects list (if there is no "o" CGI query parameter in the URL). Valid values are "none" (unsorted), "project" (projects are by project name, i.e. path to repository relative to <code>$projectroot</code>), "descr" (project description), "owner", and "age" (by date of most current commit).</p> <div class="paragraph"> <p>Default value is "project". Unknown value means unsorted.</p> </div> </dd> </dl> </div> </div> <div class="sect2"> <h3 id="_changing_gitweb_s_behavior">Changing gitweb&#8217;s behavior</h3> <div class="paragraph"> <p>These configuration variables control <em>internal</em> gitweb behavior.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">$default_blob_plain_mimetype</dt> <dd> <p>Default mimetype for the blob_plain (raw) view, if mimetype checking doesn&#8217;t result in some other type; by default "text/plain". Gitweb guesses mimetype of a file to display based on extension of its filename, using <code>$mimetypes_file</code> (if set and file exists) and <em>/etc/mime.types</em> files (see <strong>mime.types</strong>(5) manpage; only filename extension rules are supported by gitweb).</p> </dd> <dt class="hdlist1">$default_text_plain_charset</dt> <dd> <p>Default charset for text files. If this is not set, the web server configuration will be used. Unset by default.</p> </dd> <dt class="hdlist1">$fallback_encoding</dt> <dd> <p>Gitweb assumes this charset when a line contains non-UTF-8 characters. The fallback decoding is used without error checking, so it can be even "utf-8". The value must be a valid encoding; see the <strong>Encoding::Supported</strong>(3pm) man page for a list. The default is "latin1", aka. "iso-8859-1".</p> </dd> <dt class="hdlist1">@diff_opts</dt> <dd> <p>Rename detection options for git-diff and git-diff-tree. The default is ('-M'); set it to ('-C') or ('-C', '-C') to also detect copies, or set it to () i.e. empty list if you don&#8217;t want to have renames detection.</p> <div class="paragraph"> <p><strong>Note</strong> that rename and especially copy detection can be quite CPU-intensive. Note also that non Git tools can have problems with patches generated with options mentioned above, especially when they involve file copies ('-C') or criss-cross renames ('-B').</p> </div> </dd> </dl> </div> </div> <div class="sect2"> <h3 id="_some_optional_features_and_policies">Some optional features and policies</h3> <div class="paragraph"> <p>Most of features are configured via <code>%feature</code> hash; however some of extra gitweb features can be turned on and configured using variables described below. This list beside configuration variables that control how gitweb looks does contain variables configuring administrative side of gitweb (e.g. cross-site scripting prevention; admittedly this as side effect affects how "summary" pages look like, or load limiting).</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">@git_base_url_list</dt> <dd> <p>List of Git base URLs. These URLs are used to generate URLs describing from where to fetch a project, which are shown on project summary page. The full fetch URL is "<code>$git_base_url/$project</code>", for each element of this list. You can set up multiple base URLs (for example one for <code>git://</code> protocol, and one for <code>http://</code> protocol).</p> <div class="paragraph"> <p>Note that per repository configuration can be set in <em>$GIT_DIR/cloneurl</em> file, or as values of multi-value <code>gitweb.url</code> configuration variable in project config. Per-repository configuration takes precedence over value composed from <code>@git_base_url_list</code> elements and project name.</p> </div> <div class="paragraph"> <p>You can setup one single value (single entry/item in this list) at build time by setting the <code>GITWEB_BASE_URL</code> build-time configuration variable. By default it is set to (), i.e. an empty list. This means that gitweb would not try to create project URL (to fetch) from project name.</p> </div> </dd> <dt class="hdlist1">$projects_list_group_categories</dt> <dd> <p>Whether to enable the grouping of projects by category on the project list page. The category of a project is determined by the <code>$GIT_DIR/category</code> file or the <code>gitweb.category</code> variable in each repository&#8217;s configuration. Disabled by default (set to 0).</p> </dd> <dt class="hdlist1">$project_list_default_category</dt> <dd> <p>Default category for projects for which none is specified. If this is set to the empty string, such projects will remain uncategorized and listed at the top, above categorized projects. Used only if project categories are enabled, which means if <code>$projects_list_group_categories</code> is true. By default set to "" (empty string).</p> </dd> <dt class="hdlist1">$prevent_xss</dt> <dd> <p>If true, some gitweb features are disabled to prevent content in repositories from launching cross-site scripting (XSS) attacks. Set this to true if you don&#8217;t trust the content of your repositories. False by default (set to 0).</p> </dd> <dt class="hdlist1">$maxload</dt> <dd> <p>Used to set the maximum load that we will still respond to gitweb queries. If the server load exceeds this value then gitweb will return "503 Service Unavailable" error. The server load is taken to be 0 if gitweb cannot determine its value. Currently it works only on Linux, where it uses <em>/proc/loadavg</em>; the load there is the number of active tasks on the system&#8201;&#8212;&#8201;processes that are actually running&#8201;&#8212;&#8201;averaged over the last minute.</p> <div class="paragraph"> <p>Set <code>$maxload</code> to undefined value (<code>undef</code>) to turn this feature off. The default value is 300.</p> </div> </dd> <dt class="hdlist1">$omit_age_column</dt> <dd> <p>If true, omit the column with date of the most current commit on the projects list page. It can save a bit of I/O and a fork per repository.</p> </dd> <dt class="hdlist1">$omit_owner</dt> <dd> <p>If true prevents displaying information about repository owner.</p> </dd> <dt class="hdlist1">$per_request_config</dt> <dd> <p>If this is set to code reference, it will be run once for each request. You can set parts of configuration that change per session this way. For example, one might use the following code in a gitweb configuration file</p> <div class="listingblock"> <div class="content"> <pre>our $per_request_config = sub { $ENV{GL_USER} = $cgi-&gt;remote_user || "gitweb"; };</pre> </div> </div> <div class="paragraph"> <p>If <code>$per_request_config</code> is not a code reference, it is interpreted as boolean value. If it is true gitweb will process config files once per request, and if it is false gitweb will process config files only once, each time it is executed. True by default (set to 1).</p> </div> <div class="paragraph"> <p><strong>NOTE</strong>: <code>$my_url</code>, <code>$my_uri</code>, and <code>$base_url</code> are overwritten with their default values before every request, so if you want to change them, be sure to set this variable to true or a code reference effecting the desired changes.</p> </div> <div class="paragraph"> <p>This variable matters only when using persistent web environments that serve multiple requests using single gitweb instance, like mod_perl, FastCGI or Plackup.</p> </div> </dd> </dl> </div> </div> <div class="sect2"> <h3 id="_other_variables">Other variables</h3> <div class="paragraph"> <p>Usually you should not need to change (adjust) any of configuration variables described below; they should be automatically set by gitweb to correct value.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">$version</dt> <dd> <p>Gitweb version, set automatically when creating gitweb.cgi from gitweb.perl. You might want to modify it if you are running modified gitweb, for example</p> <div class="listingblock"> <div class="content"> <pre>our $version .= " with caching";</pre> </div> </div> <div class="paragraph"> <p>if you run modified version of gitweb with caching support. This variable is purely informational, used e.g. in the "generator" meta header in HTML header.</p> </div> </dd> <dt class="hdlist1">$my_url</dt> <dt class="hdlist1">$my_uri</dt> <dd> <p>Full URL and absolute URL of the gitweb script; in earlier versions of gitweb you might have need to set those variables, but now there should be no need to do it. See <code>$per_request_config</code> if you need to set them still.</p> </dd> <dt class="hdlist1">$base_url</dt> <dd> <p>Base URL for relative URLs in pages generated by gitweb, (e.g. <code>$logo</code>, <code>$favicon</code>, <code>@stylesheets</code> if they are relative URLs), needed and used <em>&lt;base href="$base_url"&gt;</em> only for URLs with nonempty PATH_INFO. Usually gitweb sets its value correctly, and there is no need to set this variable, e.g. to $my_uri or "/". See <code>$per_request_config</code> if you need to override it anyway.</p> </dd> </dl> </div> </div> </div> </div> <div class="sect1"> <h2 id="_configuring_gitweb_features">CONFIGURING GITWEB FEATURES</h2> <div class="sectionbody"> <div class="paragraph"> <p>Many gitweb features can be enabled (or disabled) and configured using the <code>%feature</code> hash. Names of gitweb features are keys of this hash.</p> </div> <div class="paragraph"> <p>Each <code>%feature</code> hash element is a hash reference and has the following structure:</p> </div> <div class="listingblock"> <div class="content"> <pre>"&lt;feature_name&gt;" =&gt; { "sub" =&gt; &lt;feature-sub (subroutine)&gt;, "override" =&gt; &lt;allow-override (boolean)&gt;, "default" =&gt; [ &lt;options&gt;... ] },</pre> </div> </div> <div class="paragraph"> <p>Some features cannot be overridden per project. For those features the structure of appropriate <code>%feature</code> hash element has a simpler form:</p> </div> <div class="listingblock"> <div class="content"> <pre>"&lt;feature_name&gt;" =&gt; { "override" =&gt; 0, "default" =&gt; [ &lt;options&gt;... ] },</pre> </div> </div> <div class="paragraph"> <p>As one can see it lacks the 'sub' element.</p> </div> <div class="paragraph"> <p>The meaning of each part of feature configuration is described below:</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">default</dt> <dd> <p>List (array reference) of feature parameters (if there are any), used also to toggle (enable or disable) given feature.</p> <div class="paragraph"> <p>Note that it is currently <strong>always</strong> an array reference, even if feature doesn&#8217;t accept any configuration parameters, and 'default' is used only to turn it on or off. In such case you turn feature on by setting this element to <code>[1]</code>, and torn it off by setting it to <code>[0]</code>. See also the passage about the "blame" feature in the "Examples" section.</p> </div> <div class="paragraph"> <p>To disable features that accept parameters (are configurable), you need to set this element to empty list i.e. <code>[]</code>.</p> </div> </dd> <dt class="hdlist1">override</dt> <dd> <p>If this field has a true value then the given feature is overridable, which means that it can be configured (or enabled/disabled) on a per-repository basis.</p> <div class="paragraph"> <p>Usually given "&lt;feature&gt;" is configurable via the <code>gitweb.&lt;feature&gt;</code> config variable in the per-repository Git configuration file.</p> </div> <div class="paragraph"> <p><strong>Note</strong> that no feature is overridable by default.</p> </div> </dd> <dt class="hdlist1">sub</dt> <dd> <p>Internal detail of implementation. What is important is that if this field is not present then per-repository override for given feature is not supported.</p> <div class="paragraph"> <p>You wouldn&#8217;t need to ever change it in gitweb config file.</p> </div> </dd> </dl> </div> <div class="sect2"> <h3 id="_features_in_code_feature_code">Features in <code>%feature</code></h3> <div class="paragraph"> <p>The gitweb features that are configurable via <code>%feature</code> hash are listed below. This should be a complete list, but ultimately the authoritative and complete list is in gitweb.cgi source code, with features described in the comments.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">blame</dt> <dd> <p>Enable the "blame" and "blame_incremental" blob views, showing for each line the last commit that modified it; see <a href="git-blame.html">git-blame</a>(1). This can be very CPU-intensive and is therefore disabled by default.</p> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.blame</code> configuration variable (boolean).</p> </div> </dd> <dt class="hdlist1">snapshot</dt> <dd> <p>Enable and configure the "snapshot" action, which allows user to download a compressed archive of any tree or commit, as produced by <a href="git-archive.html">git-archive</a>(1) and possibly additionally compressed. This can potentially generate high traffic if you have large project.</p> <div class="paragraph"> <p>The value of 'default' is a list of names of snapshot formats, defined in <code>%known_snapshot_formats</code> hash, that you wish to offer. Supported formats include "tgz", "tbz2", "txz" (gzip/bzip2/xz compressed tar archive) and "zip"; please consult gitweb sources for a definitive list. By default only "tgz" is offered.</p> </div> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.blame</code> configuration variable, which contains a comma separated list of formats or "none" to disable snapshots. Unknown values are ignored.</p> </div> </dd> <dt class="hdlist1">grep</dt> <dd> <p>Enable grep search, which lists the files in currently selected tree (directory) containing the given string; see <a href="git-grep.html">git-grep</a>(1). This can be potentially CPU-intensive, of course. Enabled by default.</p> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.grep</code> configuration variable (boolean).</p> </div> </dd> <dt class="hdlist1">pickaxe</dt> <dd> <p>Enable the so called pickaxe search, which will list the commits that introduced or removed a given string in a file. This can be practical and quite faster alternative to "blame" action, but it is still potentially CPU-intensive. Enabled by default.</p> <div class="paragraph"> <p>The pickaxe search is described in <a href="git-log.html">git-log</a>(1) (the description of <code>-S&lt;string&gt;</code> option, which refers to pickaxe entry in <a href="gitdiffcore.html">gitdiffcore</a>(7) for more details).</p> </div> <div class="paragraph"> <p>This feature can be configured on a per-repository basis by setting repository&#8217;s <code>gitweb.pickaxe</code> configuration variable (boolean).</p> </div> </dd> <dt class="hdlist1">show-sizes</dt> <dd> <p>Enable showing size of blobs (ordinary files) in a "tree" view, in a separate column, similar to what <code>ls -l</code> does; see description of <code>-l</code> option in <a href="git-ls-tree.html">git-ls-tree</a>(1) manpage. This costs a bit of I/O. Enabled by default.</p> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.showSizes</code> configuration variable (boolean).</p> </div> </dd> <dt class="hdlist1">patches</dt> <dd> <p>Enable and configure "patches" view, which displays list of commits in email (plain text) output format; see also <a href="git-format-patch.html">git-format-patch</a>(1). The value is the maximum number of patches in a patchset generated in "patches" view. Set the <em>default</em> field to a list containing single item of or to an empty list to disable patch view, or to a list containing a single negative number to remove any limit. Default value is 16.</p> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.patches</code> configuration variable (integer).</p> </div> </dd> <dt class="hdlist1">avatar</dt> <dd> <p>Avatar support. When this feature is enabled, views such as "shortlog" or "commit" will display an avatar associated with the email of each committer and author.</p> <div class="paragraph"> <p>Currently available providers are <strong>"gravatar"</strong> and <strong>"picon"</strong>. Only one provider at a time can be selected (<em>default</em> is one element list). If an unknown provider is specified, the feature is disabled. <strong>Note</strong> that some providers might require extra Perl packages to be installed; see <em>gitweb/INSTALL</em> for more details.</p> </div> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.avatar</code> configuration variable.</p> </div> <div class="paragraph"> <p>See also <code>%avatar_size</code> with pixel sizes for icons and avatars ("default" is used for one-line like "log" and "shortlog", "double" is used for two-line like "commit", "commitdiff" or "tag"). If the default font sizes or lineheights are changed (e.g. via adding extra CSS stylesheet in <code>@stylesheets</code>), it may be appropriate to change these values.</p> </div> </dd> <dt class="hdlist1">highlight</dt> <dd> <p>Server-side syntax highlight support in "blob" view. It requires <code>$highlight_bin</code> program to be available (see the description of this variable in the "Configuration variables" section above), and therefore is disabled by default.</p> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.highlight</code> configuration variable (boolean).</p> </div> </dd> <dt class="hdlist1">remote_heads</dt> <dd> <p>Enable displaying remote heads (remote-tracking branches) in the "heads" list. In most cases the list of remote-tracking branches is an unnecessary internal private detail, and this feature is therefore disabled by default. <a href="git-instaweb.html">git-instaweb</a>(1), which is usually used to browse local repositories, enables and uses this feature.</p> <div class="paragraph"> <p>This feature can be configured on a per-repository basis via repository&#8217;s <code>gitweb.remote_heads</code> configuration variable (boolean).</p> </div> </dd> </dl> </div> <div class="paragraph"> <p>The remaining features cannot be overridden on a per project basis.</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">search</dt> <dd> <p>Enable text search, which will list the commits which match author, committer or commit text to a given string; see the description of <code>--author</code>, <code>--committer</code> and <code>--grep</code> options in <a href="git-log.html">git-log</a>(1) manpage. Enabled by default.</p> <div class="paragraph"> <p>Project specific override is not supported.</p> </div> </dd> <dt class="hdlist1">forks</dt> <dd> <p>If this feature is enabled, gitweb considers projects in subdirectories of project root (basename) to be forks of existing projects. For each project <code>$projname.git</code>, projects in the <code>$projname/</code> directory and its subdirectories will not be shown in the main projects list. Instead, a '+' mark is shown next to +$projname+, which links to a "forks" view that lists all the forks (all projects in <code>$projname/</code> subdirectory). Additionally a "forks" view for a project is linked from project summary page.</p> <div class="paragraph"> <p>If the project list is taken from a file (<code>$projects_list</code> points to a file), forks are only recognized if they are listed after the main project in that file.</p> </div> <div class="paragraph"> <p>Project specific override is not supported.</p> </div> </dd> <dt class="hdlist1">actions</dt> <dd> <p>Insert custom links to the action bar of all project pages. This allows you to link to third-party scripts integrating into gitweb.</p> <div class="paragraph"> <p>The "default" value consists of a list of triplets in the form <code>("&lt;label&gt;", "&lt;link&gt;", "&lt;position&gt;")</code> where "position" is the label after which to insert the link, "link" is a format string where <code>%n</code> expands to the project name, <code>%f</code> to the project path within the filesystem (i.e. "$projectroot/$project"), <code>%h</code> to the current hash ('h' gitweb parameter) and <code>%b</code> to the current hash base ('hb' gitweb parameter); <code>%%</code> expands to '%'.</p> </div> <div class="paragraph"> <p>For example, at the time this page was written, the <a href="http://repo.or.cz" class="bare">http://repo.or.cz</a> Git hosting site set it to the following to enable graphical log (using the third party tool <strong>git-browser</strong>):</p> </div> <div class="listingblock"> <div class="content"> <pre>$feature{'actions'}{'default'} = [ ('graphiclog', '/git-browser/by-commit.html?r=%n', 'summary')];</pre> </div> </div> <div class="paragraph"> <p>This adds a link titled "graphiclog" after the "summary" link, leading to <code>git-browser</code> script, passing <code>r=&lt;project&gt;</code> as a query parameter.</p> </div> <div class="paragraph"> <p>Project specific override is not supported.</p> </div> </dd> <dt class="hdlist1">timed</dt> <dd> <p>Enable displaying how much time and how many Git commands it took to generate and display each page in the page footer (at the bottom of page). For example the footer might contain: "This page took 6.53325 seconds and 13 Git commands to generate." Disabled by default.</p> <div class="paragraph"> <p>Project specific override is not supported.</p> </div> </dd> <dt class="hdlist1">javascript-timezone</dt> <dd> <p>Enable and configure the ability to change a common time zone for dates in gitweb output via JavaScript. Dates in gitweb output include authordate and committerdate in "commit", "commitdiff" and "log" views, and taggerdate in "tag" view. Enabled by default.</p> <div class="paragraph"> <p>The value is a list of three values: a default time zone (for if the client hasn&#8217;t selected some other time zone and saved it in a cookie), a name of cookie where to store selected time zone, and a CSS class used to mark up dates for manipulation. If you want to turn this feature off, set "default" to empty list: <code>[]</code>.</p> </div> <div class="paragraph"> <p>Typical gitweb config files will only change starting (default) time zone, and leave other elements at their default values:</p> </div> <div class="listingblock"> <div class="content"> <pre>$feature{'javascript-timezone'}{'default'}[0] = "utc";</pre> </div> </div> <div class="paragraph"> <p>The example configuration presented here is guaranteed to be backwards and forward compatible.</p> </div> <div class="paragraph"> <p>Time zone values can be "local" (for local time zone that browser uses), "utc" (what gitweb uses when JavaScript or this feature is disabled), or numerical time zones in the form of "+/-HHMM", such as "+0200".</p> </div> <div class="paragraph"> <p>Project specific override is not supported.</p> </div> </dd> <dt class="hdlist1">extra-branch-refs</dt> <dd> <p>List of additional directories under "refs" which are going to be used as branch refs. For example if you have a gerrit setup where all branches under refs/heads/ are official, push-after-review ones and branches under refs/sandbox/, refs/wip and refs/other are user ones where permissions are much wider, then you might want to set this variable as follows:</p> <div class="listingblock"> <div class="content"> <pre>$feature{'extra-branch-refs'}{'default'} = ['sandbox', 'wip', 'other'];</pre> </div> </div> <div class="paragraph"> <p>This feature can be configured on per-repository basis after setting $feature{<em>extra-branch-refs</em>}{<em>override</em>} to true, via repository&#8217;s <code>gitweb.extraBranchRefs</code> configuration variable, which contains a space separated list of refs. An example:</p> </div> <div class="listingblock"> <div class="content"> <pre>[gitweb] extraBranchRefs = sandbox wip other</pre> </div> </div> <div class="paragraph"> <p>The gitweb.extraBranchRefs is actually a multi-valued configuration variable, so following example is also correct and the result is the same as of the snippet above:</p> </div> <div class="listingblock"> <div class="content"> <pre>[gitweb] extraBranchRefs = sandbox extraBranchRefs = wip other</pre> </div> </div> <div class="paragraph"> <p>It is an error to specify a ref that does not pass "git check-ref-format" scrutiny. Duplicated values are filtered.</p> </div> </dd> </dl> </div> </div> </div> </div> <div class="sect1"> <h2 id="_examples">EXAMPLES</h2> <div class="sectionbody"> <div class="paragraph"> <p>To enable blame, pickaxe search, and snapshot support (allowing "tar.gz" and "zip" snapshots), while allowing individual projects to turn them off, put the following in your GITWEB_CONFIG file:</p> </div> <div class="literalblock"> <div class="content"> <pre>$feature{'blame'}{'default'} = [1]; $feature{'blame'}{'override'} = 1;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>$feature{'pickaxe'}{'default'} = [1]; $feature{'pickaxe'}{'override'} = 1;</pre> </div> </div> <div class="literalblock"> <div class="content"> <pre>$feature{'snapshot'}{'default'} = ['zip', 'tgz']; $feature{'snapshot'}{'override'} = 1;</pre> </div> </div> <div class="paragraph"> <p>If you allow overriding for the snapshot feature, you can specify which snapshot formats are globally disabled. You can also add any command-line options you want (such as setting the compression level). For instance, you can disable Zip compressed snapshots and set <strong>gzip</strong>(1) to run at level 6 by adding the following lines to your gitweb configuration file:</p> </div> <div class="literalblock"> <div class="content"> <pre>$known_snapshot_formats{'zip'}{'disabled'} = 1; $known_snapshot_formats{'tgz'}{'compressor'} = ['gzip','-6'];</pre> </div> </div> </div> </div> <div class="sect1"> <h2 id="_bugs">BUGS</h2> <div class="sectionbody"> <div class="paragraph"> <p>Debugging would be easier if the fallback configuration file (<code>/etc/gitweb.conf</code>) and environment variable to override its location (<em>GITWEB_CONFIG_SYSTEM</em>) had names reflecting their "fallback" role. The current names are kept to avoid breaking working setups.</p> </div> </div> </div> <div class="sect1"> <h2 id="_environment">ENVIRONMENT</h2> <div class="sectionbody"> <div class="paragraph"> <p>The location of per-instance and system-wide configuration files can be overridden using the following environment variables:</p> </div> <div class="dlist"> <dl> <dt class="hdlist1">GITWEB_CONFIG</dt> <dd> <p>Sets location of per-instance configuration file.</p> </dd> <dt class="hdlist1">GITWEB_CONFIG_SYSTEM</dt> <dd> <p>Sets location of fallback system-wide configuration file. This file is read only if per-instance one does not exist.</p> </dd> <dt class="hdlist1">GITWEB_CONFIG_COMMON</dt> <dd> <p>Sets location of common system-wide configuration file.</p> </dd> </dl> </div> </div> </div> <div class="sect1"> <h2 id="_files">FILES</h2> <div class="sectionbody"> <div class="dlist"> <dl> <dt class="hdlist1">gitweb_config.perl</dt> <dd> <p>This is default name of per-instance configuration file. The format of this file is described above.</p> </dd> <dt class="hdlist1">/etc/gitweb.conf</dt> <dd> <p>This is default name of fallback system-wide configuration file. This file is used only if per-instance configuration variable is not found.</p> </dd> <dt class="hdlist1">/etc/gitweb-common.conf</dt> <dd> <p>This is default name of common system-wide configuration file.</p> </dd> </dl> </div> </div> </div> <div class="sect1"> <h2 id="_see_also">SEE ALSO</h2> <div class="sectionbody"> <div class="paragraph"> <p><a href="gitweb.html">gitweb</a>(1), <a href="git-instaweb.html">git-instaweb</a>(1)</p> </div> <div class="paragraph"> <p><em>gitweb/README</em>, <em>gitweb/INSTALL</em></p> </div> </div> </div> <div class="sect1"> <h2 id="_git">GIT</h2> <div class="sectionbody"> <div class="paragraph"> <p>Part of the <a href="git.html">git</a>(1) suite</p> </div> </div> </div> </div> <div id="footer"> <div id="footer-text"> Last updated 2016-10-04 17:10:56 W. Europe Daylight Time </div> </div> </body> </html>
alinlupu/visualize-git
docs/git-doc/gitweb.conf.html
HTML
mit
80,506
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 999, 1011, 1011, 1031, 2065, 29464, 1033, 1028...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright (C) 2015 Swift Navigation Inc. * Contact: Joshua Gross <josh@swift-nav.com> * This source is subject to the license found in the file 'LICENSE' which must * be distributed together with this source. All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ var fs = require('fs'); var path = require('path'); var assert = require('assert'); var Readable = require('stream').Readable; var dispatch = require(path.resolve(__dirname, '../sbp/')).dispatch; var MsgPosLlh = require(path.resolve(__dirname, '../sbp/navigation')).MsgPosLlh; var MsgVelEcef = require(path.resolve(__dirname, '../sbp/navigation')).MsgVelEcef; var framedMessage = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x14, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; var corruptedMessageTooShort = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x12, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; var corruptedMessageTooLong = [0x55, 0x02, 0x02, 0xcc, 0x04, 0x16, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; var corruptedMessageExtraPreamble = [0x55, 0x55, 0x02, 0x02, 0xcc, 0x04, 0x14, 0x70, 0x3d, 0xd0, 0x18, 0xcf, 0xef, 0xff, 0xff, 0xef, 0xe8, 0xff, 0xff, 0xf0, 0x18, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x43, 0x94]; describe('dispatcher', function () { it('should read stream of bytes and dispatch callback for single framed message', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should read stream of bytes and dispatch callback for two framed message', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 2) { assert.equal(validMessages, 2); done(); } }); }); it('should read stream of bytes and dispatch callback for two framed message, with garbage in between', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage)); rs.push(new Buffer([0x54, 0x53, 0x00, 0x01])); rs.push(new Buffer(framedMessage)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 2) { assert.equal(validMessages, 2); done(); } }); }); it('should read stream of bytes and dispatch callback for three framed messages, with garbage before first message and last', function (done) { var rs = new Readable(); rs.push(new Buffer(framedMessage.slice(2))); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage.slice(1))); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage.slice(3))); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(framedMessage.slice(4))); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 3) { assert.equal(validMessages, 3); done(); } }); }); it('should read stream of bytes and dispatch callback for one valid message, ignore corrupt message', function (done) { var rs = new Readable(); rs.push(new Buffer(corruptedMessageTooShort)); rs.push(new Buffer(framedMessage)); rs.push(new Buffer(corruptedMessageTooLong)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should read stream of bytes and dispatch callback for one valid message, ignore corrupt preamble', function (done) { var rs = new Readable(); rs.push(new Buffer(corruptedMessageExtraPreamble)); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should whitelist messages properly - no whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgLlhPayload); rs.push(msgVelEcefPayload); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, function (err, framedMessage) { if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 2) { assert.equal(validMessages, 2); done(); } }); }); it('should whitelist messages properly - array whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgVelEcefPayload); rs.push(msgLlhPayload); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, [MsgPosLlh.prototype.msg_type], function (err, framedMessage) { assert.equal(framedMessage.msg_type, MsgPosLlh.prototype.msg_type); if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should whitelist messages properly - mask whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgVelEcefPayload); rs.push(msgLlhPayload); rs.push(null); var callbacks = 0; var validMessages = 0; dispatch(rs, ~MsgVelEcef.prototype.msg_type, function (err, framedMessage) { assert.equal(framedMessage.msg_type, MsgPosLlh.prototype.msg_type); if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); it('should whitelist messages properly - function whitelist', function (done) { var msgLlhPayload = new Buffer('VQEC9tciFC4nAPod4rrrtkJAE8szxBiLXsAfnaDoenNRQAAAAAAJAOyL', 'base64'); var msgVelEcefPayload = new Buffer('VQQC9tcUFC4nANoLAACG9f//o/z//wAACQBQ7A==', 'base64'); var rs = new Readable(); rs.push(msgVelEcefPayload); rs.push(msgLlhPayload); rs.push(null); var callbacks = 0; var validMessages = 0; var whitelist = function (msgType) { return msgType === MsgVelEcef.prototype.msg_type; }; dispatch(rs, whitelist, function (err, framedMessage) { assert.equal(framedMessage.msg_type, MsgVelEcef.prototype.msg_type); if (framedMessage && framedMessage.fields && framedMessage.fields.tow) { validMessages++; } if ((++callbacks) === 1) { assert.equal(validMessages, 1); done(); } }); }); });
swift-nav/libsbp
javascript/tests/test_dispatch.js
JavaScript
lgpl-3.0
8,674
[ 30522, 1013, 1008, 1008, 1008, 9385, 1006, 1039, 1007, 2325, 9170, 9163, 4297, 1012, 1008, 3967, 1024, 9122, 7977, 1026, 6498, 1030, 9170, 1011, 6583, 2615, 1012, 4012, 1028, 1008, 2023, 3120, 2003, 3395, 2000, 1996, 6105, 2179, 1999, 199...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php include("../connection.php"); $data = json_decode(file_get_contents("php://input")); $provider_id = $data->user_id; $email = $data->email; echo json_encode($provider_id); $q = "INSERT INTO Provider (ProviderID, Email) VALUES (:provider_id, :email) ON DUPLICATE KEY UPDATE Email = :email "; $query = $db->prepare($q); $query->bindParam(':provider_id', $provider_id); $query->bindParam(':email', $email); $query->execute();
PromoPass/web
endpoints/register.php
PHP
mit
519
[ 30522, 1026, 1029, 25718, 2421, 1006, 1000, 1012, 1012, 1013, 4434, 1012, 25718, 1000, 1007, 1025, 1002, 2951, 1027, 1046, 3385, 1035, 21933, 3207, 1006, 5371, 1035, 2131, 1035, 8417, 1006, 1000, 25718, 1024, 1013, 1013, 7953, 1000, 1007, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var searchData= [ ['sdio_5fisr',['sdio_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#gab47b4803bd30546e2635832b5fdb92fe',1,'nvic.h']]], ['spi1_5fisr',['spi1_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#gad680d21d3e734ad7ce84e5a9dce5af5c',1,'nvic.h']]], ['spi2_5fisr',['spi2_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#gabe80c6cda580ec6a1e915e9f7e192879',1,'nvic.h']]], ['spi3_5fisr',['spi3_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#ga433dae627c4694ab9055540a7694248d',1,'nvic.h']]], ['spi_5fclean_5fdisable',['spi_clean_disable',['../group__spi__defines.html#gaf76785dab1741f75d4fc2f03793b57d9',1,'spi_clean_disable(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaf76785dab1741f75d4fc2f03793b57d9',1,'spi_clean_disable(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable',['spi_disable',['../group__spi__defines.html#ga3a67a664d96e95e80d3308b7d53736e6',1,'spi_disable(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga3a67a664d96e95e80d3308b7d53736e6',1,'spi_disable(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5fcrc',['spi_disable_crc',['../group__spi__defines.html#ga168934fcc518d617447514ca06a48b3c',1,'spi_disable_crc(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga168934fcc518d617447514ca06a48b3c',1,'spi_disable_crc(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5ferror_5finterrupt',['spi_disable_error_interrupt',['../group__spi__defines.html#gaa84513c1f4d95c7de20b9416447c2148',1,'spi_disable_error_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaa84513c1f4d95c7de20b9416447c2148',1,'spi_disable_error_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5frx_5fbuffer_5fnot_5fempty_5finterrupt',['spi_disable_rx_buffer_not_empty_interrupt',['../group__spi__defines.html#gada77b72d4924b55840e73ed14a325978',1,'spi_disable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gada77b72d4924b55840e73ed14a325978',1,'spi_disable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5frx_5fdma',['spi_disable_rx_dma',['../group__spi__defines.html#ga010e94503b79a98060a9920fd8f50806',1,'spi_disable_rx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga010e94503b79a98060a9920fd8f50806',1,'spi_disable_rx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5fsoftware_5fslave_5fmanagement',['spi_disable_software_slave_management',['../group__spi__defines.html#ga4cf9bda5fa58c220e6d45d6a809737c4',1,'spi_disable_software_slave_management(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga4cf9bda5fa58c220e6d45d6a809737c4',1,'spi_disable_software_slave_management(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5fss_5foutput',['spi_disable_ss_output',['../group__spi__defines.html#ga8cd024f5b5f4806bbeeec58e8e79162b',1,'spi_disable_ss_output(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga8cd024f5b5f4806bbeeec58e8e79162b',1,'spi_disable_ss_output(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5ftx_5fbuffer_5fempty_5finterrupt',['spi_disable_tx_buffer_empty_interrupt',['../group__spi__defines.html#gac803fac4d999f49c7ecbda22aa5b7221',1,'spi_disable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gac803fac4d999f49c7ecbda22aa5b7221',1,'spi_disable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5ftx_5fdma',['spi_disable_tx_dma',['../group__spi__defines.html#gafc90aaa52298179b5190ee677ac5d4cc',1,'spi_disable_tx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gafc90aaa52298179b5190ee677ac5d4cc',1,'spi_disable_tx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable',['spi_enable',['../group__spi__defines.html#ga33fbdd2e4f6b876273a2b3f0e05eb6b4',1,'spi_enable(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga33fbdd2e4f6b876273a2b3f0e05eb6b4',1,'spi_enable(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5fcrc',['spi_enable_crc',['../group__spi__defines.html#ga3993016e02c92b696c8661840e602a00',1,'spi_enable_crc(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga3993016e02c92b696c8661840e602a00',1,'spi_enable_crc(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5ferror_5finterrupt',['spi_enable_error_interrupt',['../group__spi__defines.html#gaedf50e8ee8ec6f033231a2c49b4ac1a1',1,'spi_enable_error_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaedf50e8ee8ec6f033231a2c49b4ac1a1',1,'spi_enable_error_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5frx_5fbuffer_5fnot_5fempty_5finterrupt',['spi_enable_rx_buffer_not_empty_interrupt',['../group__spi__defines.html#gad05d3885fad620fc84d284fc9b42554e',1,'spi_enable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gad05d3885fad620fc84d284fc9b42554e',1,'spi_enable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5frx_5fdma',['spi_enable_rx_dma',['../group__spi__defines.html#gac860af47e3356336e01495554de5e506',1,'spi_enable_rx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gac860af47e3356336e01495554de5e506',1,'spi_enable_rx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5fsoftware_5fslave_5fmanagement',['spi_enable_software_slave_management',['../group__spi__defines.html#gab3cb4176148e6f3602a0b238f32eb83b',1,'spi_enable_software_slave_management(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gab3cb4176148e6f3602a0b238f32eb83b',1,'spi_enable_software_slave_management(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5fss_5foutput',['spi_enable_ss_output',['../group__spi__defines.html#gada533027af13ff16aceb7daad049c4e4',1,'spi_enable_ss_output(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gada533027af13ff16aceb7daad049c4e4',1,'spi_enable_ss_output(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5ftx_5fbuffer_5fempty_5finterrupt',['spi_enable_tx_buffer_empty_interrupt',['../group__spi__defines.html#ga4c552fab799a9009bc541a3fb41061fe',1,'spi_enable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga4c552fab799a9009bc541a3fb41061fe',1,'spi_enable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5ftx_5fdma',['spi_enable_tx_dma',['../group__spi__defines.html#ga74726047b7cad9c11465a3cf4d0fd090',1,'spi_enable_tx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga74726047b7cad9c11465a3cf4d0fd090',1,'spi_enable_tx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5finit_5fmaster',['spi_init_master',['../group__spi__defines.html#gaa963b02acbae0939ec4537a8136873ed',1,'spi_init_master(uint32_t spi, uint32_t br, uint32_t cpol, uint32_t cpha, uint32_t dff, uint32_t lsbfirst):&#160;spi_common_l1f124.c'],['../group__spi__file.html#gaa963b02acbae0939ec4537a8136873ed',1,'spi_init_master(uint32_t spi, uint32_t br, uint32_t cpol, uint32_t cpha, uint32_t dff, uint32_t lsbfirst):&#160;spi_common_l1f124.c']]], ['spi_5fread',['spi_read',['../group__spi__defines.html#ga1bfe6bd4512dc398cb7f680feec01b20',1,'spi_read(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga1bfe6bd4512dc398cb7f680feec01b20',1,'spi_read(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5freset',['spi_reset',['../group__spi__defines.html#gaae815897f2f548556dde9fa8ecb13058',1,'spi_reset(uint32_t spi_peripheral):&#160;spi_common_all.c'],['../group__spi__file.html#gaae815897f2f548556dde9fa8ecb13058',1,'spi_reset(uint32_t spi_peripheral):&#160;spi_common_all.c']]], ['spi_5fsend',['spi_send',['../group__spi__defines.html#ga1fcf7661af69bcf8999ae3f6d102fd8b',1,'spi_send(uint32_t spi, uint16_t data):&#160;spi_common_all.c'],['../group__spi__file.html#ga1fcf7661af69bcf8999ae3f6d102fd8b',1,'spi_send(uint32_t spi, uint16_t data):&#160;spi_common_all.c']]], ['spi_5fsend_5flsb_5ffirst',['spi_send_lsb_first',['../group__spi__defines.html#ga9f834ea1e68b2c23a4b0866f96f38578',1,'spi_send_lsb_first(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga9f834ea1e68b2c23a4b0866f96f38578',1,'spi_send_lsb_first(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fsend_5fmsb_5ffirst',['spi_send_msb_first',['../group__spi__defines.html#gae19e92c8051fe49e4eac918ee51feeac',1,'spi_send_msb_first(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gae19e92c8051fe49e4eac918ee51feeac',1,'spi_send_msb_first(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fbaudrate_5fprescaler',['spi_set_baudrate_prescaler',['../group__spi__defines.html#ga69a60fb0cd832d3b9a16ce4411328e64',1,'spi_set_baudrate_prescaler(uint32_t spi, uint8_t baudrate):&#160;spi_common_all.c'],['../group__spi__file.html#ga69a60fb0cd832d3b9a16ce4411328e64',1,'spi_set_baudrate_prescaler(uint32_t spi, uint8_t baudrate):&#160;spi_common_all.c']]], ['spi_5fset_5fbidirectional_5fmode',['spi_set_bidirectional_mode',['../group__spi__defines.html#gaf0088037e6a1aa78a9ed4c4e261a55ac',1,'spi_set_bidirectional_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaf0088037e6a1aa78a9ed4c4e261a55ac',1,'spi_set_bidirectional_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fbidirectional_5freceive_5fonly_5fmode',['spi_set_bidirectional_receive_only_mode',['../group__spi__defines.html#gaf27f88063c2cb644a2935490d61202c5',1,'spi_set_bidirectional_receive_only_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaf27f88063c2cb644a2935490d61202c5',1,'spi_set_bidirectional_receive_only_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fbidirectional_5ftransmit_5fonly_5fmode',['spi_set_bidirectional_transmit_only_mode',['../group__spi__defines.html#ga8ad1268a257456a854b960f8aa73b1ce',1,'spi_set_bidirectional_transmit_only_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga8ad1268a257456a854b960f8aa73b1ce',1,'spi_set_bidirectional_transmit_only_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fphase_5f0',['spi_set_clock_phase_0',['../group__spi__defines.html#gac01452c132ec4c5ffc5d281d43d975d7',1,'spi_set_clock_phase_0(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gac01452c132ec4c5ffc5d281d43d975d7',1,'spi_set_clock_phase_0(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fphase_5f1',['spi_set_clock_phase_1',['../group__spi__defines.html#gacd6b278668088bce197d6401787c4e62',1,'spi_set_clock_phase_1(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gacd6b278668088bce197d6401787c4e62',1,'spi_set_clock_phase_1(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fpolarity_5f0',['spi_set_clock_polarity_0',['../group__spi__defines.html#ga683b0840af6f7bee227ccb31d57dc36a',1,'spi_set_clock_polarity_0(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga683b0840af6f7bee227ccb31d57dc36a',1,'spi_set_clock_polarity_0(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fpolarity_5f1',['spi_set_clock_polarity_1',['../group__spi__defines.html#ga379382439ed44f061ab6fd4232d47319',1,'spi_set_clock_polarity_1(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga379382439ed44f061ab6fd4232d47319',1,'spi_set_clock_polarity_1(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fdff_5f16bit',['spi_set_dff_16bit',['../group__spi__defines.html#ga6665731fd5d37e5dfb00f29f859e6c9c',1,'spi_set_dff_16bit(uint32_t spi):&#160;spi_common_l1f124.c'],['../group__spi__file.html#ga6665731fd5d37e5dfb00f29f859e6c9c',1,'spi_set_dff_16bit(uint32_t spi):&#160;spi_common_l1f124.c']]], ['spi_5fset_5fdff_5f8bit',['spi_set_dff_8bit',['../group__spi__defines.html#ga715bcb5541f2908d16a661b0a6a07014',1,'spi_set_dff_8bit(uint32_t spi):&#160;spi_common_l1f124.c'],['../group__spi__file.html#ga715bcb5541f2908d16a661b0a6a07014',1,'spi_set_dff_8bit(uint32_t spi):&#160;spi_common_l1f124.c']]], ['spi_5fset_5ffull_5fduplex_5fmode',['spi_set_full_duplex_mode',['../group__spi__defines.html#ga714f48c6586abf8ce6e3e118f6303708',1,'spi_set_full_duplex_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga714f48c6586abf8ce6e3e118f6303708',1,'spi_set_full_duplex_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fmaster_5fmode',['spi_set_master_mode',['../group__spi__defines.html#gafca8671510322b29ef82b291dec68dc7',1,'spi_set_master_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gafca8671510322b29ef82b291dec68dc7',1,'spi_set_master_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnext_5ftx_5ffrom_5fbuffer',['spi_set_next_tx_from_buffer',['../group__spi__defines.html#ga0f70abf18588bb5bbe24da6457cb9ff7',1,'spi_set_next_tx_from_buffer(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga0f70abf18588bb5bbe24da6457cb9ff7',1,'spi_set_next_tx_from_buffer(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnext_5ftx_5ffrom_5fcrc',['spi_set_next_tx_from_crc',['../group__spi__defines.html#gaabd95475b2fe0fab2a7c22c5ae50aa14',1,'spi_set_next_tx_from_crc(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaabd95475b2fe0fab2a7c22c5ae50aa14',1,'spi_set_next_tx_from_crc(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnss_5fhigh',['spi_set_nss_high',['../group__spi__defines.html#gad86076b9c51c2ce18f844d42053ed8cc',1,'spi_set_nss_high(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gad86076b9c51c2ce18f844d42053ed8cc',1,'spi_set_nss_high(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnss_5flow',['spi_set_nss_low',['../group__spi__defines.html#ga47838ebf43d91e96b65338b6b0a50786',1,'spi_set_nss_low(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga47838ebf43d91e96b65338b6b0a50786',1,'spi_set_nss_low(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5freceive_5fonly_5fmode',['spi_set_receive_only_mode',['../group__spi__defines.html#gaacdf55f39a2de0f53ac356233cc34cbb',1,'spi_set_receive_only_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaacdf55f39a2de0f53ac356233cc34cbb',1,'spi_set_receive_only_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fslave_5fmode',['spi_set_slave_mode',['../group__spi__defines.html#gae9700a3a5f8301b5b3a8442d257d75dd',1,'spi_set_slave_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gae9700a3a5f8301b5b3a8442d257d75dd',1,'spi_set_slave_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fstandard_5fmode',['spi_set_standard_mode',['../group__spi__defines.html#gacebc47030a2733da436142828f0c9fa4',1,'spi_set_standard_mode(uint32_t spi, uint8_t mode):&#160;spi_common_all.c'],['../group__spi__file.html#gacebc47030a2733da436142828f0c9fa4',1,'spi_set_standard_mode(uint32_t spi, uint8_t mode):&#160;spi_common_all.c']]], ['spi_5fset_5funidirectional_5fmode',['spi_set_unidirectional_mode',['../group__spi__defines.html#ga25ed748ce16f85c263594198b702d949',1,'spi_set_unidirectional_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga25ed748ce16f85c263594198b702d949',1,'spi_set_unidirectional_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fwrite',['spi_write',['../group__spi__defines.html#ga6c3dfa86916c2c38d4a1957f4704bb47',1,'spi_write(uint32_t spi, uint16_t data):&#160;spi_common_all.c'],['../group__spi__file.html#ga6c3dfa86916c2c38d4a1957f4704bb47',1,'spi_write(uint32_t spi, uint16_t data):&#160;spi_common_all.c']]], ['spi_5fxfer',['spi_xfer',['../group__spi__defines.html#gae453ac946166bc51a42c35738d9d005b',1,'spi_xfer(uint32_t spi, uint16_t data):&#160;spi_common_all.c'],['../group__spi__file.html#gae453ac946166bc51a42c35738d9d005b',1,'spi_xfer(uint32_t spi, uint16_t data):&#160;spi_common_all.c']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/stm32f2/html/search/functions_c.js
JavaScript
gpl-3.0
15,984
[ 30522, 13075, 3945, 2850, 2696, 1027, 1031, 1031, 1005, 17371, 3695, 1035, 1019, 8873, 21338, 1005, 1010, 1031, 1005, 17371, 3695, 1035, 2003, 2099, 1005, 1010, 1031, 1005, 1012, 1012, 1013, 2177, 1035, 1035, 4642, 2509, 1035, 1035, 1050, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using Kekiri.IoC.Autofac; using NUnit.Framework; namespace Kekiri.UnitTests.IoC { [TestFixture] public class When_creating_contexts { [Test] public void If_class_has_default_constructor_then_use_it() { Assert.IsNotNull(new AutofacFluentTest<WithDefaultConstructor>().Context); } [Test] public void If_class_has_no_default_constructor_then_use_container() { Assert.IsNotNull(new AutofacFluentTest<WithNoDefaultConstructor>().Context); } #region Supporting Types public class WithDefaultConstructor { } public class WithNoDefaultConstructor { public class Dependency { } // ReSharper disable once UnusedParameter.Local public WithNoDefaultConstructor(Dependency dependency) { } } #endregion } }
jorbor/Kekiri
src/Tests/UnitTests/IoC/When_creating_contexts.cs
C#
mit
953
[ 30522, 2478, 17710, 23630, 2072, 1012, 25941, 1012, 8285, 7011, 2278, 1025, 2478, 16634, 4183, 1012, 7705, 1025, 3415, 15327, 17710, 23630, 2072, 1012, 3131, 22199, 2015, 1012, 25941, 1063, 1031, 3231, 8873, 18413, 5397, 1033, 2270, 2465, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
const log = require('app/lib/core/log') module.exports = config => props => { const [ pluginName, pluginPath, pluginExports ] = props log.trace(`Initialzing includer: ${log.ul(pluginPath)}.`) const exports = {} exports.name = pluginExports.name || pluginName exports.options = pluginExports.options exports.setOptions = newOpts => { log.trace(`Setting options for modifier: ${log.ul(pluginPath)} ${log.hl(pluginName)}.`) exports.options = newOpts } exports.configure = conf => new Promise(resolve => { log.trace(`Configuring includer ${log.hl(pluginName)}.`) config = conf exports.htmlCommentIncluder = pluginExports.plugin(pluginExports, config) if (!exports.htmlCommentIncluder) { const msg = `Could not configure includer: ${pluginName}.` log.error(msg) // return reject(msg) resolve(exports) } resolve(exports) }) return exports }
F1LT3R/markserv-cli
lib/plugin/includer.js
JavaScript
gpl-3.0
890
[ 30522, 9530, 3367, 8833, 1027, 5478, 1006, 1005, 10439, 1013, 5622, 2497, 1013, 4563, 1013, 8833, 1005, 1007, 11336, 1012, 14338, 1027, 9530, 8873, 2290, 1027, 1028, 24387, 1027, 1028, 1063, 9530, 3367, 1031, 13354, 23111, 14074, 1010, 1335...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/***************************************************************************//** * \file cyutils.c * \version 5.40 * * \brief Provides a function to handle 24-bit value writes. * ******************************************************************************** * \copyright * Copyright 2008-2016, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "cytypes.h" #if (!CY_PSOC3) /*************************************************************************** * Function Name: CySetReg24 ************************************************************************//** * * Writes a 24-bit value to the specified register. * * \param addr The address where data must be written. * \param value The data that must be written. * * \reentrant No * ***************************************************************************/ void CySetReg24(uint32 volatile * addr, uint32 value) { uint8 volatile *tmpAddr; tmpAddr = (uint8 volatile *) addr; tmpAddr[0u] = (uint8) value; tmpAddr[1u] = (uint8) (value >> 8u); tmpAddr[2u] = (uint8) (value >> 16u); } #if(CY_PSOC4) /*************************************************************************** * Function Name: CyGetReg24 ************************************************************************//** * * Reads the 24-bit value from the specified register. * * \param addr The address where data must be read. * * \reentrant No * ***************************************************************************/ uint32 CyGetReg24(uint32 const volatile * addr) { uint8 const volatile *tmpAddr; uint32 value; tmpAddr = (uint8 const volatile *) addr; value = (uint32) tmpAddr[0u]; value |= ((uint32) tmpAddr[1u] << 8u ); value |= ((uint32) tmpAddr[2u] << 16u); return(value); } #endif /*(CY_PSOC4)*/ #endif /* (!CY_PSOC3) */ /* [] END OF FILE */
techdude101/code
PSoC BLE/WS_UARTDeepSleepWakeUp/UARTDeepSleepWakeUp.cydsn/codegentemp/cyutils.c
C
gpl-3.0
2,399
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
NXT-Omni ======== Omnidirectional Robot Code for Lego NXT with RobotC. This was written for a robotics club demonstration as rapidly as possible. Since then, I've been interested in splitting its functions into headers, but the documentation for what RobotC supports and how is spotty at best.
rdbahm/NXT-Omni
README.md
Markdown
unlicense
297
[ 30522, 1050, 18413, 1011, 18168, 3490, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 18168, 3490, 4305, 2890, 7542, 2389, 8957, 3642, 2005, 23853, 1050, 18413, 2007, 8957, 2278, 1012, 2023, 2001, 2517, 2005, 1037, 21331, 2252, 10467, 2004...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: default --- <div class="container docs-container"> <div class="row"> <div class="col-md-3"> <div class="sidebar hidden-print" role="complementary"> {% include lefttree.html %} </div> </div> <div class="col-md-9" role="main"> <div class="panel docs-content"> <div class="wrapper"> <header class="post-header"> <h1 class="post-title">{{ page.title }}</h1> <!-- <p class="post-meta">{{ page.date | date: "%b %-d, %Y" }}{% if page.author %} • {{ page.author }}{% endif %}{% if page.meta %} • {{ page.meta }}{% endif %}</p> --> <div class="meta">Posted on <span class="postdate">{{ page.date | date: "%b %d, %Y" }}</span> By <a target="_blank" href="{{site.url}}">{{ site.author }}</a></div> <br /> </header> <article class="post-content"> {{ content }} </article> </div> </div> <div class="panel docs-content"> <article class="post-content"> <div class="wrapper"> {% include lessismore/comments %} </div> </div> </div> </div> </div>
bg25452/bg25452.github.io
_layouts/post.html
HTML
mit
1,215
[ 30522, 1011, 1011, 1011, 9621, 1024, 12398, 1011, 1011, 1011, 1026, 4487, 2615, 2465, 1027, 1000, 11661, 9986, 2015, 1011, 11661, 1000, 1028, 1026, 4487, 2615, 2465, 1027, 1000, 5216, 1000, 1028, 1026, 4487, 2615, 2465, 1027, 1000, 8902, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Runtime CPU detection * (C) 2009,2010,2013,2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #ifndef BOTAN_CPUID_H_ #define BOTAN_CPUID_H_ #include <botan/types.h> #include <vector> #include <string> #include <iosfwd> namespace Botan { /** * A class handling runtime CPU feature detection. It is limited to * just the features necessary to implement CPU specific code in Botan, * rather than being a general purpose utility. * * This class supports: * * - x86 features using CPUID. x86 is also the only processor with * accurate cache line detection currently. * * - PowerPC AltiVec detection on Linux, NetBSD, OpenBSD, and Darwin * * - ARM NEON and crypto extensions detection. On Linux and Android * systems which support getauxval, that is used to access CPU * feature information. Otherwise a relatively portable but * thread-unsafe mechanism involving executing probe functions which * catching SIGILL signal is used. */ class BOTAN_PUBLIC_API(2,1) CPUID final { public: /** * Probe the CPU and see what extensions are supported */ static void initialize(); static bool has_simd_32(); /** * Deprecated equivalent to * o << "CPUID flags: " << CPUID::to_string() << "\n"; */ BOTAN_DEPRECATED("Use CPUID::to_string") static void print(std::ostream& o); /** * Return a possibly empty string containing list of known CPU * extensions. Each name will be seperated by a space, and the ordering * will be arbitrary. This list only contains values that are useful to * Botan (for example FMA instructions are not checked). * * Example outputs "sse2 ssse3 rdtsc", "neon arm_aes", "altivec" */ static std::string to_string(); /** * Return a best guess of the cache line size */ static size_t cache_line_size() { if(g_processor_features == 0) { initialize(); } return g_cache_line_size; } static bool is_little_endian() { return endian_status() == ENDIAN_LITTLE; } static bool is_big_endian() { return endian_status() == ENDIAN_BIG; } enum CPUID_bits : uint64_t { #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) // These values have no relation to cpuid bitfields // SIMD instruction sets CPUID_SSE2_BIT = (1ULL << 0), CPUID_SSSE3_BIT = (1ULL << 1), CPUID_SSE41_BIT = (1ULL << 2), CPUID_SSE42_BIT = (1ULL << 3), CPUID_AVX2_BIT = (1ULL << 4), CPUID_AVX512F_BIT = (1ULL << 5), // Misc useful instructions CPUID_RDTSC_BIT = (1ULL << 10), CPUID_BMI2_BIT = (1ULL << 11), CPUID_ADX_BIT = (1ULL << 12), // Crypto-specific ISAs CPUID_AESNI_BIT = (1ULL << 16), CPUID_CLMUL_BIT = (1ULL << 17), CPUID_RDRAND_BIT = (1ULL << 18), CPUID_RDSEED_BIT = (1ULL << 19), CPUID_SHA_BIT = (1ULL << 20), #endif #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) CPUID_ALTIVEC_BIT = (1ULL << 0), CPUID_PPC_CRYPTO_BIT = (1ULL << 1), #endif #if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) CPUID_ARM_NEON_BIT = (1ULL << 0), CPUID_ARM_AES_BIT = (1ULL << 16), CPUID_ARM_PMULL_BIT = (1ULL << 17), CPUID_ARM_SHA1_BIT = (1ULL << 18), CPUID_ARM_SHA2_BIT = (1ULL << 19), #endif CPUID_INITIALIZED_BIT = (1ULL << 63) }; #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) /** * Check if the processor supports AltiVec/VMX */ static bool has_altivec() { return has_cpuid_bit(CPUID_ALTIVEC_BIT); } /** * Check if the processor supports POWER8 crypto extensions */ static bool has_ppc_crypto() { return has_cpuid_bit(CPUID_PPC_CRYPTO_BIT); } #endif #if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) /** * Check if the processor supports NEON SIMD */ static bool has_neon() { return has_cpuid_bit(CPUID_ARM_NEON_BIT); } /** * Check if the processor supports ARMv8 SHA1 */ static bool has_arm_sha1() { return has_cpuid_bit(CPUID_ARM_SHA1_BIT); } /** * Check if the processor supports ARMv8 SHA2 */ static bool has_arm_sha2() { return has_cpuid_bit(CPUID_ARM_SHA2_BIT); } /** * Check if the processor supports ARMv8 AES */ static bool has_arm_aes() { return has_cpuid_bit(CPUID_ARM_AES_BIT); } /** * Check if the processor supports ARMv8 PMULL */ static bool has_arm_pmull() { return has_cpuid_bit(CPUID_ARM_PMULL_BIT); } #endif #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) /** * Check if the processor supports RDTSC */ static bool has_rdtsc() { return has_cpuid_bit(CPUID_RDTSC_BIT); } /** * Check if the processor supports SSE2 */ static bool has_sse2() { return has_cpuid_bit(CPUID_SSE2_BIT); } /** * Check if the processor supports SSSE3 */ static bool has_ssse3() { return has_cpuid_bit(CPUID_SSSE3_BIT); } /** * Check if the processor supports SSE4.1 */ static bool has_sse41() { return has_cpuid_bit(CPUID_SSE41_BIT); } /** * Check if the processor supports SSE4.2 */ static bool has_sse42() { return has_cpuid_bit(CPUID_SSE42_BIT); } /** * Check if the processor supports AVX2 */ static bool has_avx2() { return has_cpuid_bit(CPUID_AVX2_BIT); } /** * Check if the processor supports AVX-512F */ static bool has_avx512f() { return has_cpuid_bit(CPUID_AVX512F_BIT); } /** * Check if the processor supports BMI2 */ static bool has_bmi2() { return has_cpuid_bit(CPUID_BMI2_BIT); } /** * Check if the processor supports AES-NI */ static bool has_aes_ni() { return has_cpuid_bit(CPUID_AESNI_BIT); } /** * Check if the processor supports CLMUL */ static bool has_clmul() { return has_cpuid_bit(CPUID_CLMUL_BIT); } /** * Check if the processor supports Intel SHA extension */ static bool has_intel_sha() { return has_cpuid_bit(CPUID_SHA_BIT); } /** * Check if the processor supports ADX extension */ static bool has_adx() { return has_cpuid_bit(CPUID_ADX_BIT); } /** * Check if the processor supports RDRAND */ static bool has_rdrand() { return has_cpuid_bit(CPUID_RDRAND_BIT); } /** * Check if the processor supports RDSEED */ static bool has_rdseed() { return has_cpuid_bit(CPUID_RDSEED_BIT); } #endif /* * Clear a CPUID bit * Call CPUID::initialize to reset * * This is only exposed for testing, don't use unless you know * what you are doing. */ static void clear_cpuid_bit(CPUID_bits bit) { const uint64_t mask = ~(static_cast<uint64_t>(bit)); g_processor_features &= mask; } /* * Don't call this function, use CPUID::has_xxx above * It is only exposed for the tests. */ static bool has_cpuid_bit(CPUID_bits elem) { if(g_processor_features == 0) initialize(); const uint64_t elem64 = static_cast<uint64_t>(elem); return ((g_processor_features & elem64) == elem64); } static std::vector<CPUID::CPUID_bits> bit_from_string(const std::string& tok); private: enum Endian_status : uint32_t { ENDIAN_UNKNOWN = 0x00000000, ENDIAN_BIG = 0x01234567, ENDIAN_LITTLE = 0x67452301, }; #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) || \ defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) || \ defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) static uint64_t detect_cpu_features(size_t* cache_line_size); #endif static Endian_status runtime_check_endian(); static Endian_status endian_status() { if(g_endian_status == ENDIAN_UNKNOWN) { g_endian_status = runtime_check_endian(); } return g_endian_status; } static uint64_t g_processor_features; static size_t g_cache_line_size; static Endian_status g_endian_status; }; } #endif
PikachuHy/shadowsocks-client
src/3rd_part/include/botan-2/botan/cpuid.h
C
gpl-3.0
8,642
[ 30522, 1013, 1008, 1008, 2448, 7292, 17368, 10788, 1008, 1006, 1039, 1007, 2268, 1010, 2230, 1010, 2286, 1010, 2418, 2990, 6746, 1008, 1008, 28516, 2319, 2003, 2207, 2104, 1996, 11038, 18667, 2094, 6105, 1006, 2156, 6105, 1012, 19067, 2102,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package heartdiagapp.core.io; import heartdiagapp.core.dsp.Signal; import java.util.Vector; public interface SignalParser { Signal parse(Vector lines); }
ckpp/heart-diag-app
src/HeartDiagApp/build/preprocessed/heartdiagapp/core/io/SignalParser.java
Java
gpl-3.0
161
[ 30522, 7427, 2540, 9032, 3654, 9397, 1012, 4563, 1012, 22834, 1025, 12324, 2540, 9032, 3654, 9397, 1012, 4563, 1012, 16233, 2361, 1012, 4742, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 9207, 1025, 2270, 8278, 4742, 19362, 8043, 1063, 4742,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
FROM nodesource/fedora20-base MAINTAINER William Blankenship <wblankenship@nodesource.com> RUN curl -sL -o ns.rpm https://rpm.nodesource.com/pub_4.x/fc/20/x86_64/nodejs-4.0.0-1nodesource.fc20.x86_64.rpm \ && rpm -i --nosignature --force ns.rpm \ && rm -f ns.rpm RUN npm install -g pangyp\ && ln -s $(which pangyp) $(dirname $(which pangyp))/node-gyp\ && npm cache clear\ && node-gyp configure || echo "" ENV NODE_ENV production WORKDIR /usr/src/app CMD ["npm","start"]
nodesource/docker-node
fedora/20/node/4.0.0/Dockerfile
Dockerfile
mit
476
[ 30522, 2013, 14164, 8162, 3401, 1013, 7349, 6525, 11387, 1011, 2918, 5441, 2121, 2520, 8744, 6132, 5605, 1026, 25610, 5802, 7520, 9650, 1030, 14164, 8162, 3401, 1012, 4012, 1028, 2448, 15390, 1011, 22889, 1011, 1051, 24978, 1012, 11575, 167...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Sabre\DAV\FSExt; use Sabre\DAV; use Sabre\HTTP; require_once 'Sabre/DAV/AbstractServer.php'; class ServerTest extends DAV\AbstractServer{ protected function getRootNode() { return new Directory($this->tempDir); } function testGet() { $request = new HTTP\Request('GET', '/test.txt'); $this->server->httpRequest = $request; $this->server->exec(); $this->assertEquals(200, $this->response->getStatus(), 'Invalid status code received.'); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Type' => ['application/octet-stream'], 'Content-Length' => [13], 'Last-Modified' => [HTTP\Util::toHTTPDate(new \DateTime('@' . filemtime($this->tempDir . '/test.txt')))], 'ETag' => ['"' .md5_file($this->tempDir . '/test.txt') . '"'], ], $this->response->getHeaders() ); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); } function testHEAD() { $request = new HTTP\Request('HEAD', '/test.txt'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Type' => ['application/octet-stream'], 'Content-Length' => [13], 'Last-Modified' => [HTTP\Util::toHTTPDate(new \DateTime('@' . filemtime($this->tempDir . '/test.txt')))], 'ETag' => ['"' . md5_file($this->tempDir . '/test.txt') . '"'], ], $this->response->getHeaders() ); $this->assertEquals(200,$this->response->status); $this->assertEquals('', $this->response->body); } function testPut() { $request = new HTTP\Request('PUT', '/testput.txt'); $request->setBody('Testing new file'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Length' => [0], 'ETag' => ['"' . md5('Testing new file') . '"'], ], $this->response->getHeaders()); $this->assertEquals(201, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertEquals('Testing new file',file_get_contents($this->tempDir . '/testput.txt')); } function testPutAlreadyExists() { $request = new HTTP\Request('PUT', '/test.txt', ['If-None-Match' => '*']); $request->setBody('Testing new file'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Type' => ['application/xml; charset=utf-8'], ],$this->response->getHeaders()); $this->assertEquals(412, $this->response->status); $this->assertNotEquals('Testing new file',file_get_contents($this->tempDir . '/test.txt')); } function testMkcol() { $request = new HTTP\Request('MKCOL', '/testcol'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Length' => ['0'], ],$this->response->getHeaders()); $this->assertEquals(201, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertTrue(is_dir($this->tempDir . '/testcol')); } function testPutUpdate() { $request = new HTTP\Request('PUT', '/test.txt'); $request->setBody('Testing updated file'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals('0', $this->response->getHeader('Content-Length')); $this->assertEquals(204, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertEquals('Testing updated file',file_get_contents($this->tempDir . '/test.txt')); } function testDelete() { $request = new HTTP\Request('DELETE', '/test.txt'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Length' => ['0'], ],$this->response->getHeaders()); $this->assertEquals(204, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertFalse(file_exists($this->tempDir . '/test.txt')); } function testDeleteDirectory() { mkdir($this->tempDir.'/testcol'); file_put_contents($this->tempDir.'/testcol/test.txt','Hi! I\'m a file with a short lifespan'); $request = new HTTP\Request('DELETE', '/testcol'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'X-Sabre-Version' => [DAV\Version::VERSION], 'Content-Length' => ['0'], ],$this->response->getHeaders()); $this->assertEquals(204, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertFalse(file_exists($this->tempDir . '/col')); } function testOptions() { $request = new HTTP\Request('OPTIONS', '/'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals([ 'DAV' => ['1, 3, extended-mkcol'], 'MS-Author-Via' => ['DAV'], 'Allow' => ['OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT'], 'Accept-Ranges' => ['bytes'], 'Content-Length' => ['0'], 'X-Sabre-Version'=> [DAV\Version::VERSION], ], $this->response->getHeaders()); $this->assertEquals(200, $this->response->status); $this->assertEquals('', $this->response->body); } function testMove() { mkdir($this->tempDir.'/testcol'); $request = new HTTP\Request('MOVE', '/test.txt', ['Destination' => '/testcol/test2.txt']); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(201, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertEquals([ 'Content-Length' => ['0'], 'X-Sabre-Version'=> [DAV\Version::VERSION], ],$this->response->getHeaders()); $this->assertTrue( is_file($this->tempDir . '/testcol/test2.txt') ); } /** * This test checks if it's possible to move a non-FSExt collection into a * FSExt collection. * * The moveInto function *should* ignore the object and let sabredav itself * execute the slow move. */ function testMoveOtherObject() { mkdir($this->tempDir.'/tree1'); mkdir($this->tempDir.'/tree2'); $tree = new DAV\Tree(new DAV\SimpleCollection('root', [ new DAV\FS\Directory($this->tempDir . '/tree1'), new DAV\FSExt\Directory($this->tempDir . '/tree2'), ])); $this->server->tree = $tree; $request = new HTTP\Request('MOVE', '/tree1', ['Destination' => '/tree2/tree1']); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(201, $this->response->status); $this->assertEquals('', $this->response->body); $this->assertEquals([ 'Content-Length' => ['0'], 'X-Sabre-Version'=> [DAV\Version::VERSION], ],$this->response->getHeaders()); $this->assertTrue( is_dir($this->tempDir . '/tree2/tree1') ); } }
mbadici/machinet
webservices/chwala/vendor/sabre/dav/tests/Sabre/DAV/FSExt/ServerTest.php
PHP
gpl-3.0
7,886
[ 30522, 1026, 1029, 25718, 3415, 15327, 22002, 1032, 4830, 2615, 1032, 1042, 3366, 18413, 1025, 2224, 22002, 1032, 4830, 2615, 1025, 2224, 22002, 1032, 8299, 1025, 5478, 1035, 2320, 1005, 22002, 1013, 4830, 2615, 1013, 29474, 2121, 6299, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.azurecompute.features; import static org.jclouds.Fallbacks.EmptyListOnNotFoundOr404; import java.util.List; import javax.inject.Named; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.jclouds.azurecompute.domain.RoleSize; import org.jclouds.azurecompute.xml.ListRoleSizesHandler; import org.jclouds.rest.annotations.Fallback; import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.XMLResponseParser; /** * The Service Management API includes operations for retrieving information about a subscription. * * @see <a href="http://msdn.microsoft.com/en-us/library/gg715315">docs</a> */ @Headers(keys = "x-ms-version", values = "{jclouds.api-version}") @Consumes(MediaType.APPLICATION_XML) public interface SubscriptionApi { /** * The List Role Sizes operation lists the role sizes that are available under the specified subscription. */ @Named("ListRoleSizes") @GET @Path("/rolesizes") @XMLResponseParser(ListRoleSizesHandler.class) @Fallback(EmptyListOnNotFoundOr404.class) List<RoleSize> listRoleSizes(); }
hardfish/justTest
azurecompute/src/main/java/org/jclouds/azurecompute/features/SubscriptionApi.java
Java
apache-2.0
1,968
[ 30522, 1013, 1008, 1008, 7000, 2000, 1996, 15895, 4007, 3192, 1006, 2004, 2546, 1007, 2104, 2028, 2030, 2062, 1008, 12130, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 5500, 2007, 1008, 2023, 2147, 2005, 3176, 2592, 4953, 9385, 6095, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/***************************************************************************** * * Filename: * --------- * ccci_md.h * * Project: * -------- * Andes * * Description: * ------------ * MT65XX Modem initialization and handshake header file * ****************************************************************************/ #ifndef __CCCI_MD_H__ #define __CCCI_MD_H__ #include <linux/interrupt.h> #include <linux/spinlock.h> #define CCCI_SYSFS_MD_INIT "modem" #define CCCI_SYSFS_MD_BOOT_ATTR "boot" #define MD_BOOT_CMD_CHAR '0' #define NORMAL_BOOT_ID 0 #define META_BOOT_ID 1 /* #define MD_RUNTIME_ADDR (CCIF_BASE + 0x0140) */ /* #define SLEEP_CON 0xF0001204 */ /* #define CCCI_CURRENT_VERSION 0x00000923 */ #define NR_CCCI_RESET_USER 10 #define NR_CCCI_RESET_USER_NAME 16 #define CCCI_UART_PORT_NUM 8 #define CCCI_MD_EXCEPTION 0x1 #define CCCI_MD_RESET 0x2 #define CCCI_MD_BOOTUP 0x3 #define CCCI_MD_STOP 0x4 #define LOCK_MD_SLP 0x1 #define UNLOCK_MD_SLP 0x0 #define MD_IMG_MAX_CNT 0x4 /*-----------------------------------------------------------*/ /* Device ID assignment */ #define CCCI_TTY_DEV_MAJOR (169) /* (0: Modem; 1: Meta; 2:IPC) */ enum { MD_BOOT_STAGE_0 = 0, MD_BOOT_STAGE_1 = 1, MD_BOOT_STAGE_2 = 2, MD_BOOT_STAGE_EXCEPTION = 3 }; enum { MD_INIT_START_BOOT = 0x00000000, MD_INIT_CHK_ID = 0x5555FFFF, MD_EX = 0x00000004, MD_EX_CHK_ID = 0x45584350, MD_EX_REC_OK = 0x00000006, MD_EX_REC_OK_CHK_ID = 0x45524543, MD_EX_RESUME_CHK_ID = 0x7, CCCI_DRV_VER_ERROR = 0x5, /* System channel, AP->MD || AP<-->MD message start from 0x100 */ /* MD_DORMANT_NOTIFY = 0x100, MD_SLP_REQUEST = 0x101, MD_TX_POWER = 0x102, MD_RF_TEMPERATURE = 0x103, MD_RF_TEMPERATURE_3G = 0x104, MD_GET_BATTERY_INFO = 0x105, */ /* System channel, MD --> AP message start from 0x1000 */ MD_WDT_MONITOR = 0x1000, MD_WAKEN_UP = 0x10000, }; enum { ER_MB_START_CMD = -1, ER_MB_CHK_ID = -2, ER_MB_BOOT_READY = -3, ER_MB_UNKNOW_STAGE = -4 }; enum { MD_EX_TYPE_INVALID = 0, MD_EX_TYPE_UNDEF = 1, MD_EX_TYPE_SWI = 2, MD_EX_TYPE_PREF_ABT = 3, MD_EX_TYPE_DATA_ABT = 4, MD_EX_TYPE_ASSERT = 5, MD_EX_TYPE_FATALERR_TASK = 6, MD_EX_TYPE_FATALERR_BUF = 7, MD_EX_TYPE_LOCKUP = 8, MD_EX_TYPE_ASSERT_DUMP = 9, MD_EX_TYPE_ASSERT_FAIL = 10, DSP_EX_TYPE_ASSERT = 11, DSP_EX_TYPE_EXCEPTION = 12, DSP_EX_FATAL_ERROR = 13, NUM_EXCEPTION }; #define MD_EX_TYPE_EMI_CHECK 99 enum { MD_EE_FLOW_START = 0, MD_EE_DUMP_ON_GOING, MD_STATE_UPDATE, MD_EE_MSG_GET, MD_EE_TIME_OUT_SET, MD_EE_OK_MSG_GET, MD_EE_FOUND_BY_ISR, MD_EE_FOUND_BY_TX, MD_EE_PENDING_TOO_LONG, MD_EE_INFO_OFFSET = 20, MD_EE_EXCP_OCCUR = 20, MD_EE_AP_MASK_I_BIT_TOO_LONG = 21, }; enum { MD_EE_CASE_NORMAL = 0, MD_EE_CASE_ONLY_EX, MD_EE_CASE_ONLY_EX_OK, MD_EE_CASE_TX_TRG, MD_EE_CASE_ISR_TRG, MD_EE_CASE_NO_RESPONSE, MD_EE_CASE_AP_MASK_I_BIT_TOO_LONG, }; #ifdef AP_MD_EINT_SHARE_DATA enum { CCCI_EXCH_CORE_AWAKEN = 0, CCCI_EXCH_CORE_SLEEP = 1, CCCI_EXCH_CORE_SLUMBER = 2 }; #endif /* CCCI system message */ enum { CCCI_SYS_MSG_RESET_MD = 0x20100406 }; /* MD Message, this is for user space deamon use */ enum { CCCI_MD_MSG_BOOT_READY = 0xFAF50001, CCCI_MD_MSG_BOOT_UP = 0xFAF50002, CCCI_MD_MSG_EXCEPTION = 0xFAF50003, CCCI_MD_MSG_RESET = 0xFAF50004, CCCI_MD_MSG_RESET_RETRY = 0xFAF50005, CCCI_MD_MSG_READY_TO_RESET = 0xFAF50006, CCCI_MD_MSG_BOOT_TIMEOUT = 0xFAF50007, CCCI_MD_MSG_STOP_MD_REQUEST = 0xFAF50008, CCCI_MD_MSG_START_MD_REQUEST = 0xFAF50009, CCCI_MD_MSG_ENTER_FLIGHT_MODE = 0xFAF5000A, CCCI_MD_MSG_LEAVE_FLIGHT_MODE = 0xFAF5000B, CCCI_MD_MSG_POWER_ON_REQUEST = 0xFAF5000C, CCCI_MD_MSG_POWER_DOWN_REQUEST = 0xFAF5000D, CCCI_MD_MSG_SEND_BATTERY_INFO = 0xFAF5000E, CCCI_MD_MSG_NOTIFY = 0xFAF5000F, CCCI_MD_MSG_STORE_NVRAM_MD_TYPE = 0xFAF50010, CCCI_MD_MSG_CFG_UPDATE = 0xFAF50011, }; /* MD Status, this is for user space deamon use */ enum { CCCI_MD_STA_BOOT_READY = 0, CCCI_MD_STA_BOOT_UP = 1, CCCI_MD_STA_RESET = 2, }; #if 0 /* MODEM MAUI SW ASSERT LOG */ struct modem_assert_log { char ex_type; char ex_nvram; short ex_serial; char data1[212]; char filename[24]; int linenumber; char data2[268]; }; /* MODEM MAUI SW FATAL ERROR LOG */ struct modem_fatalerr_log { char ex_type; char ex_nvram; short ex_serial; char data1[212]; int err_code1; int err_code2; char data2[288]; }; #endif struct cores_sleep_info { unsigned char AP_Sleep; unsigned char padding1[3]; unsigned int RTC_AP_WakeUp; unsigned int AP_SettleTime; /* clock settle duration */ unsigned char MD_Sleep; unsigned char padding2[3]; unsigned int RTC_MD_WakeUp; unsigned int RTC_MD_Settle_OK; /* clock settle done time */ }; /* MODEM MAUI Exception header (4 bytes)*/ struct EX_HEADER_T { unsigned char ex_type; unsigned char ex_nvram; unsigned short ex_serial_num; }; /* MODEM MAUI Environment information (164 bytes) */ struct EX_ENVINFO_T { unsigned char boot_mode; unsigned char reserved1[8]; unsigned char execution_unit[8]; unsigned char reserved2[147]; }; /* MODEM MAUI Special for fatal error (8 bytes)*/ struct EX_FATALERR_CODE_T { unsigned int code1; unsigned int code2; }; /* MODEM MAUI fatal error (296 bytes)*/ struct EX_FATALERR_T { struct EX_FATALERR_CODE_T error_code; unsigned char reserved1[288]; }; /* MODEM MAUI Assert fail (296 bytes)*/ struct EX_ASSERTFAIL_T { unsigned char filename[24]; unsigned int linenumber; unsigned int parameters[3]; unsigned char reserved1[256]; }; /* MODEM MAUI Globally exported data structure (300 bytes) */ union EX_CONTENT_T { struct EX_FATALERR_T fatalerr; struct EX_ASSERTFAIL_T assert; }; /* MODEM MAUI Standard structure of an exception log ( */ struct EX_LOG_T { struct EX_HEADER_T header; unsigned char reserved1[12]; struct EX_ENVINFO_T envinfo; unsigned char reserved2[36]; union EX_CONTENT_T content; }; struct core_eint_config { unsigned char eint_no; unsigned char Sensitivity; unsigned char ACT_Polarity; unsigned char Dbounce_En; unsigned int Dbounce_ms; }; struct ccci_cores_exch_data { struct cores_sleep_info sleep_info; unsigned int report_os_tick; /* report OS Tick Periodic in second unit */ /* ( 0 = disable ) */ unsigned int nr_eint_config; unsigned int eint_config_offset; /* offset from SysShareMemBase for struct coreeint_config */ }; #define CCCI_SYS_SMEM_SIZE sizeof(struct ccci_cores_exch_data) struct ccci_reset_sta { int is_allocate; int is_reset; char name[NR_CCCI_RESET_USER_NAME]; }; struct modem_runtime_t { int Prefix; /* "CCIF" */ int Platform_L; /* Hardware Platform String ex: "MT6589E1" */ int Platform_H; int DriverVersion; /* 0x20121001 since W12.39 */ int BootChannel; /* Channel to ACK AP with boot ready */ int BootingStartID; /* MD is booting. NORMAL_BOOT_ID or META_BOOT_ID */ int BootAttributes; /* Attributes passing from AP to MD Booting */ int BootReadyID; /* MD response ID if boot successful and ready */ int MdlogShareMemBase; int MdlogShareMemSize; int PcmShareMemBase; int PcmShareMemSize; int UartPortNum; int UartShareMemBase[CCCI_UART_PORT_NUM]; int UartShareMemSize[CCCI_UART_PORT_NUM]; int FileShareMemBase; int FileShareMemSize; int RpcShareMemBase; int RpcShareMemSize; int PmicShareMemBase; int PmicShareMemSize; int ExceShareMemBase; int ExceShareMemSize; /* 512 Bytes Required */ int SysShareMemBase; int SysShareMemSize; int IPCShareMemBase; int IPCShareMemSize; int MDULNetShareMemBase; int MDULNetShareMemSize; int MDDLNetShareMemBase; int MDDLNetShareMemSize; int NetPortNum; int NetULCtrlShareMemBase[NET_PORT_NUM]; /* <<< Current NET_PORT_NUM is 4 */ int NetULCtrlShareMemSize[NET_PORT_NUM]; int NetDLCtrlShareMemBase[NET_PORT_NUM]; int NetDLCtrlShareMemSize[NET_PORT_NUM]; int MDExExpInfoBase; /* md exception expand info memory */ int MDExExpInfoSize; int IPCMDIlmShareMemBase; int IPCMDIlmShareMemSize; int MiscInfoBase; int MiscInfoSize; int CheckSum; int Postfix; /* "CCIF" */ }; #define CCCI_MD_RUNTIME_DATA_SMEM_SIZE (sizeof(struct modem_runtime_t)) struct modem_runtime_info_tag_t { int prefix; /* "CCIF" */ int platform_L; /* Hardware platform string. ex: 'TK6516E0' */ int platform_H; int driver_version; /* 0x00000923 since W09.23 */ int runtime_data_base; int runtime_data_size; int postfix; /* "CCIF" */ }; struct modem_exception_exp_t { int exception_occur; int send_time; int wait_time; }; struct MD_CALL_BACK_QUEUE { void (*call) (struct MD_CALL_BACK_QUEUE *, unsigned long data); struct MD_CALL_BACK_QUEUE *next; }; struct MD_CALL_BACK_HEAD_T { spinlock_t lock; struct MD_CALL_BACK_QUEUE *next; int is_busy; struct tasklet_struct tasklet; }; typedef int (*ccci_cores_sleep_info_base_req) (void *); typedef int (*ccci_core_eint_config_setup) (int, void *); int __init ccci_md_init_mod_init(void); void __exit ccci_md_init_mod_exit(void); int ccci_mdlog_base_req(int md_id, void *addr_vir, void *addr_phy, unsigned int *len); int ccci_pcm_base_req(int md_id, void *addr_vir, void *addr_phy, unsigned int *len); int ccci_uart_base_req(int md_id, int port, void *addr_vir, void *addr_phy, unsigned int *len); int ccci_fs_base_req(int md_id, void *addr_vir, void *addr_phy, unsigned int *len); int ccci_rpc_base_req(int md_id, int *addr_vir, int *addr_phy, int *len); int ccci_pmic_base_req(int md_id, void *addr_vir, void *addr_phy, int *len); int ccci_ipc_base_req(int md_id, void *addr_vir, void *addr_phy, int *len); int ccmni_v2_ul_base_req(int md_id, void *addr_vir, void *addr_phy); int ccmni_v2_dl_base_req(int md_id, void *addr_vir, void *addr_phy); int ccci_ccmni_v2_ctl_mem_base_req(int md_id, int port, int *addr_virt, int *addr_phy, int *len); int md_register_call_chain(int md_id, struct MD_CALL_BACK_QUEUE *queue); int md_unregister_call_chain(int md_id, struct MD_CALL_BACK_QUEUE *queue); void md_call_chain(struct MD_CALL_BACK_HEAD_T *head, unsigned long data); int ccci_reset_register(int md_id, char *name); int ccci_user_ready_to_reset(int md_id, int handle); int get_curr_md_state(int md_id); void check_data_connected(int md_id, int channel); /* extern int ccci_sys_smem_base_phy; */ extern int ccci_smem_size; extern int *ccci_smem_virt; extern dma_addr_t ccci_smem_phy; extern int is_first_boot; extern struct MD_CALL_BACK_HEAD_T md_notifier; #endif /* __CCCI_MD_H__ */
andrea2107/android_kernel_xiaomi_hermes
drivers/misc/mediatek/dual_ccci/include/ccci_md.h
C
gpl-2.0
10,388
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
export { enableDebugTools, disableDebugTools } from 'angular2/src/tools/tools';
binariedMe/blogging
node_modules/angular2/tools.d.ts
TypeScript
mit
80
[ 30522, 9167, 1063, 9124, 15878, 15916, 3406, 27896, 1010, 9776, 15878, 15916, 3406, 27896, 1065, 2013, 1005, 16108, 2475, 1013, 5034, 2278, 1013, 5906, 1013, 5906, 1005, 1025, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from django.contrib import admin from modeltranslation.admin import TabbedTranslationAdmin from .models import Person, Office, Tag class PersonAdmin(TabbedTranslationAdmin): list_display = ('name', 'surname', 'security_level', 'gender') list_filter = ('security_level', 'tags', 'office', 'name', 'gender') actions = ['copy_100'] def copy_100(self, request, queryset): for item in queryset.all(): item.populate() copy_100.short_description = 'Copy 100 objects with random data' class PersonStackedInline(admin.TabularInline): model = Person extra = 0 class OfficeAdmin(admin.ModelAdmin): inlines = (PersonStackedInline,) list_display = ('office', 'address') class TagAdmin(admin.ModelAdmin): list_display = ('name',) admin.site.register(Person, PersonAdmin) admin.site.register(Office, OfficeAdmin) admin.site.register(Tag, TagAdmin)
mtrgroup/django-mtr-utils
tests/app/admin.py
Python
mit
908
[ 30522, 2013, 6520, 23422, 1012, 9530, 18886, 2497, 12324, 4748, 10020, 2013, 2944, 6494, 3619, 13490, 1012, 4748, 10020, 12324, 21628, 8270, 6494, 3619, 13490, 4215, 10020, 2013, 1012, 4275, 12324, 2711, 1010, 2436, 1010, 6415, 2465, 16115, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFormation.Model { /// <summary> /// The input for <a>UpdateStack</a> action. /// </summary> public partial class UpdateStackRequest : AmazonCloudFormationRequest { /// <summary> /// Default Constructor /// </summary> public UpdateStackRequest() { this._notificationARNs = new AutoConstructedList<string>(); } } }
rafd123/aws-sdk-net
sdk/src/Services/CloudFormation/Custom/Model/UpdateStackRequest.Extensions.cs
C#
apache-2.0
1,177
[ 30522, 1013, 1008, 1008, 9385, 2230, 1011, 2286, 9733, 1012, 4012, 1010, 4297, 1012, 2030, 2049, 18460, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.cluster.routing; import com.carrotsearch.hppc.ObjectIntHashMap; import com.carrotsearch.hppc.cursors.ObjectCursor; import org.apache.lucene.util.CollectionUtil; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlocks; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; /** * {@link RoutingNodes} represents a copy the routing information contained in * the {@link ClusterState cluster state}. */ public class RoutingNodes implements Iterable<RoutingNode> { private final MetaData metaData; private final ClusterBlocks blocks; private final RoutingTable routingTable; private final Map<String, RoutingNode> nodesToShards = new HashMap<>(); private final UnassignedShards unassignedShards = new UnassignedShards(this); private final Map<ShardId, List<ShardRouting>> assignedShards = new HashMap<>(); private final ImmutableOpenMap<String, ClusterState.Custom> customs; private final boolean readOnly; private int inactivePrimaryCount = 0; private int inactiveShardCount = 0; private int relocatingShards = 0; private final Map<String, ObjectIntHashMap<String>> nodesPerAttributeNames = new HashMap<>(); private final Map<String, Recoveries> recoveryiesPerNode = new HashMap<>(); public RoutingNodes(ClusterState clusterState) { this(clusterState, true); } public RoutingNodes(ClusterState clusterState, boolean readOnly) { this.readOnly = readOnly; this.metaData = clusterState.metaData(); this.blocks = clusterState.blocks(); this.routingTable = clusterState.routingTable(); this.customs = clusterState.customs(); Map<String, List<ShardRouting>> nodesToShards = new HashMap<>(); // fill in the nodeToShards with the "live" nodes for (ObjectCursor<DiscoveryNode> cursor : clusterState.nodes().dataNodes().values()) { nodesToShards.put(cursor.value.id(), new ArrayList<>()); } // fill in the inverse of node -> shards allocated // also fill replicaSet information for (ObjectCursor<IndexRoutingTable> indexRoutingTable : routingTable.indicesRouting().values()) { for (IndexShardRoutingTable indexShard : indexRoutingTable.value) { assert indexShard.primary != null; for (ShardRouting shard : indexShard) { // to get all the shards belonging to an index, including the replicas, // we define a replica set and keep track of it. A replica set is identified // by the ShardId, as this is common for primary and replicas. // A replica Set might have one (and not more) replicas with the state of RELOCATING. if (shard.assignedToNode()) { List<ShardRouting> entries = nodesToShards.computeIfAbsent(shard.currentNodeId(), k -> new ArrayList<>()); final ShardRouting sr = getRouting(shard, readOnly); entries.add(sr); assignedShardsAdd(sr); if (shard.relocating()) { relocatingShards++; entries = nodesToShards.computeIfAbsent(shard.relocatingNodeId(), k -> new ArrayList<>()); // add the counterpart shard with relocatingNodeId reflecting the source from which // it's relocating from. ShardRouting targetShardRouting = shard.buildTargetRelocatingShard(); addInitialRecovery(targetShardRouting); if (readOnly) { targetShardRouting.freeze(); } entries.add(targetShardRouting); assignedShardsAdd(targetShardRouting); } else if (shard.active() == false) { // shards that are initializing without being relocated if (shard.primary()) { inactivePrimaryCount++; } inactiveShardCount++; addInitialRecovery(shard); } } else { final ShardRouting sr = getRouting(shard, readOnly); assignedShardsAdd(sr); unassignedShards.add(sr); } } } } for (Map.Entry<String, List<ShardRouting>> entry : nodesToShards.entrySet()) { String nodeId = entry.getKey(); this.nodesToShards.put(nodeId, new RoutingNode(nodeId, clusterState.nodes().get(nodeId), entry.getValue())); } } private void addRecovery(ShardRouting routing) { addRecovery(routing, true, false); } private void removeRecovery(ShardRouting routing) { addRecovery(routing, false, false); } public void addInitialRecovery(ShardRouting routing) { addRecovery(routing,true, true); } private void addRecovery(final ShardRouting routing, final boolean increment, final boolean initializing) { final int howMany = increment ? 1 : -1; assert routing.initializing() : "routing must be initializing: " + routing; Recoveries.getOrAdd(recoveryiesPerNode, routing.currentNodeId()).addIncoming(howMany); final String sourceNodeId; if (routing.relocatingNodeId() != null) { // this is a relocation-target sourceNodeId = routing.relocatingNodeId(); if (routing.primary() && increment == false) { // primary is done relocating int numRecoveringReplicas = 0; for (ShardRouting assigned : assignedShards(routing)) { if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) { numRecoveringReplicas++; } } // we transfer the recoveries to the relocated primary recoveryiesPerNode.get(sourceNodeId).addOutgoing(-numRecoveringReplicas); recoveryiesPerNode.get(routing.currentNodeId()).addOutgoing(numRecoveringReplicas); } } else if (routing.primary() == false) { // primary without relocationID is initial recovery ShardRouting primary = findPrimary(routing); if (primary == null && initializing) { primary = routingTable.index(routing.index().getName()).shard(routing.shardId().id()).primary; } else if (primary == null) { throw new IllegalStateException("replica is initializing but primary is unassigned"); } sourceNodeId = primary.currentNodeId(); } else { sourceNodeId = null; } if (sourceNodeId != null) { Recoveries.getOrAdd(recoveryiesPerNode, sourceNodeId).addOutgoing(howMany); } } public int getIncomingRecoveries(String nodeId) { return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getIncoming(); } public int getOutgoingRecoveries(String nodeId) { return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getOutgoing(); } private ShardRouting findPrimary(ShardRouting routing) { List<ShardRouting> shardRoutings = assignedShards.get(routing.shardId()); ShardRouting primary = null; if (shardRoutings != null) { for (ShardRouting shardRouting : shardRoutings) { if (shardRouting.primary()) { if (shardRouting.active()) { return shardRouting; } else if (primary == null) { primary = shardRouting; } else if (primary.relocatingNodeId() != null) { primary = shardRouting; } } } } return primary; } private static ShardRouting getRouting(ShardRouting src, boolean readOnly) { if (readOnly) { src.freeze(); // we just freeze and reuse this instance if we are read only } else { src = new ShardRouting(src); } return src; } @Override public Iterator<RoutingNode> iterator() { return Collections.unmodifiableCollection(nodesToShards.values()).iterator(); } public RoutingTable routingTable() { return routingTable; } public RoutingTable getRoutingTable() { return routingTable(); } public MetaData metaData() { return this.metaData; } public MetaData getMetaData() { return metaData(); } public ClusterBlocks blocks() { return this.blocks; } public ClusterBlocks getBlocks() { return this.blocks; } public ImmutableOpenMap<String, ClusterState.Custom> customs() { return this.customs; } public <T extends ClusterState.Custom> T custom(String type) { return (T) customs.get(type); } public UnassignedShards unassigned() { return this.unassignedShards; } public RoutingNodesIterator nodes() { return new RoutingNodesIterator(nodesToShards.values().iterator()); } public RoutingNode node(String nodeId) { return nodesToShards.get(nodeId); } public ObjectIntHashMap<String> nodesPerAttributesCounts(String attributeName) { ObjectIntHashMap<String> nodesPerAttributesCounts = nodesPerAttributeNames.get(attributeName); if (nodesPerAttributesCounts != null) { return nodesPerAttributesCounts; } nodesPerAttributesCounts = new ObjectIntHashMap<>(); for (RoutingNode routingNode : this) { String attrValue = routingNode.node().attributes().get(attributeName); nodesPerAttributesCounts.addTo(attrValue, 1); } nodesPerAttributeNames.put(attributeName, nodesPerAttributesCounts); return nodesPerAttributesCounts; } /** * Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned primaries even if the * primaries are marked as temporarily ignored. */ public boolean hasUnassignedPrimaries() { return unassignedShards.getNumPrimaries() + unassignedShards.getNumIgnoredPrimaries() > 0; } /** * Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned shards even if the * shards are marked as temporarily ignored. * @see UnassignedShards#isEmpty() * @see UnassignedShards#isIgnoredEmpty() */ public boolean hasUnassignedShards() { return unassignedShards.isEmpty() == false || unassignedShards.isIgnoredEmpty() == false; } public boolean hasInactivePrimaries() { return inactivePrimaryCount > 0; } public boolean hasInactiveShards() { return inactiveShardCount > 0; } public int getRelocatingShardCount() { return relocatingShards; } /** * Returns the active primary shard for the given ShardRouting or <code>null</code> if * no primary is found or the primary is not active. */ public ShardRouting activePrimary(ShardRouting shard) { for (ShardRouting shardRouting : assignedShards(shard.shardId())) { if (shardRouting.primary() && shardRouting.active()) { return shardRouting; } } return null; } /** * Returns one active replica shard for the given ShardRouting shard ID or <code>null</code> if * no active replica is found. */ public ShardRouting activeReplica(ShardRouting shard) { for (ShardRouting shardRouting : assignedShards(shard.shardId())) { if (!shardRouting.primary() && shardRouting.active()) { return shardRouting; } } return null; } /** * Returns all shards that are not in the state UNASSIGNED with the same shard * ID as the given shard. */ public Iterable<ShardRouting> assignedShards(ShardRouting shard) { return assignedShards(shard.shardId()); } /** * Returns <code>true</code> iff all replicas are active for the given shard routing. Otherwise <code>false</code> */ public boolean allReplicasActive(ShardRouting shardRouting) { final List<ShardRouting> shards = assignedShards(shardRouting.shardId()); if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index().getName()).shard(shardRouting.id()).size()) { return false; // if we are empty nothing is active if we have less than total at least one is unassigned } for (ShardRouting shard : shards) { if (!shard.active()) { return false; } } return true; } public List<ShardRouting> shards(Predicate<ShardRouting> predicate) { List<ShardRouting> shards = new ArrayList<>(); for (RoutingNode routingNode : this) { for (ShardRouting shardRouting : routingNode) { if (predicate.test(shardRouting)) { shards.add(shardRouting); } } } return shards; } public List<ShardRouting> shardsWithState(ShardRoutingState... state) { // TODO these are used on tests only - move into utils class List<ShardRouting> shards = new ArrayList<>(); for (RoutingNode routingNode : this) { shards.addAll(routingNode.shardsWithState(state)); } for (ShardRoutingState s : state) { if (s == ShardRoutingState.UNASSIGNED) { unassigned().forEach(shards::add); break; } } return shards; } public List<ShardRouting> shardsWithState(String index, ShardRoutingState... state) { // TODO these are used on tests only - move into utils class List<ShardRouting> shards = new ArrayList<>(); for (RoutingNode routingNode : this) { shards.addAll(routingNode.shardsWithState(index, state)); } for (ShardRoutingState s : state) { if (s == ShardRoutingState.UNASSIGNED) { for (ShardRouting unassignedShard : unassignedShards) { if (unassignedShard.index().equals(index)) { shards.add(unassignedShard); } } break; } } return shards; } public String prettyPrint() { StringBuilder sb = new StringBuilder("routing_nodes:\n"); for (RoutingNode routingNode : this) { sb.append(routingNode.prettyPrint()); } sb.append("---- unassigned\n"); for (ShardRouting shardEntry : unassignedShards) { sb.append("--------").append(shardEntry.shortSummary()).append('\n'); } return sb.toString(); } /** * Moves a shard from unassigned to initialize state * * @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated. */ public void initialize(ShardRouting shard, String nodeId, @Nullable String existingAllocationId, long expectedSize) { ensureMutable(); assert shard.unassigned() : shard; shard.initialize(nodeId, existingAllocationId, expectedSize); node(nodeId).add(shard); inactiveShardCount++; if (shard.primary()) { inactivePrimaryCount++; } addRecovery(shard); assignedShardsAdd(shard); } /** * Relocate a shard to another node, adding the target initializing * shard as well as assigning it. And returning the target initializing * shard. */ public ShardRouting relocate(ShardRouting shard, String nodeId, long expectedShardSize) { ensureMutable(); relocatingShards++; shard.relocate(nodeId, expectedShardSize); ShardRouting target = shard.buildTargetRelocatingShard(); node(target.currentNodeId()).add(target); assignedShardsAdd(target); addRecovery(target); return target; } /** * Mark a shard as started and adjusts internal statistics. */ public void started(ShardRouting shard) { ensureMutable(); assert !shard.active() : "expected an initializing shard " + shard; if (shard.relocatingNodeId() == null) { // if this is not a target shard for relocation, we need to update statistics inactiveShardCount--; if (shard.primary()) { inactivePrimaryCount--; } } removeRecovery(shard); shard.moveToStarted(); } /** * Cancels a relocation of a shard that shard must relocating. */ public void cancelRelocation(ShardRouting shard) { ensureMutable(); relocatingShards--; shard.cancelRelocation(); } /** * swaps the status of a shard, making replicas primary and vice versa. * * @param shards the shard to have its primary status swapped. */ public void swapPrimaryFlag(ShardRouting... shards) { ensureMutable(); for (ShardRouting shard : shards) { if (shard.primary()) { shard.moveFromPrimary(); if (shard.unassigned()) { unassignedShards.primaries--; } } else { shard.moveToPrimary(); if (shard.unassigned()) { unassignedShards.primaries++; } } } } private static final List<ShardRouting> EMPTY = Collections.emptyList(); private List<ShardRouting> assignedShards(ShardId shardId) { final List<ShardRouting> replicaSet = assignedShards.get(shardId); return replicaSet == null ? EMPTY : Collections.unmodifiableList(replicaSet); } /** * Cancels the give shard from the Routing nodes internal statistics and cancels * the relocation if the shard is relocating. */ private void remove(ShardRouting shard) { ensureMutable(); if (!shard.active() && shard.relocatingNodeId() == null) { inactiveShardCount--; assert inactiveShardCount >= 0; if (shard.primary()) { inactivePrimaryCount--; } } else if (shard.relocating()) { cancelRelocation(shard); } assignedShardsRemove(shard); if (shard.initializing()) { removeRecovery(shard); } } private void assignedShardsAdd(ShardRouting shard) { if (shard.unassigned()) { // no unassigned return; } List<ShardRouting> shards = assignedShards.computeIfAbsent(shard.shardId(), k -> new ArrayList<>()); assert assertInstanceNotInList(shard, shards); shards.add(shard); } private boolean assertInstanceNotInList(ShardRouting shard, List<ShardRouting> shards) { for (ShardRouting s : shards) { assert s != shard; } return true; } private void assignedShardsRemove(ShardRouting shard) { ensureMutable(); final List<ShardRouting> replicaSet = assignedShards.get(shard.shardId()); if (replicaSet != null) { final Iterator<ShardRouting> iterator = replicaSet.iterator(); while(iterator.hasNext()) { // yes we check identity here if (shard == iterator.next()) { iterator.remove(); return; } } assert false : "Illegal state"; } } public boolean isKnown(DiscoveryNode node) { return nodesToShards.containsKey(node.getId()); } public void addNode(DiscoveryNode node) { ensureMutable(); RoutingNode routingNode = new RoutingNode(node.id(), node); nodesToShards.put(routingNode.nodeId(), routingNode); } public RoutingNodeIterator routingNodeIter(String nodeId) { final RoutingNode routingNode = nodesToShards.get(nodeId); if (routingNode == null) { return null; } return new RoutingNodeIterator(routingNode); } public RoutingNode[] toArray() { return nodesToShards.values().toArray(new RoutingNode[nodesToShards.size()]); } public void reinitShadowPrimary(ShardRouting candidate) { ensureMutable(); if (candidate.relocating()) { cancelRelocation(candidate); } candidate.reinitializeShard(); inactivePrimaryCount++; inactiveShardCount++; } /** * Returns the number of routing nodes */ public int size() { return nodesToShards.size(); } public static final class UnassignedShards implements Iterable<ShardRouting> { private final RoutingNodes nodes; private final List<ShardRouting> unassigned; private final List<ShardRouting> ignored; private int primaries = 0; private int ignoredPrimaries = 0; public UnassignedShards(RoutingNodes nodes) { this.nodes = nodes; unassigned = new ArrayList<>(); ignored = new ArrayList<>(); } public void add(ShardRouting shardRouting) { if(shardRouting.primary()) { primaries++; } unassigned.add(shardRouting); } public void sort(Comparator<ShardRouting> comparator) { CollectionUtil.timSort(unassigned, comparator); } /** * Returns the size of the non-ignored unassigned shards */ public int size() { return unassigned.size(); } /** * Returns the size of the temporarily marked as ignored unassigned shards */ public int ignoredSize() { return ignored.size(); } /** * Returns the number of non-ignored unassigned primaries */ public int getNumPrimaries() { return primaries; } /** * Returns the number of temporarily marked as ignored unassigned primaries */ public int getNumIgnoredPrimaries() { return ignoredPrimaries; } @Override public UnassignedIterator iterator() { return new UnassignedIterator(); } /** * The list of ignored unassigned shards (read only). The ignored unassigned shards * are not part of the formal unassigned list, but are kept around and used to build * back the list of unassigned shards as part of the routing table. */ public List<ShardRouting> ignored() { return Collections.unmodifiableList(ignored); } /** * Marks a shard as temporarily ignored and adds it to the ignore unassigned list. * Should be used with caution, typically, * the correct usage is to removeAndIgnore from the iterator. * @see #ignored() * @see UnassignedIterator#removeAndIgnore() * @see #isIgnoredEmpty() */ public void ignoreShard(ShardRouting shard) { if (shard.primary()) { ignoredPrimaries++; } ignored.add(shard); } public class UnassignedIterator implements Iterator<ShardRouting> { private final Iterator<ShardRouting> iterator; private ShardRouting current; public UnassignedIterator() { this.iterator = unassigned.iterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public ShardRouting next() { return current = iterator.next(); } /** * Initializes the current unassigned shard and moves it from the unassigned list. * * @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated. */ public void initialize(String nodeId, @Nullable String existingAllocationId, long expectedShardSize) { innerRemove(); nodes.initialize(new ShardRouting(current), nodeId, existingAllocationId, expectedShardSize); } /** * Removes and ignores the unassigned shard (will be ignored for this run, but * will be added back to unassigned once the metadata is constructed again). * Typically this is used when an allocation decision prevents a shard from being allocated such * that subsequent consumers of this API won't try to allocate this shard again. */ public void removeAndIgnore() { innerRemove(); ignoreShard(current); } /** * Unsupported operation, just there for the interface. Use {@link #removeAndIgnore()} or * {@link #initialize(String, String, long)}. */ @Override public void remove() { throw new UnsupportedOperationException("remove is not supported in unassigned iterator, use removeAndIgnore or initialize"); } private void innerRemove() { nodes.ensureMutable(); iterator.remove(); if (current.primary()) { primaries--; } } } /** * Returns <code>true</code> iff this collection contains one or more non-ignored unassigned shards. */ public boolean isEmpty() { return unassigned.isEmpty(); } /** * Returns <code>true</code> iff any unassigned shards are marked as temporarily ignored. * @see UnassignedShards#ignoreShard(ShardRouting) * @see UnassignedIterator#removeAndIgnore() */ public boolean isIgnoredEmpty() { return ignored.isEmpty(); } public void shuffle() { Randomness.shuffle(unassigned); } /** * Drains all unassigned shards and returns it. * This method will not drain ignored shards. */ public ShardRouting[] drain() { ShardRouting[] mutableShardRoutings = unassigned.toArray(new ShardRouting[unassigned.size()]); unassigned.clear(); primaries = 0; return mutableShardRoutings; } } /** * Calculates RoutingNodes statistics by iterating over all {@link ShardRouting}s * in the cluster to ensure the book-keeping is correct. * For performance reasons, this should only be called from asserts * * @return this method always returns <code>true</code> or throws an assertion error. If assertion are not enabled * this method does nothing. */ public static boolean assertShardStats(RoutingNodes routingNodes) { boolean run = false; assert (run = true); // only run if assertions are enabled! if (!run) { return true; } int unassignedPrimaryCount = 0; int unassignedIgnoredPrimaryCount = 0; int inactivePrimaryCount = 0; int inactiveShardCount = 0; int relocating = 0; Map<Index, Integer> indicesAndShards = new HashMap<>(); for (RoutingNode node : routingNodes) { for (ShardRouting shard : node) { if (!shard.active() && shard.relocatingNodeId() == null) { if (!shard.relocating()) { inactiveShardCount++; if (shard.primary()) { inactivePrimaryCount++; } } } if (shard.relocating()) { relocating++; } Integer i = indicesAndShards.get(shard.index()); if (i == null) { i = shard.id(); } indicesAndShards.put(shard.index(), Math.max(i, shard.id())); } } // Assert that the active shard routing are identical. Set<Map.Entry<Index, Integer>> entries = indicesAndShards.entrySet(); final List<ShardRouting> shards = new ArrayList<>(); for (Map.Entry<Index, Integer> e : entries) { Index index = e.getKey(); for (int i = 0; i < e.getValue(); i++) { for (RoutingNode routingNode : routingNodes) { for (ShardRouting shardRouting : routingNode) { if (shardRouting.index().equals(index) && shardRouting.id() == i) { shards.add(shardRouting); } } } List<ShardRouting> mutableShardRoutings = routingNodes.assignedShards(new ShardId(index, i)); assert mutableShardRoutings.size() == shards.size(); for (ShardRouting r : mutableShardRoutings) { assert shards.contains(r); shards.remove(r); } assert shards.isEmpty(); } } for (ShardRouting shard : routingNodes.unassigned()) { if (shard.primary()) { unassignedPrimaryCount++; } } for (ShardRouting shard : routingNodes.unassigned().ignored()) { if (shard.primary()) { unassignedIgnoredPrimaryCount++; } } for (Map.Entry<String, Recoveries> recoveries : routingNodes.recoveryiesPerNode.entrySet()) { String node = recoveries.getKey(); final Recoveries value = recoveries.getValue(); int incoming = 0; int outgoing = 0; RoutingNode routingNode = routingNodes.nodesToShards.get(node); if (routingNode != null) { // node might have dropped out of the cluster for (ShardRouting routing : routingNode) { if (routing.initializing()) { incoming++; } else if (routing.relocating()) { outgoing++; } if (routing.primary() && (routing.initializing() && routing.relocatingNodeId() != null) == false) { // we don't count the initialization end of the primary relocation List<ShardRouting> shardRoutings = routingNodes.assignedShards.get(routing.shardId()); for (ShardRouting assigned : shardRoutings) { if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) { outgoing++; } } } } } assert incoming == value.incoming : incoming + " != " + value.incoming; assert outgoing == value.outgoing : outgoing + " != " + value.outgoing + " node: " + routingNode; } assert unassignedPrimaryCount == routingNodes.unassignedShards.getNumPrimaries() : "Unassigned primaries is [" + unassignedPrimaryCount + "] but RoutingNodes returned unassigned primaries [" + routingNodes.unassigned().getNumPrimaries() + "]"; assert unassignedIgnoredPrimaryCount == routingNodes.unassignedShards.getNumIgnoredPrimaries() : "Unassigned ignored primaries is [" + unassignedIgnoredPrimaryCount + "] but RoutingNodes returned unassigned ignored primaries [" + routingNodes.unassigned().getNumIgnoredPrimaries() + "]"; assert inactivePrimaryCount == routingNodes.inactivePrimaryCount : "Inactive Primary count [" + inactivePrimaryCount + "] but RoutingNodes returned inactive primaries [" + routingNodes.inactivePrimaryCount + "]"; assert inactiveShardCount == routingNodes.inactiveShardCount : "Inactive Shard count [" + inactiveShardCount + "] but RoutingNodes returned inactive shards [" + routingNodes.inactiveShardCount + "]"; assert routingNodes.getRelocatingShardCount() == relocating : "Relocating shards mismatch [" + routingNodes.getRelocatingShardCount() + "] but expected [" + relocating + "]"; return true; } public class RoutingNodesIterator implements Iterator<RoutingNode>, Iterable<ShardRouting> { private RoutingNode current; private final Iterator<RoutingNode> delegate; public RoutingNodesIterator(Iterator<RoutingNode> iterator) { delegate = iterator; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public RoutingNode next() { return current = delegate.next(); } public RoutingNodeIterator nodeShards() { return new RoutingNodeIterator(current); } @Override public void remove() { delegate.remove(); } @Override public Iterator<ShardRouting> iterator() { return nodeShards(); } } public final class RoutingNodeIterator implements Iterator<ShardRouting>, Iterable<ShardRouting> { private final RoutingNode iterable; private ShardRouting shard; private final Iterator<ShardRouting> delegate; private boolean removed = false; public RoutingNodeIterator(RoutingNode iterable) { this.delegate = iterable.mutableIterator(); this.iterable = iterable; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public ShardRouting next() { removed = false; return shard = delegate.next(); } @Override public void remove() { ensureMutable(); delegate.remove(); RoutingNodes.this.remove(shard); removed = true; } /** returns true if {@link #remove()} or {@link #moveToUnassigned(UnassignedInfo)} were called on the current shard */ public boolean isRemoved() { return removed; } @Override public Iterator<ShardRouting> iterator() { return iterable.iterator(); } public void moveToUnassigned(UnassignedInfo unassignedInfo) { ensureMutable(); if (isRemoved() == false) { remove(); } ShardRouting unassigned = new ShardRouting(shard); // protective copy of the mutable shard unassigned.moveToUnassigned(unassignedInfo); unassigned().add(unassigned); } public ShardRouting current() { return shard; } } private void ensureMutable() { if (readOnly) { throw new IllegalStateException("can't modify RoutingNodes - readonly"); } } private static final class Recoveries { private static final Recoveries EMPTY = new Recoveries(); private int incoming = 0; private int outgoing = 0; int getTotal() { return incoming + outgoing; } void addOutgoing(int howMany) { assert outgoing + howMany >= 0 : outgoing + howMany+ " must be >= 0"; outgoing += howMany; } void addIncoming(int howMany) { assert incoming + howMany >= 0 : incoming + howMany+ " must be >= 0"; incoming += howMany; } int getOutgoing() { return outgoing; } int getIncoming() { return incoming; } public static Recoveries getOrAdd(Map<String, Recoveries> map, String key) { Recoveries recoveries = map.get(key); if (recoveries == null) { recoveries = new Recoveries(); map.put(key, recoveries); } return recoveries; } } }
mapr/elasticsearch
core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java
Java
apache-2.0
37,917
[ 30522, 1013, 1008, 1008, 7000, 2000, 21274, 17310, 11140, 2104, 2028, 2030, 2062, 12130, 1008, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 5500, 2007, 1008, 2023, 2147, 2005, 3176, 2592, 4953, 9385, 1008, 6095, 1012, 21274, 17310, 11140, 159...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* global SnippetedMessages */ Template.snippetedMessages.helpers({ hasMessages() { return SnippetedMessages.find({ snippeted:true, rid: this.rid }, { sort: { ts: -1 } }).count() > 0; }, messages() { return SnippetedMessages.find({ snippeted: true, rid: this.rid }, { sort: { ts: -1 } }); }, message() { return _.extend(this, { customClass: 'snippeted' }); }, hasMore() { return Template.instance().hasMore.get(); } }); Template.snippetedMessages.onCreated(function() { this.hasMore = new ReactiveVar(true); this.limit = new ReactiveVar(50); const self = this; this.autorun(function() { const data = Template.currentData(); self.subscribe('snippetedMessages', data.rid, self.limit.get(), function() { if (SnippetedMessages.find({ snippeted: true, rid: data.rid }).count() < self.limit.get()) { return self.hasMore.set(false); } }); }); });
tntobias/Rocket.Chat
packages/rocketchat-message-snippet/client/tabBar/views/snippetedMessages.js
JavaScript
mit
878
[ 30522, 1013, 1008, 3795, 1055, 3490, 29519, 2098, 7834, 3736, 8449, 1008, 1013, 23561, 1012, 1055, 3490, 29519, 2098, 7834, 3736, 8449, 1012, 2393, 2545, 1006, 1063, 2038, 7834, 3736, 8449, 1006, 1007, 1063, 2709, 1055, 3490, 29519, 2098, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package redpoll.clusterer.canopy; import java.io.IOException; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputCollector; import redpoll.core.LabeledWritableVector; import redpoll.core.Vector; import redpoll.core.WritableSparseVector; import redpoll.core.WritableVector; import redpoll.util.DistanceMeasure; /** * This class models a canopy as a center point. */ public class Canopy { // keys used by Driver, Mapper & Reducer public static final String DISTANCE_MEASURE_KEY = "redpoll.clusterer.canopy.measure"; public static final String T1_KEY = "redpoll.clusterer.canopy.t1"; public static final String T2_KEY = "redpoll.clusterer.canopy.t2"; public static final String CANOPY_PATH_KEY = "redpoll.clusterer.canopy.path"; private static final Log log = LogFactory.getLog(Canopy.class.getName()); // the T1 distance threshold private static double t1; // the T2 distance threshold private static double t2; // the distance measure private static DistanceMeasure measure; // this canopy's canopyId private final Text canopyId; // the current center private WritableVector center = new WritableSparseVector(0); public Canopy(String idString, WritableVector point) { super(); this.canopyId = new Text(idString); this.center = point; } /** * Create a new Canopy containing the given labeled point. * @param point a labeled point in vector space */ public Canopy(LabeledWritableVector point) { super(); this.canopyId = point.getLabel(); this.center = point; } /** * Configure the Canopy and its distance measure * @param job the JobConf for this job */ public static void configure(JobConf job) { try { final ClassLoader ccl = Thread.currentThread().getContextClassLoader(); Class<?> cl = ccl.loadClass(job.get(DISTANCE_MEASURE_KEY)); measure = (DistanceMeasure) cl.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } t1 = Double.parseDouble(job.get(T1_KEY)); t2 = Double.parseDouble(job.get(T2_KEY)); } /** * Configure the Canopy for unit tests * @param aMeasure * @param aT1 * @param aT2 */ public static void config(DistanceMeasure aMeasure, double aT1, double aT2) { measure = aMeasure; t1 = aT1; t2 = aT2; } /** * This method is used by the CanopyMapper to perform canopy inclusion tests * and to emit the point and its covering canopies to the output. * * @param point the point to be added * @param canopies the List<Canopy> to be appended * @param collector an OutputCollector in which to emit the point */ public static void emitPointToNewCanopies(LabeledWritableVector point, List<Canopy> canopies, OutputCollector<Text, WritableVector> collector) throws IOException { boolean pointStronglyBound = false; for (Canopy canopy : canopies) { double dist = measure.distance(canopy.getCenter(), point); pointStronglyBound = pointStronglyBound || (dist < t2); } if (!pointStronglyBound) { // strong bound Canopy newCanopy = new Canopy(point.copy()); canopies.add(newCanopy); collector.collect(new Text("canopy"), newCanopy.getCenter()); } } /** * This method is used by the ClusterMapper to perform canopy inclusion tests * and to emit the point keyed by its covering canopies to the output. if the * point is not covered by any canopies (due to canopy centroid clustering), * emit the point to the closest covering canopy. * * @param point the point to be added * @param canopies the List<Canopy> to be appended * @param writable the original Writable from the input, may include arbitrary * payload information after the point [...]<payload> * @param collector an OutputCollector in which to emit the point */ public static void emitPointToExistingCanopies(Text key, List<Canopy> canopies, WritableVector point, OutputCollector<Text, WritableVector> collector) throws IOException { double minDist = Double.MAX_VALUE; Canopy closest = null; boolean isCovered = false; StringBuilder builder = new StringBuilder(); for (Canopy canopy : canopies) { double dist = measure.distance(canopy.getCenter(), point); if (dist < t1) { isCovered = true; builder.append(canopy.getIdentifier()).append(":"); } else if (dist < minDist) { minDist = dist; closest = canopy; } } // if the point is not contained in any canopies (due to canopy centroid // clustering), emit the point to the closest covering canopy. Text label = isCovered ? new Text(builder.toString()) : closest.getCanopyId(); collector.collect(key, new LabeledWritableVector(label, point)); } @Override public String toString() { return getIdentifier() + " - " + getCenter().asFormatString(); } public String getIdentifier() { return canopyId.toString(); } public Text getCanopyId() { return canopyId; } /** * Return the center point * * @return the center of the Canopy */ public WritableVector getCenter() { return center; } /** * Return if the point is covered by this canopy * * @param point a point * @return if the point is covered */ public boolean covers(Vector point) { return measure.distance(center, point) < t1; } }
coderplay/redpoll
core/src/java/redpoll/clusterer/canopy/Canopy.java
Java
apache-2.0
6,785
[ 30522, 1013, 1008, 1008, 1008, 7000, 2000, 1996, 15895, 4007, 3192, 1006, 2004, 2546, 1007, 2104, 2028, 2030, 2062, 1008, 12130, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 5500, 2007, 1008, 2023, 2147, 2005, 3176, 2592, 4953, 9385, 6095, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package cn.xaut.shop.dao; import java.util.List; import cn.xaut.common.paging.domain.Page; import cn.xaut.shop.modules.repository.CrudRepository; import cn.xaut.shop.pojo.Goods; public interface GoodsDao extends CrudRepository<Goods, Integer>{ Page<Goods> findByKey(Page<Goods> page,String key); Page<Goods> findByKeyShopId(Page<Goods> page,String key,Integer sid); Page<Goods> findHotByShopId(Page<Goods> page,int sid); Page<Goods> queryByShopId(Page<Goods> page,int sid); Page<Goods> findAllHot(Page<Goods> page); Page<Goods> queryAllHot(Page<Goods> page); Page<Goods> findDHByShopId(Page<Goods> page,String key, String stype,Integer sid); Page<Goods> findByPrice(Page<Goods> page,String p,String keyword); Page<Goods> queryDiscount(Page<Goods> page); Page<Goods> queryShopDiscount(Page<Goods> page, String date, Integer shopId); List<Goods> findByGoodsId(Integer goodsid); Page<Goods> querySale(Page<Goods> page,String keyword); Page<Goods> queryType(Page<Goods> page, String type); //dwj查询所有商品 Page<Goods> findByAllGood(Page<Goods> page); //dwj关键字list查询 public List<Goods> findGoodsInfoKeyWord (String keyWord); //dwjSET集合 public List<Goods> getShopSet(Integer sid); /** * 减库存,没有商品类型的的情况 */ public int minGoodAmount(Integer goodsid , final Integer amount); /** * 减少库存,有商品类型的情况 * @param property 商品类型值 */ public int minGoodAmountProperty(int goodsid,final int amount,final String property); /** * 取消订单,还原库存 * @param goodsid 商品ID * @param amount 还原的商品数量 * @return */ public int rollBackGoodAmount(Integer goodsid , final Integer amount); /** * 取消定单后的库存还原 * @param property 商品类别信息 * */ public int rollBackGoodAmountProperty(int goodsid, int amount,String property); /** * 增加销售数量 * @param goodsId 商品ID * @param sellAmount 销售数量 */ public int increaseSellAmount(Integer goodsId , final Integer sellAmount); /** * 减少销售数量 ywl * @param goodsId 商品ID * @param sellAmount 销售数量 */ public int decreaseSellAmount(Integer goodsId , final Integer sellAmount); List<Goods> getGoodsList(Integer shopid, String key); //根据Goods的goodsid活动goods public Goods findGoodsByGoodsId(Integer goodsid); List<Goods> findGoodsByTypeId(String gtypeID); Page<Goods> findByShopKey(Page<Goods> page, String shopId, String key); Page<Goods> findByState(Page<Goods> page); Page<Goods> findTop(Page<Goods> page); Page<Goods> queryViewShopId(Page<Goods> page, Integer sid); List<Goods> getGoodsTypeList(Integer shopid, String typeid, String key); List<Goods> getType(Integer typeid, Integer goodsid); Page<Goods> findShandByKey(Page<Goods> page, String keyword); Page<Goods> findShand(Page<Goods> page); Page<Goods> findShandByType(Page<Goods> page, String keyword, String type); }
wanliyang10010/Shop
src/cn/xaut/shop/dao/GoodsDao.java
Java
apache-2.0
2,971
[ 30522, 7427, 27166, 1012, 1060, 4887, 2102, 1012, 4497, 1012, 4830, 2080, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 2862, 1025, 12324, 27166, 1012, 1060, 4887, 2102, 1012, 2691, 1012, 6643, 4726, 1012, 5884, 1012, 3931, 1025, 12324, 27166...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.jetbrains.plugins.scala package components import java.awt.event.MouseEvent import javax.swing.Icon import com.intellij.ide.DataManager import com.intellij.notification._ import com.intellij.openapi.actionSystem.{CommonDataKeys, DataContext} import com.intellij.openapi.components._ import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.wm.StatusBarWidget.PlatformType import com.intellij.openapi.wm.{StatusBar, StatusBarWidget, WindowManager} import com.intellij.util.{Consumer, FileContentUtil} import org.intellij.lang.annotations.Language import org.jetbrains.plugins.scala.extensions.ObjectExt import org.jetbrains.plugins.scala.icons.Icons import org.jetbrains.plugins.scala.project._ import org.jetbrains.plugins.scala.util.NotificationUtil import scala.collection.JavaConversions._ @State( name = "HighlightingAdvisor", storages = Array( new Storage("highlighting.xml")) ) class HighlightingAdvisor(project: Project) extends AbstractProjectComponent(project) with PersistentStateComponent[HighlightingSettings] { @Language("HTML") private val AdviceMessage = """ <html> <body> <p><a href="http://confluence.jetbrains.net/display/SCA/Type-aware+highlighting">Type-aware highlighting</a> helps to discover type mismatches, unresolved symbols and many other type-related errors.</p> <br> <p>However, the feature is in beta and sometimes may report "false errors" in regular code.</p> <br> <a href="ftp://enable">Enable type-aware highlighting</a> (recommended) or <a href="ftp://disable">leave it disabled</a> </body> </html>""" @Language("HTML") private val EnabledMessage = """ <html> <body> <p><a href="http://confluence.jetbrains.net/display/SCA/Type-aware+highlighting">Type-aware highlighting</a> has been enabled.</p> <!--<br> <a href="ftp://disable">Disable it again</a>--> </body> </html>""" @Language("HTML") private val DisabledMessage = """ <html> <body> <p><a href="http://confluence.jetbrains.net/display/SCA/Type-aware+highlighting">Type-aware highlighting</a> has been disabled.</p> <!--<br> <a href="ftp://enable">Enable it again</a>--> </body> </html>""" private var installed = false private var settings = new HighlightingSettings() override def getComponentName = "HighlightingAdvisor" override def projectOpened() { project.scalaEvents.addScalaProjectListener(ScalaListener) statusBar.foreach { bar => configureWidget(bar) notifyIfNeeded() } } override def projectClosed() { project.scalaEvents.removeScalaProjectListener(ScalaListener) statusBar.foreach { bar => configureWidget(bar) } } def getState: HighlightingSettings = settings def loadState(state: HighlightingSettings) { settings = state } private def configureWidget(bar: StatusBar) { (applicable, installed) match { case (true, true) => // do nothing case (true, false) => bar.addWidget(Widget, project) installed = true case (false, true) => bar.removeWidget(Widget.ID) installed = false case (false, false) => // do nothing } } private def notifyIfNeeded() { if (settings.SUGGEST_TYPE_AWARE_HIGHLIGHTING && !enabled && applicable) { notify("Configure type-aware highlighting for the project", AdviceMessage, NotificationType.WARNING) } } private def notify(title: String, message: String, notificationType: NotificationType) { NotificationUtil.builder(project, message) setNotificationType notificationType setTitle title setHandler { case "enable" => enabled = true case "disable" => enabled = false case _ => } } def toggle() { if (applicable) { enabled = !enabled TypeAwareHighlightingApplicationState.getInstance setSuggest enabled } } private def applicable = project.hasScala && !project.hasDotty def enabled = settings.TYPE_AWARE_HIGHLIGHTING_ENABLED private def enabled_=(enabled: Boolean) { settings.SUGGEST_TYPE_AWARE_HIGHLIGHTING = false if (this.enabled == enabled) return settings.TYPE_AWARE_HIGHLIGHTING_ENABLED = enabled statusBar.foreach { bar => updateWidget(bar) reparseActiveFile() notify(status, if (enabled) EnabledMessage else DisabledMessage, NotificationType.INFORMATION) } } private def status = s"Scala type-aware highlighting: ${if (enabled) "enabled" else "disabled"}}" private def updateWidget(bar: StatusBar) { bar.updateWidget(Widget.ID) } private def reparseActiveFile() { val context = DataManager.getInstance.getDataContextFromFocus context.doWhenDone(new Consumer[DataContext] { override def consume(dataContext: DataContext): Unit = { CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext) match { case editor: EditorEx => FileContentUtil.reparseFiles(project, Seq(editor.getVirtualFile), true) case _ => // do nothing } } }) } private def statusBar: Option[StatusBar] = Option(WindowManager.getInstance).flatMap(_.getStatusBar(project).toOption) private object Widget extends StatusBarWidget { def ID = "TypeAwareHighlighting" def getPresentation(platformType: PlatformType) = Presentation def install(statusBar: StatusBar) {} def dispose() {} object Presentation extends StatusBarWidget.IconPresentation { def getIcon: Icon = if (enabled) Icons.TYPED else Icons.UNTYPED def getClickConsumer = ClickConsumer def getTooltipText = s"$status (click to ${if (enabled) "disable" else "enable"}, or press Ctrl+Shift+Alt+E)" object ClickConsumer extends Consumer[MouseEvent] { def consume(t: MouseEvent): Unit = toggle() } } } private object ScalaListener extends ScalaProjectListener { def onScalaProjectChanged() { statusBar.foreach { bar => configureWidget(bar) if (applicable) { notifyIfNeeded() } } } } } object HighlightingAdvisor { def getInstance(project: Project): HighlightingAdvisor = project.getComponent(classOf[HighlightingAdvisor]) }
loskutov/intellij-scala
src/org/jetbrains/plugins/scala/components/HighlightingAdvisor.scala
Scala
apache-2.0
6,242
[ 30522, 7427, 8917, 1012, 6892, 10024, 7076, 1012, 13354, 7076, 1012, 26743, 7427, 6177, 12324, 9262, 1012, 22091, 2102, 1012, 2724, 1012, 8000, 18697, 3372, 12324, 9262, 2595, 1012, 7370, 1012, 12696, 12324, 4012, 1012, 13420, 3669, 3501, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
Please go to https://firebase.google.com/support/release-notes/ios#3.10.0 to view the Firebase iOS release notes. You can find information about prior changes to the Firebase pod and Firebase Database [here](https://www.firebase.com/docs/ios/changelog.html).
OlegNovosad/Sample
iOS/Pods/Firebase/CHANGELOG.md
Markdown
apache-2.0
260
[ 30522, 3531, 2175, 2000, 16770, 1024, 1013, 1013, 2543, 15058, 1012, 8224, 1012, 4012, 1013, 2490, 1013, 2713, 1011, 3964, 1013, 16380, 1001, 1017, 1012, 2184, 1012, 1014, 2000, 3193, 1996, 2543, 15058, 16380, 2713, 3964, 1012, 2017, 2064, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- ''' Use a git repository as a Pillar source --------------------------------------- .. note:: This external pillar has been rewritten for the :doc:`2015.8.0 </topics/releases/2015.8.0>` release. The old method of configuring this external pillar will be maintained for a couple releases, allowing time for configurations to be updated to reflect the new usage. This external pillar allows for a Pillar top file and Pillar SLS files to be sourced from a git repository. However, since git_pillar does not have an equivalent to the :conf_master:`pillar_roots` parameter, configuration is slightly different. The Pillar top file must still contain the relevant environment, like so: .. code-block:: yaml base: '*': - foo The branch/tag which maps to that environment must then be specified along with the repo's URL. Configuration details can be found below. .. _git-pillar-pre-2015-8-0: Configuring git_pillar for Salt releases before 2015.8.0 ======================================================== For Salt releases earlier than :doc:`2015.8.0 </topics/releases/2015.8.0>`, GitPython is the only supported provider for git_pillar. Individual repositories can be configured under the :conf_master:`ext_pillar` configuration parameter like so: .. code-block:: yaml ext_pillar: - git: master https://gitserver/git-pillar.git root=subdirectory The repository is specified in the format ``<branch> <repo_url>``, with an optional ``root`` parameter (added in the :doc:`2014.7.0 </topics/releases/2014.7.0>` release) which allows the pillar SLS files to be served up from a subdirectory (similar to :conf_master:`gitfs_root` in gitfs). To use more than one branch from the same repo, multiple lines must be specified under :conf_master:`ext_pillar`: .. code-block:: yaml ext_pillar: - git: master https://gitserver/git-pillar.git - git: dev https://gitserver/git-pillar.git To remap a specific branch to a specific Pillar environment, use the format ``<branch>:<env>``: .. code-block:: yaml ext_pillar: - git: develop:dev https://gitserver/git-pillar.git - git: master:prod https://gitserver/git-pillar.git In this case, the ``develop`` branch would need its own ``top.sls`` with a ``dev`` section in it, like this: .. code-block:: yaml dev: '*': - bar The ``master`` branch would need its own ``top.sls`` with a ``prod`` section in it: .. code-block:: yaml prod: '*': - bar If ``__env__`` is specified as the branch name, then git_pillar will use the branch specified by :conf_master:`gitfs_base`: .. code-block:: yaml ext_pillar: - git: __env__ https://gitserver/git-pillar.git root=pillar The corresponding Pillar top file would look like this: .. code-block:: yaml {{env}}: '*': - bar .. _git-pillar-2015-8-0-and-later: Configuring git_pillar for Salt releases 2015.8.0 and later =========================================================== .. note:: In version 2015.8.0, the method of configuring git external pillars has changed, and now more closely resembles that of the :ref:`Git Fileserver Backend <tutorial-gitfs>`. If Salt detects the old configuration schema, it will use the pre-2015.8.0 code to compile the external pillar. A warning will also be logged. Beginning with Salt version 2015.8.0, pygit2_ is now supported in addition to GitPython_ (Dulwich_ will not be supported for the forseeable future). The requirements for GitPython_ and pygit2_ are the same as for gitfs, as described :ref:`here <gitfs-dependencies>`. .. important:: git_pillar has its own set of global configuration parameters. While it may seem intuitive to use the global gitfs configuration parameters (:conf_master:`gitfs_base`, etc.) to manage git_pillar, this will not work. The main difference for this is the fact that the different components which use Salt's git backend code do not all function identically. For instance, in git_pillar it is necessary to specify which branch/tag to be used for git_pillar remotes. This is the reverse behavior from gitfs, where branches/tags make up your environments. See :ref:`here <git_pillar-config-opts>` for documentation on the git_pillar configuration options and their usage. Here is an example git_pillar configuration: .. code-block:: yaml ext_pillar: - git: # Use 'prod' instead of the branch name 'production' as the environment - production https://gitserver/git-pillar.git: - env: prod # Use 'dev' instead of the branch name 'develop' as the environment - develop https://gitserver/git-pillar.git: - env: dev # No per-remote config parameters (and no trailing colon), 'qa' will # be used as the environment - qa https://gitserver/git-pillar.git # SSH key authentication - master git@other-git-server:pillardata-ssh.git: # Pillar SLS files will be read from the 'pillar' subdirectory in # this repository - root: pillar - privkey: /path/to/key - pubkey: /path/to/key.pub - passphrase: CorrectHorseBatteryStaple # HTTPS authentication - master https://other-git-server/pillardata-https.git: - user: git - password: CorrectHorseBatteryStaple The main difference between this and the old way of configuring git_pillar is that multiple remotes can be configured under one ``git`` section under :conf_master:`ext_pillar`. More than one ``git`` section can be used, but it is not necessary. Remotes will be evaluated sequentially. Per-remote configuration parameters are supported (similar to :ref:`gitfs <gitfs-per-remote-config>`), and global versions of the git_pillar configuration parameters can also be set. With the addition of pygit2_ support, git_pillar can now interact with authenticated remotes. Authentication works just like in gitfs (as outlined in the :ref:`Git Fileserver Backend Walkthrough <gitfs-authentication>`), only with the global authenication parameter names prefixed with ``git_pillar`` instead of ``gitfs`` (e.g. :conf_master:`git_pillar_pubkey`, :conf_master:`git_pillar_privkey`, :conf_master:`git_pillar_passphrase`, etc.). .. _GitPython: https://github.com/gitpython-developers/GitPython .. _pygit2: https://github.com/libgit2/pygit2 .. _Dulwich: https://www.samba.org/~jelmer/dulwich/ ''' from __future__ import absolute_import # Import python libs import copy import logging import hashlib import os # Import salt libs import salt.utils.gitfs import salt.utils.dictupdate from salt.exceptions import FileserverConfigError from salt.pillar import Pillar # Import third party libs import salt.ext.six as six # pylint: disable=import-error try: import git HAS_GITPYTHON = True except ImportError: HAS_GITPYTHON = False # pylint: enable=import-error PER_REMOTE_OVERRIDES = ('env', 'root', 'ssl_verify') # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'git' def __virtual__(): ''' Only load if gitpython is available ''' git_ext_pillars = [x for x in __opts__['ext_pillar'] if 'git' in x] if not git_ext_pillars: # No git external pillars were configured return False for ext_pillar in git_ext_pillars: if isinstance(ext_pillar['git'], six.string_types): # Verification of legacy git pillar configuration if not HAS_GITPYTHON: log.error( 'Git-based ext_pillar is enabled in configuration but ' 'could not be loaded, is GitPython installed?' ) return False if not git.__version__ > '0.3.0': return False return __virtualname__ else: # Verification of new git pillar configuration try: salt.utils.gitfs.GitPillar(__opts__) # Initialization of the GitPillar object did not fail, so we # know we have valid configuration syntax and that a valid # provider was detected. return __virtualname__ except FileserverConfigError: pass return False def ext_pillar(minion_id, repo, pillar_dirs): ''' Checkout the ext_pillar sources and compile the resulting pillar SLS ''' if isinstance(repo, six.string_types): return _legacy_git_pillar(minion_id, repo, pillar_dirs) else: opts = copy.deepcopy(__opts__) opts['pillar_roots'] = {} pillar = salt.utils.gitfs.GitPillar(opts) pillar.init_remotes(repo, PER_REMOTE_OVERRIDES) pillar.checkout() ret = {} merge_strategy = __opts__.get( 'pillar_source_merging_strategy', 'smart' ) merge_lists = __opts__.get( 'pillar_merge_lists', False ) for pillar_dir, env in six.iteritems(pillar.pillar_dirs): log.debug( 'git_pillar is processing pillar SLS from {0} for pillar ' 'env \'{1}\''.format(pillar_dir, env) ) all_dirs = [d for (d, e) in six.iteritems(pillar.pillar_dirs) if env == e] # Ensure that the current pillar_dir is first in the list, so that # the pillar top.sls is sourced from the correct location. pillar_roots = [pillar_dir] pillar_roots.extend([x for x in all_dirs if x != pillar_dir]) opts['pillar_roots'] = {env: pillar_roots} local_pillar = Pillar(opts, __grains__, minion_id, env) ret = salt.utils.dictupdate.merge( ret, local_pillar.compile_pillar(ext=False), strategy=merge_strategy, merge_lists=merge_lists ) return ret # Legacy git_pillar code class _LegacyGitPillar(object): ''' Deal with the remote git repository for Pillar ''' def __init__(self, branch, repo_location, opts): ''' Try to initialize the Git repo object ''' self.branch = self.map_branch(branch, opts) self.rp_location = repo_location self.opts = opts self._envs = set() self.working_dir = '' self.repo = None hash_type = getattr(hashlib, opts.get('hash_type', 'md5')) hash_str = '{0} {1}'.format(self.branch, self.rp_location) repo_hash = hash_type(hash_str).hexdigest() rp_ = os.path.join(self.opts['cachedir'], 'pillar_gitfs', repo_hash) if not os.path.isdir(rp_): os.makedirs(rp_) try: self.repo = git.Repo.init(rp_) except (git.exc.NoSuchPathError, git.exc.InvalidGitRepositoryError) as exc: log.error('GitPython exception caught while ' 'initializing the repo: {0}. Maybe ' 'git is not available.'.format(exc)) # Git directory we are working on # Should be the same as self.repo.working_dir self.working_dir = rp_ if isinstance(self.repo, git.Repo): if not self.repo.remotes: try: self.repo.create_remote('origin', self.rp_location) # ignore git ssl verification if requested if self.opts.get('pillar_gitfs_ssl_verify', True): self.repo.git.config('http.sslVerify', 'true') else: self.repo.git.config('http.sslVerify', 'false') except os.error: # This exception occurs when two processes are # trying to write to the git config at once, go # ahead and pass over it since this is the only # write. # This should place a lock down. pass else: if self.repo.remotes.origin.url != self.rp_location: self.repo.remotes.origin.config_writer.set( 'url', self.rp_location) def map_branch(self, branch, opts=None): opts = __opts__ if opts is None else opts if branch == '__env__': branch = opts.get('environment') or 'base' if branch == 'base': branch = opts.get('gitfs_base') or 'master' elif ':' in branch: branch = branch.split(':', 1)[0] return branch def update(self): ''' Ensure you are following the latest changes on the remote Return boolean whether it worked ''' try: log.debug('Updating fileserver for git_pillar module') self.repo.git.fetch() except git.exc.GitCommandError as exc: log.error('Unable to fetch the latest changes from remote ' '{0}: {1}'.format(self.rp_location, exc)) return False try: self.repo.git.checkout('origin/{0}'.format(self.branch)) except git.exc.GitCommandError as exc: log.error('Unable to checkout branch ' '{0}: {1}'.format(self.branch, exc)) return False return True def envs(self): ''' Return a list of refs that can be used as environments ''' if isinstance(self.repo, git.Repo): remote = self.repo.remote() for ref in self.repo.refs: parted = ref.name.partition('/') short = parted[2] if parted[2] else parted[0] if isinstance(ref, git.Head): if short == 'master': short = 'base' if ref not in remote.stale_refs: self._envs.add(short) elif isinstance(ref, git.Tag): self._envs.add(short) return list(self._envs) def _legacy_git_pillar(minion_id, repo_string, pillar_dirs): ''' Support pre-Beryllium config schema ''' if pillar_dirs is None: return # split the branch, repo name and optional extra (key=val) parameters. options = repo_string.strip().split() branch_env = options[0] repo_location = options[1] root = '' for extraopt in options[2:]: # Support multiple key=val attributes as custom parameters. DELIM = '=' if DELIM not in extraopt: log.error('Incorrectly formatted extra parameter. ' 'Missing \'{0}\': {1}'.format(DELIM, extraopt)) key, val = _extract_key_val(extraopt, DELIM) if key == 'root': root = val else: log.warning('Unrecognized extra parameter: {0}'.format(key)) # environment is "different" from the branch cfg_branch, _, environment = branch_env.partition(':') gitpil = _LegacyGitPillar(cfg_branch, repo_location, __opts__) branch = gitpil.branch if environment == '': if branch == 'master': environment = 'base' else: environment = branch # normpath is needed to remove appended '/' if root is empty string. pillar_dir = os.path.normpath(os.path.join(gitpil.working_dir, root)) pillar_dirs.setdefault(pillar_dir, {}) if cfg_branch == '__env__' and branch not in ['master', 'base']: gitpil.update() elif pillar_dirs[pillar_dir].get(branch, False): return {} # we've already seen this combo pillar_dirs[pillar_dir].setdefault(branch, True) # Don't recurse forever-- the Pillar object will re-call the ext_pillar # function if __opts__['pillar_roots'].get(branch, []) == [pillar_dir]: return {} opts = copy.deepcopy(__opts__) opts['pillar_roots'][environment] = [pillar_dir] pil = Pillar(opts, __grains__, minion_id, branch) return pil.compile_pillar(ext=False) def _update(branch, repo_location): ''' Ensure you are following the latest changes on the remote return boolean whether it worked ''' gitpil = _LegacyGitPillar(branch, repo_location, __opts__) return gitpil.update() def _envs(branch, repo_location): ''' Return a list of refs that can be used as environments ''' gitpil = _LegacyGitPillar(branch, repo_location, __opts__) return gitpil.envs() def _extract_key_val(kv, delimiter='='): '''Extract key and value from key=val string. Example: >>> _extract_key_val('foo=bar') ('foo', 'bar') ''' pieces = kv.split(delimiter) key = pieces[0] val = delimiter.join(pieces[1:]) return key, val
smallyear/linuxLearn
salt/salt/pillar/git_pillar.py
Python
apache-2.0
16,836
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1005, 1005, 1005, 2224, 1037, 21025, 2102, 22409, 2004, 1037, 14809, 3120, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
js.Offset = function(rawptr) { this.rawptr = rawptr; } js.Offset.prototype = new konoha.Object(); js.Offset.prototype._new = function(rawptr) { this.rawptr = rawptr; } js.Offset.prototype.getTop = function() { return this.rawptr.top; } js.Offset.prototype.getLeft = function() { return this.rawptr.left; } js.jquery = {}; var initJQuery = function() { var verifyArgs = function(args) { for (var i = 0; i < args.length; i++) { if (args[i].rawptr) { args[i] = args[i].rawptr; } } return args; } var jquery = function(rawptr) { this.rawptr = rawptr; } jquery.prototype = new konoha.Object(); jquery.konohaclass = "js.jquery.JQuery"; /* Selectors */ jquery.prototype.each_ = function(callback) { this.rawptr.each(callback.rawptr); } jquery.prototype.size = function() { return this.rawptr.size(); } jquery.prototype.getSelector = function() { return new konoha.String(this.rawptr.getSelector()); } jquery.prototype.getContext = function() { return new js.dom.Node(this.rawptr.getContext()); } jquery.prototype.getNodeList = function() { return new js.dom.NodeList(this.rawptr.get()); } jquery.prototype.getNode = function(index) { return new js.dom.Node(this.rawptr.get(index)); } /* Attributes */ jquery.prototype.getAttr = function(arg) { return new konoha.String(this.rawptr.attr(arg.rawptr)); } jquery.prototype.attr = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.attr.apply(this.rawptr, args)); } jquery.prototype.removeAttr = function(name) { return new jquery(this.rawptr.removeAttr(name.rawptr)); } jquery.prototype.addClass = function(className) { return new jquery(this.rawptr.addClass(className.rawptr)); } jquery.prototype.removeClass = function(className) { return new jquery(this.rawptr.removeClass(className.rawptr)); } jquery.prototype.toggleClass = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.toggleClass.apply(this.rawptr, args)); } jquery.prototype.getHTML = function() { return new konoha.String(this.rawptr.html()); } jquery.prototype.html = function(val) { return new jquery(this.rawptr.html(val.rawptr)); } jquery.prototype.getText = function() { return new konoha.String(this.rawptr.text()); } jquery.prototype.text = function(val) { return new jquery(this.rawptr.text(val.rawptr)); } jquery.prototype.getVal = function() { return new konoha.Array(this.rawptr.val()) } jquery.prototype.val = function(val) { return new jquery(this.rawptr.val(val.rawptr)); } /* Traversing */ jquery.prototype.eq = function(position) { return new jquery(this.rawptr.eq(position)); } jquery.prototype.filter = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.filter.apply(this.rawptr, args)); } jquery.prototype.is = function(expr) { return this.rawptr.is(expr.rawptr); } jquery.prototype.opnot = function(expr) { return this.rawptr.not(expr.rawptr); } jquery.prototype.slice = function() { return new jquery(this.rawptr.slice.apply(this.rawptr, Array.prototype.slice.call(arguments))); } jquery.prototype.add = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.add.apply(this.rawptr, args)); } jquery.prototype.children = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.children.apply(this.rawptr, args)); } jquery.prototype.closest = function() { var args =verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.closest.apply(this.rawptr, args)); } jquery.prototype.contents = function() { return new jquery(this.rawptr.contents()); } jquery.prototype.find = function(expr) { return new jquery(this.rawptr.find(expr.rawptr)); } jquery.prototype.next = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.next.apply(this.rawptr, args)); } jquery.prototype.nextAll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.nextAll.apply(this.rawptr, args)); } jquery.prototype.parent = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.parent.apply(this.rawptr, args)); } jquery.prototype.parents = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.parents.apply(this.rawptr, args)); } jquery.prototype.prev = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.prev.apply(this.rawptr, args)); } jquery.prototype.prevAll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.prevAll.apply(this.rawptr, args)); } jquery.prototype.siblings = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.siblings.apply(this.rawptr, args)); } jquery.prototype.andSelf = function() { return new jquery(this.rawptr.andSelf()); } jquery.prototype.end = function() { return new jquery(this.rawptr.end()); } /* Manipulation */ jquery.prototype.append = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.append.apply(this.rawptr, args)); } jquery.prototype.appendTo = function(content) { return new jquery(this.rawptr.appendTo(content.rawptr)); } jquery.prototype.prepend = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.prepend.apply(this.rawptr, args)); } jquery.prototype.prependTo = function(content) { return new jquery(this.rawptr.prependTo(content.rawptr)); } jquery.prototype.after = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.after.apply(this.rawptr, args)); } jquery.prototype.before = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.before.apply(this.rawptr, args)); } jquery.prototype.insertAfter = function(content) { return new jquery(this.rawptr.insertAfter(content.rawptr)); } jquery.prototype.insertBefore = function(content) { return new jquery(this.rawptr.insertBefore(content.rawptr)); } jquery.prototype.wrap = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.wrap.apply(this.rawptr, args)); } jquery.prototype.wrapAll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.wrapAll.apply(this.rawptr, args)); } jquery.prototype.wrapInner = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.wrapInner.apply(this.rawptr, args)); } jquery.prototype.replaceWith = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.replaceWith.apply(this.rawptr, args)); } jquery.prototype.replaceAll = function(selector) { return new jquery(this.rawptr.replaceAll(selector.rawptr)); } jquery.prototype.empty = function() { return new jquery(this.rawptr.empty()); } jquery.prototype.remove = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.remove.apply(this.rawptr, args)); } jquery.prototype.clone = function() { return new jquery(this.rawptr.clone.apply(this.rawptr, Array.prototype.slice.call(arguments))); } /* CSS */ jquery.prototype.getCss = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new konoha.String(this.rawptr.css.apply(this.rawptr, args)); } jquery.prototype.css = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.css.apply(this.rawptr, args)); } jquery.prototype.offset = function() { return new js.Offset(this.rawptr.offset()); } jquery.prototype.position = function() { return new js.Offset(this.rawptr.position()); } jquery.prototype.scrollTop = function() { return this.rawptr.scrollTop.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.scrollLeft = function() { return this.rawptr.scrollLeft.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.height = function() { return this.rawptr.height.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.width = function() { return this.rawptr.width.apply(this.rawptr, Array.prototype.slice.call(arguments)); } jquery.prototype.innerHeight = function() { return this.rawptr.innerHeight(); } jquery.prototype.innerWidth = function() { return this.rawptr.innerWidth(); } jquery.prototype.outerHeight = function() { return this.rawptr.outerHeight(); } jquery.prototype.outerWidth = function() { return this.rawptr.outerWidth(); } /* Events */ jquery.prototype.ready = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.ready.apply(this.rawptr, args)); } jquery.prototype.bind = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.bind.apply(this.rawptr, args)); } jquery.prototype.one = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.one.apply(this.rawptr, args)); } jquery.prototype.trigger = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.trigger.apply(this.rawptr, args)); } jquery.prototype.triggerHandler = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.triggerHandler.apply(this.rawptr, args)); } jquery.prototype.unbind = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.unbind.apply(this.rawptr, args)); } jquery.prototype.hover = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.hover.apply(this.rawptr, args)); } jquery.prototype.toggleEvent = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); args = verifyArgs(args[0]); return new jquery(this.rawptr.toggle.apply(this.rawptr, args)); } jquery.prototype.live = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.live.apply(this.rawptr, args)); } jquery.prototype.die = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.die.apply(this.rawptr, args)); } jquery.prototype.blur = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.blur.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.blur(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.change = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.change.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.change(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.click = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.click.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.click(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.dblclick = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.dblclick.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.dblclick(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.error = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.error.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.error(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.focus = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.focus.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.focus(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.keydown = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.keydown.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.keydown(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.keypress = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.keypress.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.keypress(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.keyup = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.keyup.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.keyup(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.load = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.load.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.load(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mousedown = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mousedown.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mousedown(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mousemove = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mousemove.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mousemove(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mouseout = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mouseout.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mouseout(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mouseover = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mouseover.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mouseover(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.mouseup = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.mouseup.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.mouseup(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.resize = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.resize.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.resize(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.scroll = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.scroll.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.scroll(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.select = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.select.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.select(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.submit = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.submit.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.select(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } jquery.prototype.unload = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (args.length == 0) { return new jquery(this.rawptr.unload.apply(this.rawptr, args)); } else { return new jquery(this.rawptr.unload(function(e) { args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]); })); } } /* Effects */ jquery.prototype.show = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.show.apply(this.rawptr, args)); } jquery.prototype.hide = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.hide.apply(this.rawptr, args)); } jquery.prototype.toggle = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.toggle.apply(this.rawptr, args)); } jquery.prototype.slideDown = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.slideDown.apply(this.rawptr, args)); } jquery.prototype.slideUp = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.slideUp.apply(this.rawptr, args)); } jquery.prototype.slideToggle = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.slideToggle.apply(this.rawptr, args)); } jquery.prototype.fadeIn = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.fadeIn.apply(this.rawptr, args)); } jquery.prototype.fadeOut = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.fadeOut.apply(this.rawptr, args)); } jquery.prototype.fadeTo = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); return new jquery(this.rawptr.fadeTo.apply(this.rawptr, args)); } jquery.prototype._new = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (arguments.length == 1) { this.rawptr = new $(args[0]); } else if (arguments.length == 2) { this.rawptr = new $(args[0], args[1]); } else { throw ("Script !!"); } return this; } return jquery; } js.jquery.JQuery = new initJQuery(); js.jquery.JEvent = new function() { var jevent = function(rawptr) { this.rawptr = rawptr; } jevent.prototype = new konoha.Object(); jevent.konohaclass = "js.jquery.JEvent"; jevent.prototype.type = function() { return new konoha.String(this.rawptr.type); } jevent.prototype.target = function() { return new konoha.dom.Element(this.rawptr.target); } jevent.prototype.relatedTarget = function() { return new konoha.dom.Element(this.rawptr.relatedTarget); } jevent.prototype.currentTarget = function() { return new konoha.dom.Element(this.rawptr.currentTarget); } jevent.prototype.pageX = function() { return this.rawptr.pageX; } jevent.prototype.pageY = function() { return this.rawptr.pageY; } jevent.prototype.timeStamp = function() { return this.rawptr.timeStamp; } jevent.prototype.preventDefault = function() { return new jevent(this.rawptr.preventDefault()); } jevent.prototype.isDefaultPrevented = function() { return this.rawptr.isDefaultPrevented(); } jevent.prototype.stopPropagation = function() { return new jevent(this.rawptr.stopPropagation()); } jevent.prototype.isPropagationStopped = function() { return this.rawptr.isPropagationStopped(); } jevent.prototype.stopImmediatePropagation = function() { return new jevent(this.rawptr.stopImmediatePropagation()); } jevent.prototype.isImmediatePropagationStopped = function() { return this.rawptr.isImmediatePropagationStopped(); } jevent.prototype._new = function() { var args = verifyArgs(Array.prototype.slice.call(arguments)); if (arguments.length == 1) { this.rawptr = new $(args[0]); } else if (arguments.length == 2) { this.rawptr = new $(args[0], args[1]); } else { throw ("Script !!"); } return this; } return jevent; }();
imasahiro/konohascript
package/konoha.compiler.js/runtime/js.jquery.js
JavaScript
lgpl-3.0
24,892
[ 30522, 1046, 2015, 1012, 16396, 1027, 3853, 1006, 6315, 13876, 2099, 1007, 1063, 2023, 1012, 6315, 13876, 2099, 1027, 6315, 13876, 2099, 1025, 1065, 1046, 2015, 1012, 16396, 1012, 8773, 1027, 2047, 12849, 3630, 3270, 1012, 4874, 1006, 1007,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close()
cdemulde/wwdata
wwdata/Class_LabExperimBased.py
Python
agpl-3.0
7,474
[ 30522, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1000, 1000, 1000, 2465, 1035, 6845, 10288, 4842, 5714, 15058, 2094, 3640, 8360, 6447, 2005, 2951, 8304, 1997, 2951, 4663, 1999, 6845, 7885, 1999, 1996, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#coding: utf-8 import os import time from . import test_util def test_add_file(): test_util.mkfile(1, 'a.md', 'add a file') test_util.verify_result() def test_add_file_t(): test_util.mkfile(2, 'l/m/n/test.md', 'add l/m/n/test.md') test_util.verify_result() def test_add_dir(): test_util.mkdir(1, 'ad') test_util.verify_result() def test_add_dir_t(): test_util.mkdir(2, 'tt/ee/st') test_util.verify_result() def test_modify_file(): test_util.modfile(1, 'a.md', 'modify a.md') test_util.verify_result() def test_rm_file(): test_util.rmfile(1, 'a.md') test_util.verify_result() def test_rm_dir(): test_util.rmdir(1, 'ad') test_util.verify_result() def test_rename_file(): test_util.mkfile(2, 'b.md', 'add b.md') time.sleep(1) test_util.move(2, 'b.md', 'b_bak.md') test_util.verify_result() def test_rename_dir(): test_util.mkdir(2, 'ab') time.sleep(1) test_util.move(2, 'ab', 'ab_bak') test_util.verify_result() def test_each(): test_util.mkdir(1, 'abc1') test_util.mkfile(1, 'abc1/c.md', 'add abc1/c.md') time.sleep(1) test_util.mkdir(2, 'bcd1') test_util.mkfile(2, 'bcd1/d.md', 'add bcd1/d.md') test_util.verify_result() def test_unsync_resync(): test_util.desync_cli1() test_util.rmdir(1, 'abc1') test_util.modfile(1, 'bcd1/d.md', 'modify bcd1/d.md to test unsync resync') test_util.sync_cli1() test_util.verify_result() if not os.path.exists(test_util.getpath(1, 'abc1')): assert False, 'dir abc1 should be recreated when resync' if len(os.listdir(test_util.getpath(1, 'bcd1'))) != 2: assert False, 'should generate conflict file for bcd1/d.md when resync' def test_modify_timestamp(): test_util.touch(1, 'bcd1/d.md') test_util.verify_result()
zhengger/seafile
tests/sync-auto-test/test_cases/test_simple.py
Python
gpl-2.0
1,826
[ 30522, 1001, 16861, 1024, 21183, 2546, 1011, 1022, 12324, 9808, 12324, 2051, 2013, 1012, 12324, 3231, 1035, 21183, 4014, 13366, 3231, 1035, 5587, 1035, 5371, 1006, 1007, 1024, 3231, 1035, 21183, 4014, 1012, 12395, 8873, 2571, 1006, 1015, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * SessionShiny.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionShiny.hpp" #include <boost/algorithm/string/predicate.hpp> #include <core/Error.hpp> #include <core/Exec.hpp> #include <r/RExec.hpp> #include <session/SessionOptions.hpp> #include <session/SessionModuleContext.hpp> using namespace core; namespace session { namespace modules { namespace shiny { namespace { void onPackageLoaded(const std::string& pkgname) { // we need an up to date version of shiny when running in server mode // to get the websocket protocol/path and port randomizing changes if (session::options().programMode() == kSessionProgramModeServer) { if (pkgname == "shiny") { if (!module_context::isPackageVersionInstalled("shiny", "0.8")) { module_context::consoleWriteError("\nWARNING: To run Shiny " "applications with RStudio you need to install the " "latest version of the Shiny package from CRAN (version 0.8 " "or higher is required).\n\n"); } } } } bool isShinyAppDir(const FilePath& filePath) { bool hasServer = filePath.childPath("server.R").exists() || filePath.childPath("server.r").exists(); if (hasServer) { bool hasUI = filePath.childPath("ui.R").exists() || filePath.childPath("ui.r").exists() || filePath.childPath("www").exists(); return hasUI; } else { return false; } } std::string onDetectShinySourceType( boost::shared_ptr<source_database::SourceDocument> pDoc) { const char * const kShinyType = "shiny"; if (!pDoc->path().empty()) { FilePath filePath = module_context::resolveAliasedPath(pDoc->path()); std::string filename = filePath.filename(); if (boost::algorithm::iequals(filename, "ui.r") && boost::algorithm::icontains(pDoc->contents(), "shinyUI")) { return kShinyType; } else if (boost::algorithm::iequals(filename, "server.r") && boost::algorithm::icontains(pDoc->contents(), "shinyServer")) { return kShinyType; } else if (filePath.extensionLowerCase() == ".r" && isShinyAppDir(filePath.parent())) { return kShinyType; } } return std::string(); } Error getShinyCapabilities(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { json::Object capsJson; capsJson["installed"] = module_context::isPackageInstalled("shiny"); pResponse->setResult(capsJson); return Success(); } } // anonymous namespace Error initialize() { using namespace module_context; events().onPackageLoaded.connect(onPackageLoaded); // run app features require shiny v0.8 (the version where the // shiny.launch.browser option can be a function) if (module_context::isPackageVersionInstalled("shiny", "0.8")) events().onDetectSourceExtendedType.connect(onDetectShinySourceType); ExecBlock initBlock; initBlock.addFunctions() (boost::bind(registerRpcMethod, "get_shiny_capabilities", getShinyCapabilities)); return initBlock.execute(); } } // namespace crypto } // namespace modules } // namesapce session
nvoron23/rstudio
src/cpp/session/modules/shiny/SessionShiny.cpp
C++
agpl-3.0
3,808
[ 30522, 1013, 1008, 1008, 6521, 10606, 2100, 1012, 18133, 2361, 1008, 1008, 9385, 1006, 1039, 1007, 2268, 1011, 2260, 2011, 12667, 8525, 20617, 1010, 4297, 1012, 1008, 1008, 4983, 2017, 2031, 2363, 2023, 2565, 3495, 2013, 12667, 8525, 20617,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.groupon.lex.metrics.json; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.groupon.lex.metrics.Tags; import static com.groupon.lex.metrics.json.Json.extractMetricValue; import java.util.HashMap; import java.util.function.Function; import java.util.stream.Collectors; class JsonTags extends HashMap<String, Object> { private static final Function<Tags, JsonTags> TAGS_CACHE = CacheBuilder.newBuilder() .softValues() .build(CacheLoader.from((Tags in) -> new JsonTags(in)))::getUnchecked; public JsonTags() {} private JsonTags(Tags tags) { super(tags.stream() .collect(Collectors.toMap(tag_entry -> tag_entry.getKey(), tag_entry -> extractMetricValue(tag_entry.getValue())))); } public static JsonTags valueOf(Tags tags) { return TAGS_CACHE.apply(tags); } }
groupon/monsoon
exporter/src/main/java/com/groupon/lex/metrics/json/JsonTags.java
Java
bsd-3-clause
903
[ 30522, 7427, 4012, 1012, 2177, 2239, 1012, 17244, 1012, 12046, 2015, 1012, 1046, 3385, 1025, 12324, 4012, 1012, 8224, 1012, 2691, 1012, 17053, 1012, 17053, 8569, 23891, 2099, 1025, 12324, 4012, 1012, 8224, 1012, 2691, 1012, 17053, 1012, 170...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Ty666\LaravelTheme; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\View; use Ty666\LaravelTheme\Exception\ThemeNotFound; class ThemeManager { protected $config; protected $files; protected $activeTheme; protected $activeThemeConfig = null; protected $isUseTheme = false; public function isUseTheme() { return $this->isUseTheme; } public function useTheme() { $this->isUseTheme = true; } public function cancelTheme() { $this->isUseTheme = false; } public function __construct(Filesystem $files, $config) { $this->files = $files; $this->config = $config; $this->setActiveTheme($config['default_theme']); } public function getConfig($key = null) { if (!is_null($key)) { return $this->config[$key]; } return $this->config; } public function setActiveTheme($theme) { $this->activeTheme = $theme; View::replaceNamespace('theme_' . $theme, $this->config['themes_path'] . DIRECTORY_SEPARATOR . $theme . DIRECTORY_SEPARATOR . 'views'); } public function getActiveTheme() { return $this->activeTheme; } public function getAllThemeConfig() { $themePaths = $this->files->directories($this->config['themes_path']); $themeConfigs = []; foreach ($themePaths as $themePath) { $themeId = basename($themePath); try { $themeConfigs[] = $this->getThemeConfig($themeId) + ['theme_id' => $themeId]; } catch (ThemeNotFound $e) { continue; } } return $themeConfigs; } public function getThemeConfig($themeId = null) { if (is_null($themeId)) { $themeId = $this->activeTheme; } $themePath = $this->config['themes_path'] . DIRECTORY_SEPARATOR . $themeId . DIRECTORY_SEPARATOR; $configFile = $themePath . $this->config['config_file_name']; if (!$this->files->exists($configFile)) { throw new ThemeNotFound($themeId . ' 主题不存在'); } $themeConfig = json_decode($this->files->get($configFile), true); $themeConfig['screenshot_url'] = route($this->config['screenshot_route']['name'], $themeId); return $themeConfig; } public function getActiveThemeConfig() { if (is_null($this->activeThemeConfig)) { $this->activeThemeConfig = $this->getThemeConfig(); } return $this->activeThemeConfig; } public function themeView($view, $data = [], $mergeData = []) { $this->useTheme(); return View::make($view, $data, $mergeData); } public function getActiveThemePath() { return $this->config['themes_path'] . DIRECTORY_SEPARATOR . $this->activeTheme; } }
ty666/laravel-theme
src/ThemeManager.php
PHP
mit
2,906
[ 30522, 1026, 1029, 25718, 3415, 15327, 5939, 28756, 2575, 1032, 13679, 15985, 10760, 4168, 1025, 2224, 5665, 12717, 12556, 1032, 6764, 27268, 6633, 1032, 6764, 27268, 6633, 1025, 2224, 5665, 12717, 12556, 1032, 2490, 1032, 28708, 1032, 3193, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.internal.config; import com.amazonaws.annotation.Immutable; /** * Signer configuration. */ @Immutable public class SignerConfig { private final String signerType; SignerConfig(String signerType) { this.signerType = signerType; } SignerConfig(SignerConfig from) { this.signerType = from.getSignerType(); } public String getSignerType() { return signerType; } @Override public String toString() { return signerType; } }
loremipsumdolor/CastFast
src/com/amazonaws/internal/config/SignerConfig.java
Java
mit
1,109
[ 30522, 1013, 1008, 1008, 9385, 2230, 1011, 2418, 9733, 1012, 4012, 1010, 4297, 1012, 2030, 2049, 18460, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright 2007 Albert Strasheim <fullung@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <boost/python/class.hpp> #include <boost/python/manage_new_object.hpp> #include <boost/python/dict.hpp> #include <cms/MapMessage.h> namespace py = boost::python; using cms::MapMessage; using cms::Message; static const char* MapMessage_docstring = "A C{MapMessage} object is used to send a set of name-value pairs.\n\n" "The names are C{String} objects, and the values are primitive data types in the " "Java programming language. The names must have a value that is not null, and " "not an empty string. The entries can be accessed sequentially or randomly by " "name. The order of the entries is undefined. C{MapMessage} inherits from the " "L{Message} interface and adds a message body that contains a C{Map}.\n\n" "When a client receives a C{MapMessage}, it is in read-only mode. If a client " "attempts to write to the message at this point, a L{CMSException} is thrown."; static const char* MapMessage_mapNames_docstring = "Returns an enumeration of all the names in the C{MapMessage} object."; static const char* MapMessage_itemExists_docstring = "Indicates whether an item exists in this C{MapMessage} object."; static const char* MapMessage_getBoolean_docstring = "Returns the C{Boolean} value of the specified name."; static const char* MapMessage_setBoolean_docstring = "Sets a boolean value with the specified name into the C{Map}."; static const char* MapMessage_getByte_docstring = "Returns the byte value of the specified name."; static const char* MapMessage_setByte_docstring = "Sets a byte value with the specified name into the C{Map}."; static const char* MapMessage_getBytes_docstring = "Returns the bytes value of the specified name."; static const char* MapMessage_setBytes_docstring = "Sets a bytes value with the specified name into the C{Map}."; static const char* MapMessage_getChar_docstring = "Returns the char value of the specified name."; static const char* MapMessage_setChar_docstring = "Sets a char value with the specified name into the C{Map}."; static const char* MapMessage_getDouble_docstring = "Returns the double value of the specified name."; static const char* MapMessage_setDouble_docstring = "Sets a double value with the specified name into the C{Map}."; static const char* MapMessage_getFloat_docstring = "Returns the float value of the specified name."; static const char* MapMessage_setFloat_docstring = "Sets a float value with the specified name into the C{Map}."; static const char* MapMessage_getInt_docstring = "Returns the int value of the specified name."; static const char* MapMessage_setInt_docstring = "Sets a int value with the specified name into the C{Map}."; static const char* MapMessage_getLong_docstring = "Returns the long value of the specified name."; static const char* MapMessage_setLong_docstring = "Sets a long value with the specified name into the C{Map}."; static const char* MapMessage_getShort_docstring = "Returns the short value of the specified name."; static const char* MapMessage_setShort_docstring = "Sets a short value with the specified name into the C{Map}."; static const char* MapMessage_getString_docstring = "Returns the string value of the specified name."; static const char* MapMessage_setString_docstring = "Sets a String value with the specified name into the C{Map}."; static const char* MapMessage_getBytes(MapMessage& This, const std::string& name) { #if 0 return reinterpret_cast<const char*>(This.getBytes(name)); #else return 0; #endif } static MapMessage* MapMessage_deepcopy(MapMessage* This, py::dict memo) { return dynamic_cast<MapMessage*>(This->clone()); } void export_MapMessage() { py::class_<MapMessage, py::bases<Message>, boost::noncopyable>("MapMessage", MapMessage_docstring, py::no_init) .add_property("mapNames", &MapMessage::getMapNames, MapMessage_mapNames_docstring) .def("itemExists", &MapMessage::itemExists, MapMessage_itemExists_docstring) .def("getBoolean", &MapMessage::getBoolean, MapMessage_getBoolean_docstring) .def("setBoolean", &MapMessage::setBoolean, MapMessage_setBoolean_docstring) .def("getByte", &MapMessage::getByte, MapMessage_getByte_docstring) .def("setByte", &MapMessage::setByte, MapMessage_setByte_docstring) .def("getBytes", MapMessage_getBytes, MapMessage_getBytes_docstring) .def("setBytes", &MapMessage::setBytes, MapMessage_setBytes_docstring) .def("getChar", &MapMessage::getChar, MapMessage_getChar_docstring) .def("setChar", &MapMessage::setChar, MapMessage_setChar_docstring) .def("getDouble", &MapMessage::getDouble, MapMessage_getDouble_docstring) .def("setDouble", &MapMessage::setDouble, MapMessage_setDouble_docstring) .def("getFloat", &MapMessage::getFloat, MapMessage_getFloat_docstring) .def("setFloat", &MapMessage::setFloat, MapMessage_setFloat_docstring) .def("getInt", &MapMessage::getInt, MapMessage_getInt_docstring) .def("setInt", &MapMessage::setInt, MapMessage_setInt_docstring) .def("getLong", &MapMessage::getLong, MapMessage_getLong_docstring) .def("setLong", &MapMessage::setLong, MapMessage_setLong_docstring) .def("getShort", &MapMessage::getShort, MapMessage_getShort_docstring) .def("setShort", &MapMessage::setShort, MapMessage_setShort_docstring) .def("getString", &MapMessage::getString, MapMessage_getString_docstring) .def("setString", &MapMessage::setString, MapMessage_setString_docstring) .def("__deepcopy__", MapMessage_deepcopy, py::return_value_policy<py::manage_new_object>()); }
tabish121/pyActiveMQ
src/main/MapMessage.cpp
C++
apache-2.0
6,225
[ 30522, 1013, 1008, 9385, 2289, 4789, 2358, 8180, 8049, 1026, 2440, 5575, 1030, 20917, 4014, 1012, 4012, 1028, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 2017, 2089, 2025, 2224, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. 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/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include "HeadSpin.h" #include "plComponent.h" #include "plComponentReg.h" #include "plMiscComponents.h" #include "MaxMain/plMaxNode.h" #include "resource.h" #include <iparamm2.h> #pragma hdrstop #include "MaxMain/plPlasmaRefMsgs.h" #include "pnSceneObject/plSceneObject.h" #include "pnSceneObject/plCoordinateInterface.h" #include "pnSceneObject/plDrawInterface.h" #include "plMessage/plSimStateMsg.h" #include "pnMessage/plEnableMsg.h" #include "MaxMain/plPluginResManager.h" void DummyCodeIncludeFuncIgnore() {} ///////////////////////////////////////////////////////////////////////////////////////////////// // // Ignore Component // // //Class that accesses the paramblock below. class plIgnoreComponent : public plComponent { public: plIgnoreComponent(); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg); bool Convert(plMaxNode *node, plErrorMsg *pErrMsg); virtual void CollectNonDrawables(INodeTab& nonDrawables); }; //Max desc stuff necessary below. CLASS_DESC(plIgnoreComponent, gIgnoreDesc, "Ignore", "Ignore", COMP_TYPE_IGNORE, Class_ID(0x48326288, 0x528a3dea)) enum { kIgnoreMeCheckBx }; ParamBlockDesc2 gIgnoreBk ( plComponent::kBlkComp, _T("Ignore"), 0, &gIgnoreDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_IGNORE, IDS_COMP_IGNORES, 0, 0, NULL, kIgnoreMeCheckBx, _T("Ignore"), TYPE_BOOL, 0, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORE_CKBX, end, end ); plIgnoreComponent::plIgnoreComponent() { fClassDesc = &gIgnoreDesc; fClassDesc->MakeAutoParamBlocks(this); } void plIgnoreComponent::CollectNonDrawables(INodeTab& nonDrawables) { if (fCompPB->GetInt(kIgnoreMeCheckBx)) { AddTargetsToList(nonDrawables); } } // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool plIgnoreComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { if (fCompPB->GetInt(kIgnoreMeCheckBx)) pNode->SetCanConvert(false); return true; } bool plIgnoreComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// // // IgnoreLite Component // // //Class that accesses the paramblock below. class plIgnoreLiteComponent : public plComponent { public: enum { kSelectedOnly }; enum LightState { kTurnOn, kTurnOff, kToggle }; public: plIgnoreLiteComponent(); void SetState(LightState s); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; } bool PreConvert(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; } bool Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; } }; class plIgnoreLiteProc : public ParamMap2UserDlgProc { public: BOOL DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_COMMAND: if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_ON) ) { plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner(); ilc->SetState(plIgnoreLiteComponent::kTurnOn); return TRUE; } if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_OFF) ) { plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner(); ilc->SetState(plIgnoreLiteComponent::kTurnOff); return TRUE; } if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_TOGGLE) ) { plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner(); ilc->SetState(plIgnoreLiteComponent::kToggle); return TRUE; } break; } return false; } void DeleteThis() {} }; static plIgnoreLiteProc gIgnoreLiteProc; //Max desc stuff necessary below. CLASS_DESC(plIgnoreLiteComponent, gIgnoreLiteDesc, "Control Max Light", "ControlLite", COMP_TYPE_IGNORE, IGNORELITE_CID) ParamBlockDesc2 gIgnoreLiteBk ( plComponent::kBlkComp, _T("IgnoreLite"), 0, &gIgnoreLiteDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_IGNORELITE, IDS_COMP_IGNORELITES, 0, 0, &gIgnoreLiteProc, plIgnoreLiteComponent::kSelectedOnly, _T("SelectedOnly"), TYPE_BOOL, 0, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORELITE_SELECTED, end, end ); plIgnoreLiteComponent::plIgnoreLiteComponent() { fClassDesc = &gIgnoreLiteDesc; fClassDesc->MakeAutoParamBlocks(this); } void plIgnoreLiteComponent::SetState(LightState s) { BOOL selectedOnly = fCompPB->GetInt(kSelectedOnly); int numTarg = NumTargets(); int i; for( i = 0; i < numTarg; i++ ) { plMaxNodeBase* targ = GetTarget(i); if( targ ) { if( selectedOnly && !targ->Selected() ) continue; Object *obj = targ->EvalWorldState(TimeValue(0)).obj; if (obj && (obj->SuperClassID() == SClass_ID(LIGHT_CLASS_ID))) { LightObject* liObj = (LightObject*)obj; switch( s ) { case kTurnOn: liObj->SetUseLight(true); break; case kTurnOff: liObj->SetUseLight(false); break; case kToggle: liObj->SetUseLight(!liObj->GetUseLight()); break; } } } } } ///////////////////////////////////////////////////////////////////////////////////////////////// // // Barney Component // // //Class that accesses the paramblock below. class plBarneyComponent : public plComponent { public: plBarneyComponent(); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg); bool Convert(plMaxNode *node, plErrorMsg *pErrMsg); }; //Max desc stuff necessary below. CLASS_DESC(plBarneyComponent, gBarneyDesc, "Barney", "Barney", COMP_TYPE_IGNORE, Class_ID(0x376955dc, 0x2fec50ae)) ParamBlockDesc2 gBarneyBk ( plComponent::kBlkComp, _T("Barney"), 0, &gBarneyDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_BARNEY, IDS_COMP_BARNEYS, 0, 0, NULL, end ); plBarneyComponent::plBarneyComponent() { fClassDesc = &gBarneyDesc; fClassDesc->MakeAutoParamBlocks(this); } // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool plBarneyComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { pNode->SetCanConvert(false); pNode->SetIsBarney(true); return true; } bool plBarneyComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// // // NoShow Component // // //Class that accesses the paramblock below. class plNoShowComponent : public plComponent { public: enum { kShowable, kAffectDraw, kAffectPhys }; public: plNoShowComponent(); virtual void CollectNonDrawables(INodeTab& nonDrawables); // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg); bool Convert(plMaxNode *node, plErrorMsg *pErrMsg); }; const Class_ID COMP_NOSHOW_CID(0x41cb2b85, 0x615932c6); //Max desc stuff necessary below. CLASS_DESC(plNoShowComponent, gNoShowDesc, "NoShow", "NoShow", COMP_TYPE_IGNORE, COMP_NOSHOW_CID) ParamBlockDesc2 gNoShowBk ( plComponent::kBlkComp, _T("NoShow"), 0, &gNoShowDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp, IDD_COMP_NOSHOW, IDS_COMP_NOSHOW, 0, 0, NULL, plNoShowComponent::kShowable, _T("Showable"), TYPE_BOOL, 0, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_SHOWABLE, end, plNoShowComponent::kAffectDraw, _T("AffectDraw"), TYPE_BOOL, 0, 0, p_default, TRUE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTDRAW, end, plNoShowComponent::kAffectPhys, _T("AffectPhys"), TYPE_BOOL, 0, 0, p_default, FALSE, p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTPHYS, end, end ); plNoShowComponent::plNoShowComponent() { fClassDesc = &gNoShowDesc; fClassDesc->MakeAutoParamBlocks(this); } // SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading // of properties on the MaxNode, as it's still indeterminant. bool plNoShowComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { if( !fCompPB->GetInt(kShowable) ) { if( fCompPB->GetInt(kAffectDraw) ) pNode->SetDrawable(false); if( fCompPB->GetInt(kAffectPhys) ) pNode->SetPhysical(false); } return true; } bool plNoShowComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg) { plSceneObject* obj = node->GetSceneObject(); if( !obj ) return true; if( fCompPB->GetInt(kShowable) ) { if( fCompPB->GetInt(kAffectDraw) ) { plEnableMsg* eMsg = new plEnableMsg(nil, plEnableMsg::kDisable, plEnableMsg::kDrawable); eMsg->AddReceiver(obj->GetKey()); eMsg->Send(); } if( fCompPB->GetInt(kAffectPhys) ) { hsAssert(0, "Who uses this?"); // plEventGroupEnableMsg* pMsg = new plEventGroupEnableMsg; // pMsg->SetFlags(plEventGroupEnableMsg::kCollideOff | plEventGroupEnableMsg::kReportOff); // pMsg->AddReceiver(obj->GetKey()); // pMsg->Send(); } #if 0 plDrawInterface* di = node->GetDrawInterface(); if( di && { di->SetProperty(plDrawInterface::kDisable, true); } #endif } return true; } void plNoShowComponent::CollectNonDrawables(INodeTab& nonDrawables) { if( fCompPB->GetInt(kAffectDraw) ) AddTargetsToList(nonDrawables); }
Lyrositor/Plasma
Sources/Tools/MaxComponent/plIgnoreComponent.cpp
C++
gpl-3.0
12,779
[ 30522, 1013, 1008, 1027, 1027, 6105, 1027, 1027, 1008, 22330, 2319, 11108, 2015, 1012, 4012, 3194, 1011, 3461, 8649, 7396, 1010, 8241, 1998, 5906, 9385, 1006, 1039, 1007, 2249, 22330, 2319, 8484, 1010, 4297, 1012, 2023, 2565, 2003, 2489, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...