Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
As it was said here before Rails (ActiveSupport) have a handy blank? method and it is implemented like this:
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
Pretty easy to add to any ruby-based project.
The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.
If you need to refer them somewhere in the Java Code, you'd rahter put your files into the "res" directory.
And all files in the res folder will be indexed in the R file, which makes it much faster (and much easier!) to load them.
I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.
You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.
I would also recommend using Adam's Who is Active script, although that is a bit more advanced.
And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.
My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.
$files = array_diff(scandir($dir,SCANDIR_SORT_DESCENDING), array('..', '.'));
print_r($files);
Please follow the below steps
1). First, navigate to the /etc/postgresql/{your pg version}/main directory.
My version is 10 Then:
cd /etc/postgresql/10/main
2). Here resides the pg_hba.conf file needs to do some changes here you may need sudo access for this.
sudo nano pg_hba.conf
3). Scroll down the file till you find this –
# Database administrative login by Unix domain socket
local all postgres peer
4). Here change the peer to md5 as follows.
# Database administrative login by Unix domain socket
local all all md5
peer means it will trust the authenticity of UNIX user hence does not
prompt for the password. md5 means it will always ask for a password, and validate it after hashing with MD5.
5).Now save the file and restart the Postgres server.
sudo service postgresql restart
Now it should be ok.
This works in Python:
import base64
def IsBase64(str):
try:
base64.b64decode(str)
return True
except Exception as e:
return False
if IsBase64("ABC"):
print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
else:
print("ABC is NOT Base64-encoded.")
if IsBase64("QUJD"):
print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
else:
print("QUJD is NOT Base64-encoded.")
Summary: IsBase64("string here")
returns true if string here
is Base64-encoded, and it returns false if string here
was NOT Base64-encoded.
After updating to Xcode 8.3.2 i had the same error with a Cordova project. I needed to upgrade Cordova (v7.0.0) and the iOS platform (v4.4.0) for code signing to work.
Although we should agree that ultimately you cannot prevent some form of document capture (specially through screen capture technology either through phone or computer), the goal is to prevent direct download of original document. Some suggest you turn it into images, but this is not necessary. There is clearly a way, as several cloud services allow you to share pdf files, removing the download option, without converting the PDF to images (a superior method because it retains important properties like word search). Personally, as a user of Outlook email, I use the cloud service it provides, OneDrive. I just want to share the HTML code produced by OneDrive to share PDF files without download and right-click support. I am no expert on HTMl so cannot tell you exactly how it is done, but it might still provide you some insights. Here is the code for one particular PDF I shared (without private information and other bits that seemed unnecessary to me):
<!DOCTYPE html>
<html lang="en-us" dir="ltr">
<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-type" content="text/html; charset=utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta http-equiv="Expires" content="0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" /><title>
OneDrive for Business
</title><link rel="shortcut icon" href="/_layouts/15/images/odbfavicon.ico?rev=47" type="image/vnd.microsoft.icon" id="favicon" /></head>
<body style="margin: 0; padding: 0;">
<script nonce= '55c3d852-fe79-49b0-927d-e793a0ba3192' >if(!spfxPerfMarks){var spfxPerfMarks = {};} var markPerfStage=function(key) {if(window.performance && typeof window.performance.now === 'function'){spfxPerfMarks[key]=window.performance.now();} else{spfxPerfMarks[key]=Date.now();} if (window.performance && typeof window.performance.mark === 'function') {window.performance.mark(key);}};</script><script type="text/javascript" id="SuiteNavShellCore" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192" crossorigin="anonymous" src="https://shellprod.msocdn.com/api/shellbootstrapper/business/oneshell">
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
window.document.getElementById('SuiteNavShellCore').addEventListener('error', function() {
var scriptElem = document.getElementById('SuiteNavShellCore');
scriptElem.parentNode.removeChild(scriptElem);
var newScript = document.createElement('script');
newScript.setAttribute('type', 'text/javascript');
newScript.setAttribute('id', 'SuiteNavShellCore');
newScript.setAttribute('src', 'https://shellprod.msocdn.com/api/shellbootstrapper/business/oneshell');
newScript.setAttribute('crossorigin', 'anonymous');
newScript.async = true;
newScript.addEventListener('load', function() { (typeof markPerfStage === 'function' && markPerfStage('suiteNavScriptAsyncEnd')); if (window.executeSuiteNavOnce) { window.executeSuiteNavOnce() } });
newScript.addEventListener('error', function() { window.o365ShellScriptLoadError = arguments[0]; (typeof markPerfStage === 'function' && markPerfStage('suiteNavScriptError')); if (window.executeSuiteNavOnce) { window.executeSuiteNavOnce() } });
document.head.appendChild(newScript); });
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
window.o365ShellLoadPromiseResolve = undefined; window.o365ShellLoadPromiseReject = undefined; window.o365ShellRenderPromiseResolve = undefined; window.o365ShellRenderPromiseReject = undefined; window.o365ShellPostRenderPromiseResolve = undefined; window.o365ShellPostRenderPromiseReject = undefined; window.o365ShellLoadPromise = new Promise(function (loadResolve, loadReject) { window.o365ShellLoadPromiseResolve = loadResolve, window.o365ShellLoadPromiseReject = loadReject }); window.o365ShellRenderPromise = new Promise(function (renderResolve, renderReject) { window.o365ShellRenderPromiseResolve = renderResolve, window.o365ShellRenderPromiseReject = renderReject }); window.o365ShellPostRenderPromise = new Promise(function (prResolve,prReject) { window.o365ShellPostRenderPromiseResolve = prResolve, window.o365ShellPostRenderPromiseReject = prReject });var executeSuiteNav = function () {var suiteNavPlaceholder = document.createElement('div');suiteNavPlaceholder.id = 'SuiteNavPlaceholder';suiteNavPlaceholder.style = "min-height: 50px";document.body.insertBefore(suiteNavPlaceholder, document.body.firstChild);if (window.o365ShellScriptLoadError) {o365ShellLoadPromiseReject(window.o365ShellScriptLoadError);o365ShellRenderPromiseReject(new Error('SuiteNavLoadError'));o365ShellPostRenderPromiseReject(new Error('SuiteNavLoadError'));return; }o365ShellLoadPromiseResolve();var themeData;try { themeData = JSON.parse(localStorage.getItem('odSuiteNavthemedata')).themeData; }catch(err) { themeData = {Primary:'#0078D4'}; }(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncStart'));O365Shell.RenderAsync({top: 'SuiteNavPlaceholder', layout: 'Mouse', enableSearchUX: true, initialSearchUXVisibility: true, initialSearchUXPlaceholderText: 'Search', initialSearchUXSearchText: "",enableDelayLoading: true, collapseO365Settings: true, disableDelayLoad: false, disableShellPlus: false, isThinHeader: false, enableLegacyResponsiveBehavior: false, expectSearchBoxSettings: true, shellDataOverrides: {}, supportShyHeaderMode: false, initialRenderData: { AppBrandTheme: themeData, Culture: 'en-US', CurrentMainLinkElementId: 'ShellDocuments', IsConsumer: false, UserDisplayName: 'JOHN DOE', UserID: '100320009e7b358d', WorkloadId: 'Sharepoint', ShellBootHost: 'https://shellprod.msocdn.com', EnableVanillaSearchBox: true }},function () {(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncEnd'));o365ShellRenderPromiseResolve();},function () {(typeof markPerfStage === 'function' && markPerfStage('suiteNavPostRender'));o365ShellPostRenderPromiseResolve();},function (error) {(typeof markPerfStage === 'function' && markPerfStage('suiteNavRenderAsyncErrorEnd'));o365ShellRenderPromiseReject(error); o365ShellPostRenderPromiseReject(error);});};
</script><script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
var params = window.location.search.substring(1).split('&') || [];
var shouldExecuteSuiteNav = true;
shouldExecuteSuiteNav &= params.indexOf('p=2') === -1;
shouldExecuteSuiteNav &= params.indexOf('cl=true') === -1;
shouldExecuteSuiteNav &= params.filter(function (x) { return x.indexOf('parent') === 0; }).length === 0;
try { shouldExecuteSuiteNav &= window.parent === window; } catch(err) { shouldExecuteSuiteNav = false; }
if (shouldExecuteSuiteNav) { executeSuiteNav(); }
</script>
</body>
<script type="text/javascript">
try {
(function() {
var a = navigator.userAgent.toLowerCase();
var i = a.indexOf("msie");
if (-1 !== i) {
var v = parseInt(a.substring(i + 5));
if (v <= 8 && Boolean(document.documentMode) && document.documentMode <= 8) {
var d = new Date(); d.setTime(d.getTime() + 31536000000);
document.cookie = "odbnu=0;expires=" + d.toUTCString() + ";path=/";
window.location.href = window.location.href.replace(/\/onedrive\.aspx/i, '/start.aspx#/Documents/Forms/All.aspx');
}
}
})();
} catch(e) {}
</script>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
SOME PRIVATE STUFF HERE
</script><link rel="preconnect" href="https://spoprod-a.akamaihd.net" crossorigin /><script type="text/javascript">
!function(){if('PerformanceLongTaskTiming' in window){var g=window.__tti={e:[]};g.o=new PerformanceObserver(function(l){g.e=g.e.concat(l.getEntries())});g.o.observe({entryTypes:['longtask']})}}();
</script><script type="text/javascript">
var g_responseEnd = new Date().getTime();window['FabricConfig'] = { fontBaseUrl: ''};window['__odsp_culture'] = 'en-us';window['__odspSriHashes'] = {"listviewdataprefetch-mini-c82c051f.js":"sha256-GCNR9Rk+cuSJfvbszuhs5ZBaUs5tQ2RdzzJTteHOXGk=","reactandknockout-mini-584215d6.js":"sha256-ICjqvvD9qHiKbj5xYFNGC/JsgNcqNRRL1t3kW4RVioI=","aria-mini-2e5a74c4.js":"sha256-CbCwYga9yHE+t1OvB+NHHDdH2rxSfY6KJkCMiUpXQjw=","spectreviewer-mini-9c641fce.js":"sha256-tqmAhKxEONjZOpZuGrbo8VdnLx6kRH+Xfhjrcchv2+4=","babylonjs-mini-22e57381.js":"sha256-T6IgL4CdkolwNC0L4tG6d+G07Bhuc7bI1pSIShdrTUk=","sp-http_odb-mini-21a5eb98.js":"sha256-mTfdqB83ALG/d2z8krhrUugjXBzFQ/bzPfUIgcayACg=","onedriveappfontsplt-mini-ce0e18ec.js":"sha256-+ockQ4cjstrmVqBPVRH8C9Z9M0ZJbyQxHQ/cm/ukBOI=","onedriveappfontsdeferred-mini-3771cbb9.js":"sha256-qXZjhCWJDNPCbbXRIwDt1cqIyqzQKqROnwdASmSsoGw=","odbonedriveapp-mini-11081db7.js":"sha256-j/CkxuEVbtMOL5PRKZ05dZURZ/aNH9tk6vnMj6ei/lk=","en-us/
</script><script type="text/javascript">
window['moduleNameMapping']={"odsp-next/providers/operation/OperationProvider":"Rq"};
</script><script type="text/javascript" data-import-link="https://spoprod-a.akamaihd.net/files/odsp-common-library-prod_2019-02-15_20190219.002/require.js" id="requireJsString">
SOME VERY LONG FUNCTION CODE
</script><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/listviewdataprefetch-mini-c82c051f.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/reactandknockout-mini-584215d6.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbonedriveapp-mini-11081db7.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbonedriveapp-mini.resx-7f957d5c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbonedrive-mini-5e8b1855.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbonedrive-mini.resx-374bb468.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbfiles-mini-9aaee23c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbfiles-mini.resx-250da06d.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/odbitemsscope-mini-5070e33c.js" rel="preload" crossorigin="anonymous" as="script" /><link href="https://spoprod-a.akamaihd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/en-us/odbitemsscope-mini.resx-ff223e24.js" rel="preload" crossorigin="anonymous" as="script" /><script type="text/javascript" id="requireConfig">
!function(){
var backupBaseUrl = 'https://az741266.vo.msecnd.net/files/odsp-next-prod-amd_2020-06-12_20200612.001/';
window.__backupBaseUrl = backupBaseUrl;
var failOverState = window.__cdnFailOverState = {
baseUrlFailedOver: false,
modulesFalledBack: []
};
function processConfigToSupportFailOver(config) {
var paths = {};
for (var bundleId in config.bundles) {
var bundlePath = config.paths[bundleId];
var fallbackPaths = [bundlePath, backupBaseUrl + bundlePath];
for (var _i = 0, _a = config.bundles[bundleId]; _i < _a.length; _i++) {
var moduleName = _a[_i];
paths[moduleName] = fallbackPaths;
}
}
return {
paths: paths,
shim: config.shim,
deps: config.deps,
baseUrl: config.baseUrl,
waitSeconds: config.waitSeconds,
onNodeCreated: config.onNodeCreated,
enforceDefine: config.enforceDefine,
onPathFallback: function (options) {
var moduleId = options.moduleId;
var config = options.config;
if (moduleId && config && config.deps && config.deps.indexOf(moduleId) >= 0) {
var failedModules = failOverState.modulesFalledBack;
failedModules.push(moduleId);
if (!failOverState.baseUrlFailedOver && failedModules.length >= 2) {
require.config({
baseUrl: backupBaseUrl
});
failOverState.baseUrlFailedOver = true;
}
}
}
};
}
var config = {paths:{"listviewdataprefetch-mini":"listviewdataprefetch-mini-c82c051f","reactandknockout-mini":"reactandknockout-mini-584215d6","aria-mini":"aria-mini-2e5a74c4","spectreviewer-mini":"spectreviewer-mini-9c641fce","babylonjs-mini":"babylonjs-mini-22e57381","sp-http_odb-mini":"sp-http_odb-mini-21a5eb98","onedriveappfontsplt-mini":"onedriveappfontsplt-mini-ce0e18ec","onedriveappfontsdeferred-mini":"onedriveappfontsdeferred-mini-3771cbb9","odbonedriveapp-mini":"odbonedriveapp-mini-11081db7","odbonedriveapp-mini.resx":"en-us/odbonedriveapp-mini.resx-7f957d5c","odbonedrive-mini":"odbonedrive-mini-5e8b1855","odbonedrive-mini.resx":"en-us/odbonedrive-mini.resx-374bb468","odbbasepage-mini":"odbbasepage-mini-8d7dea71","odbfiles-mini":"odbfiles-mini-9aaee23c","odbfiles-mini.resx":"en-us/odbfiles-mini.resx-250da06d","odbuploadmanager-mini":"odbuploadmanager-mini-168f0ee8","odbuploadmanager-mini.resx":"en-us/odbuploadmanager-mini.resx-660b735c","odbreactcontrols-mini":"odbreactcontrols-mini-6f323ced","odbreactcontrols-mini.resx":"en-us/odbreactcontrols-mini.resx-c7ec26e2","odbdeferred-mini":"odbdeferred-mini-b9def3da","odbdeferred-mini.resx":"en-us/odbdeferred-mini.resx-d1f98f82","odblivepersonapicker-mini":"odblivepersonapicker-mini-414c6f81","odbdebugwindow-mini":"odbdebugwindow-mini-2f4ef22c","odbfilepicker-mini":"odbfilepicker-mini-2f5a2203","odbfilepicker-mini.resx":"en-us/odbfilepicker-mini.resx-3562db06","odbembed-mini":"odbembed-mini-8638d6c3","odboneup-mini":"odboneup-mini-3086899d","odboneup-mini.resx":"en-us/odboneup-mini.resx-a7d40d5e","odbpdf-mini":"odbpdf-mini-7d046eb1","odbpdf-mini.resx":"en-us/odbpdf-mini.resx-e5e07b77","odbwrs-mini":"odbwrs-mini-2c0b0a8b","odbsharepage-mini":"odbsharepage-mini-e62fc2f8","odbtextfileeditor-mini":"odbtextfileeditor-mini-000ede78","odbtextfileeditor-mini.resx":"en-us/odbtextfileeditor-mini.resx-259dbac3","odbfilerequestpage-mini":"odbfilerequestpage-mini-db0e14b3","odbfilerequestpage-mini.resx":"en-us/odbfilerequestpage-mini.resx-8e83db21","odbtiles-mini":"odbtiles-mini-a111ffa2","odbtiles-mini.resx":"en-us/odbtiles-mini.resx-4fae993b","odbsites-mini":"odbsites-mini-c5563389","odbsites-mini.resx":"en-us/odbsites-mini.resx-1b3b4aeb","odbitemvideoplayer-mini":"odbitemvideoplayer-mini-b7a61bf1","odbitemvideoplayer-mini.resx":"en-us/odbitemvideoplayer-mini.resx-983d47a8","odbexecutors-mini":"odbexecutors-mini-f93c0ada","odbexecutors-mini.resx":"en-us/odbexecutors-mini.resx-853081e6","odbdeferredcontrols-mini":"odbdeferredcontrols-mini-29643ad1","odbdeferredcontrols-mini.resx":"en-us/odbdeferredcontrols-mini.resx-d50ca5ed","odbnotifications-mini":"odbnotifications-mini-04da08b9","odbpushchannel-mini":"odbpushchannel-mini-38d90d10","odberror-mini":"odberror-mini-12596c1d","odberror-mini.resx":"en-us/odberror-mini.resx-cf31139d","odbrestore-mini":"odbrestore-mini-950ba62f","odbrestore-mini.resx":"en-us/odbrestore-mini.resx-3a5cbe8e","odbsettingsbasepage-mini":"odbsettingsbasepage-mini-d6c5acdd","odbsettingsbasepage-mini.resx":"en-us/odbsettingsbasepage-mini.resx-b5949852","odbsettings-mini":"odbsettings-mini-ddeab1d1","odbitemsscope-mini":"odbitemsscope-mini-5070e33c","odbitemsscope-mini.resx":"en-us/odbitemsscope-mini.resx-ff223e24","odbitemsscopedeferred-mini":"odbitemsscopedeferred-mini-f918897a","odbitemsscopedeferred-mini.resx":"en-us/odbitemsscopedeferred-mini.resx-af61a995","odbmobileappupsellbasepage-mini":"odbmobileappupsellbasepage-mini-723e546a","odbemptyfolderroot-mini":"odbemptyfolderroot-mini-f9f096eb","odbwinappcommunicator-mini":"odbwinappcommunicator-mini-60ab2c1a","odbcreatesite-mini":"odbcreatesite-mini-5400c9ec","odbcreatesite-mini.resx":"en-us/odbcreatesite-mini.resx-d9c236d6","odb-functional-tests-mini":"odb-functional-tests-mini-41e66bd6","odbhighcharts-mini":"odbhighcharts-mini-ce7056aa","odbclientform-mini":"odbclientform-mini-106b2b9f","odbclientform-mini.resx":"en-us/odbclientform-mini.resx-356af9e8","odbfloodgate-mini":"odbfloodgate-mini-061846b3","odbfloodgate-mini.resx":"en-us/odbfloodgate-mini.resx-610e7422","odbpowerapps-mini":"odbpowerapps-mini-c5977eac","msflowsdk":"msflowsdk-8689f64f","power-app":"power-app-86d2bb4d"},"directional-navigation":{}},deps:["bL3","f","bvB","a6o","buW","buZ","bfi"],baseUrl:"https:\u002f\u002fspoprod-a.akamaihd.net\u002ffiles\u002fodsp-next-prod-amd_2020-06-12_20200612.001\u002f",waitSeconds:0,onNodeCreated:function(n,c,m,u) {
n.setAttribute("crossorigin","anonymous");
var urlParts = u.split('/');
var fileName = urlParts[urlParts.length - 1];
var odspSriHashes = window.__odspSriHashes;
var integrity = odspSriHashes && (odspSriHashes[window.__odsp_culture + '/' + fileName] || odspSriHashes[fileName]);
if (integrity) {
n.setAttribute("integrity",integrity);
}
},enforceDefine:true};
var newConfig = processConfigToSupportFailOver(config);
require.config(newConfig);
}();
</script><script type="text/javascript">
window["_spModuleLink"]={"buildNumber":"odsp-next-prod-amd_2020-06-12_20200612.001","manifestName":"ODBOneDrive","scenarioName":"ODBOneDrive","usingRedirectCookie":false,"bugLinkFormat":null,"ulsLinkFormat":null};
</script>
</html>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
var g_duration = 92;
var g_iisLatency = 2;
var g_cpuDuration = 72;
var g_queryCount = 6;
var g_queryDuration = 18;
var g_requireJSDone = new Date().getTime();
</script><script type="text/javascript">
var _spOneDrivePageDataCache = {"SPHomeWeb:sites/feed":{"cacheContext":{"ListItemId":3,"Hash":null,"MySiteUrl":null,"Time":"2020-05-28T15:24:51.0000000Z","Version":null},"cacheValue":null},"ODBWeb.sites/feed":{"cacheContext":{"ListItemId":4,"Hash":"7iItaPeKRTNyNthQTkF2/CvVyjcOTjNOkCsKnNsKarY=","MySiteUrl":null,"Time":"2020-05-28T15:25:03.0000000Z","Version":"1.0"},"cacheValue":"{\"Items\":[],\"Type\":\"ItemsList\"}"},"ODBWeb.substrate.recommended":{"cacheContext":{"ListItemId":5,"Hash":null,"MySiteUrl":null,"Time":"2020-05-28T15:24:51.0000000Z","Version":null},"cacheValue":null}};
</script>
<script type="text/javascript" nonce="55c3d852-fe79-49b0-927d-e793a0ba3192">
var g_deferDataLoadTime = new Date().getTime();var g_payload = {"parameters":{"__metadata":{"type":"SP.RenderListDataParameters"},"RenderOptions":1513223,"AllowMultipleValueFilterForTaxonomyFields":true, "AddRequiredFields":true}}; var g_listData = {"wpq":"","Templates":{},"ListData":{ "Row" :
[] OTHER SETTINGS WITH PRIVATE STUFF...
}};if (typeof DeferredListDataComplete != "undefined" && DeferredListDataComplete) { DeferredListDataComplete(); }
</script>
Because JavaScript is handling the click event. When you click, the following code is called:
el.addEvent('click', function(e){
if(obj.options.onOpen){
new Event(e).stop();
if(obj.options.open == i){
obj.options.open = null;
obj.options.onClose(this.href, i);
}else{
obj.options.open = i;
obj.options.onOpen(this.href, i);
}
}
})
The onOpen
manually changes the location
.
Edit: Regarding your comment...
If you can modify ImageMenu.js, you could update the script which calls onClose
to pass the a
element object (this
, rather than this.href
)
obj.options.onClose(this, i);
Then update your ImageMenu instance, with the following onOpen
change:
window.addEvent('domready', function(){
var myMenu = new ImageMenu($$('#imageMenu a'), {
openWidth: 310,
border: 2,
onOpen: function(e, i) {
if (e.target === '_blank') {
window.open(e.href);
} else {
location = e.href;
}
}
});
});
This would check for the target property of the element to see if it's _blank
, and then call window.open
, if found.
If you'd prefer not to modify ImageMenu.js, another option would be to modify your links to identify them in your onOpen
handler. Say something like:
<a href="http://www.foracure.org.au/#_b=1" target="_blank" style="width: 105px;"></a>
Then, update your onOpen
call to:
onOpen: function(e, i) {
if (e.indexOf('_b=1') > -1) {
window.open(e);
} else {
location = e;
}
}
The only downside to this is the user sees the hash on hover.
Finally, if the number of links that you plan to open in a new window are low, you could create a map and check against that. Something like:
var linksThatOpenInANewWindow = {
'http://www.foracure.org.au': 1
};
onOpen: function(e, i) {
if (linksThatOpenInANewWindow[e] === 1) {
window.open(e);
} else {
location = e
}
}
The only downside is maintenance, depending on the number of links.
Others have suggested modifying the link (using #
or javascript:
) and adding an inline event handler (onclick
) - I don't recommend that at all as it breaks links when JS is disabled/not supported.
if you want a structured solution (like ORM) then JAXB2 is a good solution.
If you want a serialization like DOT NET then you could use Long Term Persistence of JavaBeans Components
The choice depends on use of serialization.
Here's a bit more information specifically regarding the PATH variable in Lion OS 10.7.x:
If you need to set the PATH globally, the PATH is built by the system in the following order:
/private/etc/paths
, one path per line/private/etc/paths.d
. Each file in that folder can contain multiple paths, one path per line. Load order is determined by the file name first, and then the order of the lines in the file.setenv PATH
statement in /private/etc/launchd.conf
, which will append that path to the path already built in #1 and #2 (you must not use $PATH to reference the PATH variable that has been built so far). But, setting the PATH here is completely unnecessary given the other two options, although this is the place where other global environment variables can be set for all users.These paths and variables are inherited by all users and applications, so they are truly global -- logging out and in will not reset these paths -- they're built for the system and are created before any user is given the opportunity to login, so changes to these require a system restart to take effect.
BTW, a clean install of OS 10.7.x Lion doesn't have an environment.plist
that I can find, so it may work but may also be deprecated.
In my bash shell the following worked like a charm:
cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;'
where input_file is
arg1
arg2
arg3
As evident, this allows you to execute multiple commands with each line from input_file, a nice little trick I learned here.
set "html" option to true if you want to have html into tooltip. Actual html is determined by option "title" (link's title attribute shouldn't be set)
$('#example1').tooltip({placement: 'bottom', title: '<p class="testtooltip">par</p>', html: true});
Visual Studio Code universal official multi-line comment toggle.
macOS: Select code-block and then ?+/
Windows: Select code-block and then Ctrl+/
You should use $(document)
. It is a function trigger for any click event in the document. Then inside you can use the jquery on("click","body *",somefunction)
, where the second argument specifies which specific element to target. In this case every element inside the body.
$(document).on('click','body *',function(){
// $(this) = your current element that clicked.
// additional code
});
My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.
This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.
Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.
Supports ...
#
# Compiler flags
#
CC = gcc
CFLAGS = -Wall -Werror -Wextra
#
# Project files
#
SRCS = file1.c file2.c file3.c file4.c
OBJS = $(SRCS:.c=.o)
EXE = exefile
#
# Debug build settings
#
DBGDIR = debug
DBGEXE = $(DBGDIR)/$(EXE)
DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))
DBGCFLAGS = -g -O0 -DDEBUG
#
# Release build settings
#
RELDIR = release
RELEXE = $(RELDIR)/$(EXE)
RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))
RELCFLAGS = -O3 -DNDEBUG
.PHONY: all clean debug prep release remake
# Default build
all: prep release
#
# Debug rules
#
debug: $(DBGEXE)
$(DBGEXE): $(DBGOBJS)
$(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^
$(DBGDIR)/%.o: %.c
$(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<
#
# Release rules
#
release: $(RELEXE)
$(RELEXE): $(RELOBJS)
$(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^
$(RELDIR)/%.o: %.c
$(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<
#
# Other rules
#
prep:
@mkdir -p $(DBGDIR) $(RELDIR)
remake: clean all
clean:
rm -f $(RELEXE) $(RELOBJS) $(DBGEXE) $(DBGOBJS)
If you are using Homebrew to install [email protected], the location is
/usr/local/Homebrew/var/mysql
I don't know if the location is the same for other versions.
Everyone has it right. Functions .load
, .get
, and .post
, are different ways of using the function .ajax
.
Personally, I find the .ajax raw function very confusing, and prefer to use load, get, or post as I need it.
POST has the following structure:
$.post(target, post_data, function(response) { });
GET has the following:
$.get(target, post_data, function(response) { });
LOAD has the following:
$(*selector*).load(target, post_data, function(response) { });
As you can see, there are little differences between them, because its the situation that determines which one to use. Need to send the info to a file internally? Use .post (this would be most of the cases). Need to send the info in such a way that you could provide a link to the specific moment? Use .get. Both of them allow a callback where you can handle the response of the files.
An important note is that .load acts in two different manners. If you only provide the url of the target document, it will act as a get (and I say act because I tested checking for $_POST
in the called PHP while using default .load behaviour and it detects $_POST
, not $_GET
; maybe it would be more precise to say it acts as .post without any arguments); however, as http://api.jquery.com/load/ says, once you provide an array of arguments to the function, it will POST the information to the file. Whatever the case is, .load function will directly insert the information into a DOM element, which in MANY cases is very legible, and very direct; but still provides a callback if you want to do something more with the response. Additionally, .load allows you to extract a certain block of code from a file, giving you the possibility to save a catalog, for example, in a html file, and retrieve pieces of it (items) directly into DOM elements.
static int binaryToInt (String binary){
char []cA = binary.toCharArray();
int result = 0;
for (int i = cA.length-1;i>=0;i--){
//111 , length = 3, i = 2, 2^(3-3) + 2^(3-2)
// 0 1
if(cA[i]=='1') result+=Math.pow(2, cA.length-i-1);
}
return result;
}
go to tsconfig.json and comment the line the //strict:true this worked for me
You can use XmlDocument and for manipulating or retrieve data from attributes you can Linq to XML classes.
The player_api will be deprecated on Jun 25, 2015. For play youtube videos there is a new api IFRAME_API
It looks like the following code:
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
This seems to be added recently:
https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/3.0.1/
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.
public class MyClass
{
event Action MyEvent;
}
...
MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;
...
Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example
Console.WriteLine(handlers[0].Method.Name);//prints the name of the method
You can examine various properties on the Method property of the delegate to see if a specific function has been added.
If you are looking to see if there is just one attached, you can just test for null.
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
window.opener.$("#serverMsg")
You can specify a new column. You also need to compute the mean along the rows, so use axis=1
.
df['mean'] = df.mean(axis=1)
>>> df
Y1961 Y1962 Y1963 Y1964 Y1965 Region mean
0 82.567307 83.104757 83.183700 83.030338 82.831958 US 82.943612
1 2.699372 2.610110 2.587919 2.696451 2.846247 US 2.688020
2 14.131355 13.690028 13.599516 13.649176 13.649046 US 13.743824
3 0.048589 0.046982 0.046583 0.046225 0.051750 US 0.048026
4 0.553377 0.548123 0.582282 0.577811 0.620999 US 0.576518
if you are using **Bootstrap** this is solution, _x000D_
_x000D_
$(document).ready(function(e) {_x000D_
$('.bootpopup').click(function(){_x000D_
var frametarget = $(this).attr('href');_x000D_
targetmodal = '#myModal'; _x000D_
$('#modeliframe').attr("src", frametarget ); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
<!-- Button trigger modal -->_x000D_
<a href="http://twitter.github.io/bootstrap/" title="Edit Transaction" class="btn btn-primary btn-lg bootpopup" data-toggle="modal" data-target="#myModal">_x000D_
Launch demo modal_x000D_
</a>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
<div class="modal-dialog" role="document">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
<h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
<button type="button" class="btn btn-primary">Save changes</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
This may help
HTML
<div id="textcontainer">
<span id="sometext">This is some information </span>
<div id="container">
</div>
</div>
CSS
#textcontainer{
position:relative;
border:1px solid #000;
width :300px;
height:300px;
}
#container{
background-image :url("http://dcooper.org/gallery/cf_appicon.jpg");
width :100%;
height:100%;
}
#sometext{
position:absolute;
top:50%;
left:50%;
}
Js
$('#container').css('opacity','.1');
ng-show and ng-hide work in opposite way. But the difference between ng-hide or ng-show with ng-if is,if we use ng-if then element will created in the dom but with ng-hide/ng-show element will be hidden completely.
ng-show=true/ng-hide=false:
Element will be displayed
ng-show=false/ng-hide=true:
element will be hidden
ng-if =true
element will be created
ng-if= false
element will be created in the dom.
Thanks All, I found how to do it, which is the same as Dave and Sergey:
I am using QT Creator:
In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")
In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:
void MainWindow::on_pushButton_clicked()
{
QImage imageObject;
imageObject.load(imagePath);
ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));
//OR use the other way by setting the Pixmap directly
QPixmap pixmapObject(imagePath");
ui->myLabel2->setPixmap(pixmapObject);
}
Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.
This can be done in your application Web.Config in the
<appSettings>
section (create the section directly under<configuration>
if it doesn’t exist). Add 2 lines similar to the lines below to the section:<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.
Also, if you had multiple event handlers attached to the same selector executing the same function, you could use
$('table.planning_grid').on('mouseenter mouseleave', function() {
//JS Code
});
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
$('#demoTable td').contents().each(function() {
if (this.nodeType === 3) {
this.textContent
? this.textContent = 'The text has been '
: this.innerText = 'The text has been '
} else {
this.innerHTML = 'changed';
return false;
}
})
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
I am sure there is a smarter way for doing what you want but this should work:
- name : Test var
hosts : all
gather_facts : no
vars:
myvariable : false
tasks:
- name: param1
set_fact:
myvariable: "{{param1}}"
when: param1 is defined
- name: param2
set_fact:
myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
when: param2 is defined
- name: param3
set_fact:
myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
when: param3 is defined
- name: default
set_fact:
myvariable: "default"
when: not myvariable
- debug:
var=myvariable
Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible
class.method
should work.
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
var someString = "(/n{})+++(/n{})---(/n{})$$$";_x000D_
var toRemove = "(/n{})"; // should find & remove last occurrence _x000D_
_x000D_
function removeLast(s, r){_x000D_
s = s.split(r)_x000D_
return s.slice(0,-1).join(r) + s.pop()_x000D_
}_x000D_
_x000D_
console.log(_x000D_
removeLast(someString, toRemove)_x000D_
)
_x000D_
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
Assume time column is in timestamp integer msec format
1 day = 86400000 ms
Here you go:
day_divider = 86400000
df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format
df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format
Define in wp_config file.
/var/www/html/Your-Project-File/wp-config.php
define( 'FS_METHOD', 'direct' );
chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions.
sudo chown -R www-data:www-data /var/www
Why are you wrapping the $_POST
array in an array?
You can access your "id" and "value" arrays using the following
// assuming the appropriate isset() checks for $_POST['id'] and $_POST['value']
$ids = $_POST['id'];
$values = $_POST['value'];
foreach ($ids as $idx => $id) {
// ...
}
foreach ($values as $idx => $value) {
// ...
}
Yes, the upload element is protected from direct manipulation in different browsers. However, you could erase the element from the DOM tree and then insert a new one in its place via JavaScript. That would give you the same result.
Something along the lines of:
$('#container-element').html('<input id="upload-file" type="file"/>');
That is so basic that I am wondering what book you are using to study? Try
data[1, "V1"] # row first, quoted column name second, and case does matter
Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.
I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html
to close bootstrap modal you can pass 'hide' as option to modal method as follow
$('#modal').modal('hide');
Please take a look at working fiddle here
bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation
If non of the above method work, give a id to your close button and trigger click on close button.
Basically your OpenSSL uses SSLv3 and the site you are accessing does not support that protocol.
Just update your wget:
sudo apt-get install wget
Or if it is already supporting another secure protocol, just add it as argument:
wget https://example.com --secure-protocol=PROTOCOL_v1
I have found a solution. It is just a workaround to my problem but currently the only solution.
ViewPager PagerAdapter not updating the View
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Does anyone know whether this is a bug or not?
If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.
In your case, you might do better to have a generic draw()
method, and rely on the subclasses (Rectangle
, Ellipse
) to implement the draw()
method as what you had been thinking of as "drawEllipse" and "drawRectangle".
Already mentioned. Just a LINQ answer:
var columns = reader.GetSchemaTable().Rows
.Cast<DataRow>()
.Select(r => (string)r["ColumnName"])
.ToList();
//Or
var columns = Enumerable.Range(0, reader.FieldCount)
.Select(reader.GetName)
.ToList();
The second one is cleaner and much faster. Even if you cache GetSchemaTable
in the first approach, the querying is going to be very slow.
If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :
Create a 2 line script called zz.sh
#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
Currently, simply executing the script sends both STDOUT and STDERR to the screen.
./zz.sh
Now start with the standard redirection :
zz.sh > zfile.txt
In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.
The above is the same as :
zz.sh 1> zfile.txt
Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.
zz.sh 2> zfile.txt
Combining the above two, you get:
zz.sh 1> zfile.txt 2>&1
Explanation:
Eventually, you can pack the whole thing inside nohup command & to run it in the background:
nohup zz.sh 1> zfile.txt 2>&1&
In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.
A slight tweak on @CPU-100's answer, for the local FQDN:
[System.Net.DNS]::GetHostByName($Null).HostName
I wrote a library called capsLock which does exactly what you want it to do.
Just include it on your web pages:
<script src="https://rawgit.com/aaditmshah/capsLock/master/capsLock.js"></script>
Then use it as follows:
alert(capsLock.status);
capsLock.observe(function (status) {
alert(status);
});
See the demo: http://jsfiddle.net/3EXMd/
The status is updated when you press the Caps Lock key. It only uses the Shift key hack to determine the correct status of the Caps Lock key. Initially the status is false
. So beware.
I use this class:
public class JsonContent : StringContent
{
public JsonContent(object obj) :
base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
{ }
}
Sample of usage:
new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
Take a look QRCoder - pure C# open source QR code generator. Can be used in three lines of code
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(textBoxQRCode.Text, QRCodeGenerator.ECCLevel.Q);
pictureBoxQRCode.BackgroundImage = qrCode.GetGraphic(20);
this will work for u
$("#button-name").click(function(){
$('#toggle-id').slideToggle('slow');
});
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
If you have date object like
var date = new Date('2017/12/03');
then there is inbuilt method in javascript for getting date in milliseconds format which is valueOf()
date.valueOf(); //1512239400000 in milliseconds format
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);
fclose(f);
SELECT e.*,
cnt.colCount
FROM eventsTable e
INNER JOIN (
select columnName,count(columnName) as colCount
from eventsTable e2
group by columnName
) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'
-- Added space
PhpUnit is an amazing library, but this specific point is a bit frustrating. This is why we can use the turbotesting-php opensource library which has a very convenient assertion method to help us testing exceptions. It is found here:
And to use it, we would simply do the following:
AssertUtils::throwsException(function(){
// Some code that must throw an exception here
}, '/expected error message/');
If the code we type inside the anonymous function does not throw an exception, an exception will be thrown.
If the code we type inside the anonymous function throws an exception, but its message does not match the expected regexp, an exception will also be thrown.
Upload your favicon.ico
to the root directory of your website and that should work with Chrome. Some browsers disregard the meta tag and just use /favicon.ico
Go figure?.....
The conceptual difference in my understanding it that a project can contain many repo's and that are independent of each other, while simultaneously a repo may contain many projects. Repo's being just a storage place for code while a project being a collection of tasks for a certain feature.
Does that make sense? A large repo can have many projects being worked on by different people at the same time (lots of difference features being added to a monolith), a large project may have many small repos that are separate but part of the same project that interact with each other - microservices? Its a personal take on what you want to do. I think that repo (storage) vs project (tasks) is the main difference - if i am wrong please let me know / explain! Thanks.
Based on the answer: https://unix.stackexchange.com/a/111627
###############################################################################
# Summary: Returns the value of a variable given it's name as a string.
# Required Positional Argument:
# variable_name - The name of the variable to return the value of
# Returns: The value if variable exists; otherwise, empty string ("").
###############################################################################
get_value_of()
{
variable_name=$1
variable_value=""
if set | grep -q "^$variable_name="; then
eval variable_value="\$$variable_name"
fi
echo "$variable_value"
}
test=123
get_value_of test
# 123
test="\$(echo \"something nasty\")"
get_value_of test
# $(echo "something nasty")
According to http://caniuse.com/#feat=flexbox:
"IE10 and IE11 default values for flex
are 0 0 auto
rather than 0 1 auto
, as per the draft spec, as of September 2013"
So in plain words, if somewhere in your CSS you have something like this: flex:1
, that is not translated the same way in all browsers. Try changing it to 1 0 0
and I believe you will immediately see that it -kinda- works.
The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:
@-moz-document url-prefix() {
#flexible-content{
flex: 1;
}
}
Since flexbox
is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.
If someone has a better answer I would like to know!
Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:
insert into blob_fun values(1, hextoraw('453d7a34'));
453d7a34
is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.
The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.
Here is what I suggest instead:
Private Sub CommandButton2_Click()
Dim lItem As Long
For lItem = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(lItem) = True Then
MsgBox(ListBox1.List(lItem))
End If
Next
End Sub
Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
Go to Help → Install new software → Here uncheck “Contact all update sites during install to find required software”
Eclipse will prompt that the content isn't authorized or something like that. just ignore and continue. then everything will be OK.
At least this trick resolved my problems similar like this:
An error occurred while collecting items to be installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). No repository found containing: osgi.bundle,org.eclipse.emf,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ant,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen.ecore,2.8.1.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen.ecore.ui,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.codegen.ui,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.common,2.8.0.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.common.ui,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.converter,2.5.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.databinding,1.2.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.databinding.edit,1.2.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore,2.8.1.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.change,2.8.0.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.change.edit,2.5.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.edit,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.editor,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.ecore.xmi,2.8.0.v20120911-0500 No repository found containing: osgi.bundle,org.eclipse.emf.edit,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.edit.ui,2.8.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.exporter,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer.ecore,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer.java,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.importer.rose,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore.editor,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2ecore,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2ecore.editor,2.5.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2xml,2.7.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ecore2xml.ui,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.emf.mapping.ui,2.6.0.v20120917-0436 No repository found containing: osgi.bundle,org.eclipse.wst.common.project.facet.core,1.4.300.v201111030424 No repository found containing: osgi.bundle,org.eclipse.wst.common.project.facet.ui,1.4.300.v201111030424 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen.ecore,2.8.1.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen.ecore.ui,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.codegen.ui,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.common,2.8.0.v20120911-0500 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.common.ui,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.converter,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.databinding.edit,1.2.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.databinding,1.2.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.ecore.edit,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.ecore.editor,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.ecore,2.8.1.v20120911-0500 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.edit,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.edit.ui,2.8.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf,2.8.1.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping.ecore.editor,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping.ecore,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.emf.mapping.ui,2.7.0.v20120917-0436 No repository found containing: org.eclipse.update.feature,org.eclipse.wst.common.fproj,3.4.0.v201202292300-377F8N8s735555393B7B
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Try this I am also not 100 % sure
for( int i = 0 ;i< dt.Rows.Count; i++)
{
If(dt.Rows[i].Product_id == 2)
{
dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
}
}
We can pass string value to main method as argument without using commandline argument concept in java through Netbean
package MainClass;
import java.util.Scanner;
public class CmdLineArgDemo {
static{
Scanner readData = new Scanner(System.in);
System.out.println("Enter any string :");
String str = readData.nextLine();
String [] str1 = str.split(" ");
// System.out.println(str1.length);
CmdLineArgDemo.main(str1);
}
public static void main(String [] args){
for(int i = 0 ; i<args.length;i++) {
System.out.print(args[i]+" ");
}
}
}
Enter any string :
Coders invent Digital World
Coders invent Digital World
Look up: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html
From AuthenticationManagerConfiguration.java looking at code, I see below. Also the in-memory configuration is a fallback if no authentication manager is provided as per Javadoc. Your earlier attempt of Injecting the Authentication Manager would work because you will no longer be using the In-memory authentication and this class will be out of picture.
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
if (auth.isConfigured()) {
return;
}
User user = this.securityProperties.getUser();
if (user.isDefaultPassword()) {
logger.info("\n\nUsing default security password: " + user.getPassword()
+ "\n");
}
Set<String> roles = new LinkedHashSet<String>(user.getRole());
withUser(user.getName()).password(user.getPassword()).roles(
roles.toArray(new String[roles.size()]));
setField(auth, "defaultUserDetailsService", getUserDetailsService());
super.configure(auth);
}
If you use inmemory authentication which is default, customize your logger configuration for org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration and remove this message.
I ran into this same problem, but in my case, the only thing that had changed is that I had uninstalled Visual Studio 2012 and installed Visual Studio 2013. I opened up our solution, but I kept getting the same The name 'model' does not exist in current context
error in every Razor view.
My coworker suggested checking for updates for VS2013. After I installed the VS2013 Update 1, I stopped getting this error.
Use below code in viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view.layer setBorderWidth: 1.0];
[self.view.layer setCornerRadius:8.0f];
[self.view.layer setMasksToBounds:YES];
[self.view.layer setBorderColor:[[UIColor colorWithRed:251.0f/255.0f green:185.0f/255.0f blue:23.0f/255.0f alpha:1.0f]];`
}
this code set red color border to your view
Next release of ASP.NET MVC (available in January or so) should have MSBuild task that compiles views, so you might want to wait.
See announcement
If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }
:
$.ajax({
url: 'yourURL',
type: 'POST',
data: yourData,
xhrFields: { responseType: 'blob' },
success: function (data, textStatus, jqXHR) {
let src = window.URL.createObjectURL(data);
}
});
For verbose
> 0, fit
method logs:
Note: If regularization mechanisms are used, they are turned on to avoid overfitting.
if validation_data
or validation_split
arguments are not empty, fit
method logs:
Note: Regularization mechanisms are turned off at testing time because we are using all the capabilities of the network.
For example, using verbose
while training the model helps to detect overfitting which occurs if your acc
keeps improving while your val_acc
gets worse.
Try PowerPivot from Microsoft. Here you can find a step by step tutorial. It worked for my 4M+ rows!
That usually means a null is being posted to the query instead of your desired value, you might try to run the SQL Profiler to see exactly what is getting passed to SQL Server from linq.
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
unset
is a function, not an operator. Use it like unset($_SESSION['key']);
to unset that session key. You can, however, use session_destroy();
as well. (Make sure to start the session with session_start();
as well)
Debugging needs to be enabled on the target device in order for adb
to see it.
As your data already in varchar, you have to convert it into date first:
select convert(varchar(10), cast(ts as date), 101) from <your table>
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
CentOS 7 users can just use:
yum install python-pip
Also recommend using virtualenv
if you're using pip. It can be added in the same way:
yum install python-virtualenv
Read about Storage Engines.
MyISAM:
The MyISAM storage engine in MySQL.
InnoDB:
The InnoDB storage engine in MySQL.
MyISAM Limitations:
InnoDB Limitations:
ROW_FORMAT=COMPRESSED
)For brief understanding read below links:
top level class: internal
method: private
members (unless an interface or enum): private (including nested classes)
members (of interface or enum): public
constructor: private (note that if no constructor is explicitly defined, a public default constructor will be automatically defined)
delegate: internal
interface: internal
explicitly implemented interface member: public!
Here's the LLVM header.
// -*- C++ -*-
//===--------------------------- __nullptr --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_NULLPTR
#define _LIBCPP_NULLPTR
#include <__config>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifdef _LIBCPP_HAS_NO_NULLPTR
_LIBCPP_BEGIN_NAMESPACE_STD
struct _LIBCPP_TEMPLATE_VIS nullptr_t
{
void* __lx;
struct __nat {int __for_bool_;};
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t() : __lx(0) {}
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t(int __nat::*) : __lx(0) {}
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR operator int __nat::*() const {return 0;}
template <class _Tp>
_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
operator _Tp* () const {return 0;}
template <class _Tp, class _Up>
_LIBCPP_INLINE_VISIBILITY
operator _Tp _Up::* () const {return 0;}
friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator==(nullptr_t, nullptr_t) {return true;}
friend _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR bool operator!=(nullptr_t, nullptr_t) {return false;}
};
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR nullptr_t __get_nullptr_t() {return nullptr_t(0);}
#define nullptr _VSTD::__get_nullptr_t()
_LIBCPP_END_NAMESPACE_STD
#else // _LIBCPP_HAS_NO_NULLPTR
namespace std
{
typedef decltype(nullptr) nullptr_t;
}
#endif // _LIBCPP_HAS_NO_NULLPTR
#endif // _LIBCPP_NULLPTR
(a great deal can be uncovered with a quick grep -r /usr/include/*`
)
One thing that jumps out is the operator *
overload (returning 0 is a lot friendlier than segfaulting...).
Another thing is it doesn't look compatible with storing an address at all. Which, compared to how it goes slinging void*'s and passing NULL results to normal pointers as sentinel values, would obviously reduce the "never forget, it might be a bomb" factor.
If you want headless browser support then there is another approach you might adopt.
https://github.com/detro/ghostdriver
It was announced during Selenium Conference and it is still in development. It uses PhantomJS as the browser and is much better than HTMLUnitDriver, there are no screenshots yet, but as it is still in active development.
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
<div class="text-danger" style="direction:rtl" asp-validation-summary="All"></div>
_x000D_
simply use asp-validation-summary Tag Helper
BitmapFactory.decodeResource()
automatically scales the bitmap, so your bitmap may turn out fuzzy. To prevent scaling, do this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
R.drawable.resource_name, options);
or
InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
I just want to expand on queen3's suggestion, applying the following does the trick:
editoptions: {
dataInit: function(element) {
$(element).attr("readonly", "readonly");
}
}
Scenario #1:
Solution:
colModel:[
{ name:'providerUserId',
index:'providerUserId',
width:100,editable:true,
editrules:{required:true},
editoptions:{
dataInit: function(element) {
jq(element).attr("readonly", "readonly");
}
}
},
],
The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents.
Scenario #2:
Solution:
colModel:[
{name:'providerUserId',
index:'providerUserId',
width:100,editable:true,
editrules:{
required:true,
edithidden:true
},
hidden:true,
editoptions:{
dataInit: function(element) {
jq(element).attr("readonly", "readonly");
}
}
},
]
Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:
<script type="text/javascript">
var jq = jQuery.noConflict();
</script>
$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one
element.
I ended up with cleaning the project file (csproj) and the applicationhost.config (iis express) with all entries regarding iis express configuration. After that, it worked.
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
To develop the answer of @Caumons:
Imagine one father class has many children and there is a need to add a common field into that class. If you consider the mentioned approach, you should go to each children class one by one and refactor their constructors for the new field. therefore that solution is not a promising solution in this scenario
Now take a look at this solution.
A father can receive an self object from each children. Here is a father class:
public class Father {
protected String fatherField;
public Father(Father a){
fatherField = a.fatherField;
}
//Second constructor
public Father(String fatherField){
this.fatherField = fatherField;
}
//.... Other constructors + Getters and Setters for the Fields
}
Here is our child class that should implement one of its father constructor, in this case the aforementioned constructor :
public class Child extends Father {
protected String childField;
public Child(Father father, String childField ) {
super(father);
this.childField = childField;
}
//.... Other constructors + Getters and Setters for the Fields
@Override
public String toString() {
return String.format("Father Field is: %s\nChild Field is: %s", fatherField, childField);
}
}
Now we test out application:
public class Test {
public static void main(String[] args) {
Father fatherObj = new Father("Father String");
Child child = new Child(fatherObj, "Child String");
System.out.println(child);
}
}
And here is the result :
Father Field is: Father String
Child Field is: Child String
Now you can easily add new fields to father class without being worried of your children codes to break;
Below code will read excel data into a datatable, which is converted to list of datarows.
if (FileUpload1.HasFile)
{
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
Stream fs = FileUpload1.FileContent;
ExcelPackage package = new ExcelPackage(fs);
DataTable dt = new DataTable();
dt= package.ToDataTable();
List<DataRow> listOfRows = new List<DataRow>();
listOfRows = dt.AsEnumerable().ToList();
}
}
using OfficeOpenXml;
using System.Data;
using System.Linq;
public static class ExcelPackageExtensions
{
public static DataTable ToDataTable(this ExcelPackage package)
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
DataTable table = new DataTable();
foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
{
table.Columns.Add(firstRowCell.Text);
}
for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
{
var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
var newRow = table.NewRow();
foreach (var cell in row)
{
newRow[cell.Start.Column - 1] = cell.Text;
}
table.Rows.Add(newRow);
}
return table;
}
}
I just saw this test:
bool getFileExists(const TCHAR *file)
{
return (GetFileAttributes(file) != 0xFFFFFFFF);
}
I found an easier way to go about this nagging problem. Register GlassFish Server without setting user/password the first time. Then right click GlassFish then to View Domain Admin Console. On the Glassfish admin page that appears, you will see Change Administrator Password under Administration on the GlassFish Console- Common Tasks. Click to set your password by changing the default password. The user is admin but the password is up to you to change it. Save your change. Go back to Netbeans and you will immediately see a popout screen asking you to enter your admin credentials. Enter admin for user and the password. That is it. If your Netbeans come with Glassfish, just right click the server then to View Domain Admin Console then follow the rest of the steps explained above
Here is an alternate syntax I use:
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = (
SELECT id_teacher
FROM tab_teacher
WHERE name_teacher = 'Dr. Smith')
I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department
and expenses
tables from the following:
Luckily, MySQL supports LAST_INSERT_ID()
exactly for this purpose.
INSERT INTO tab_teacher
SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = LAST_INSERT_ID()
At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.
The following groovy snippet should pass the version (as you've already supplied), and store it in the job's variables as 'miniVersion'.
import hudson.model.*
def env = System.getenv()
def version = env['currentversion']
def m = version =~/\d{1,2}/
def minVerVal = m[0]+"."+m[1]
def pa = new ParametersAction([
new StringParameterValue("miniVersion", minVerVal)
])
// add variable to current job
Thread.currentThread().executable.addAction(pa)
The variable will then be accessible from other build steps. e.g.
echo miniVersion=%miniVersion%
Outputs:
miniVersion=12.34
I believe you'll need to use the "System Groovy Script" (on the Master node only) as opposed to the "Groovy Plugin" - https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin#Groovyplugin-GroovyScriptvsSystemGroovyScript
I believe the previous (Jenkins 1.x) behaviour stopped working because of this Security Advisory...
It's possible to restore the previous behaviour by setting the system property hudson.model.ParametersAction.keepUndefinedParameters
to true
. This is potentially very unsafe and intended as a short-term workaround only.
java -Dhudson.model.ParametersAction.keepUndefinedParameters=true -jar jenkins.war
To allow specific, known safe parameter names to be passed to builds, set the system property hudson.model.ParametersAction.safeParameters
to a comma-separated list of safe parameter names.
e.g.
java -Dhudson.model.ParametersAction.safeParameters=miniVersion,FOO,BAR -jar jenkins.war
I saw a case where Chrome had installed WidgetBlock which was blocking the Facebook script. The result was exactly this error message. Make sure you disable any extensions that may interfere.
Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.
Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.
As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:
Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.
Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:
meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)
Formula is from Chris Broadfoot's comment.
Google Maps basics
Zoom Level - zoom
0 - 19
0 lowest zoom (whole world)
19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()
What you're looking for are the scales for each zoom level. Use these:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
Here's a solution using a negative lookahead (not supported in all regex engines):
^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$
Test that it works as expected:
import re
tests = [
('a', True),
('_', False),
('zz', True),
('a0', True),
('A_', False),
('a0_b', True),
('a__b', False),
('a_1_c', True),
]
regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
is_match = re.match(regex, test[0]) is not None
if is_match != test[1]:
print "fail: " + test[0]
From the console in Chrome, you can do console.log(data_to_be_displayed)
.
Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.
The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters -¦
instead of a degree °
.
Demonstration (using python 2.7 in a windows console):
deg = u'\xb0` # utf code for degree
print deg.encode('utf8')
effectively outputs -¦
.
Fix: just force the correct encoding (or better use unicode):
local_encoding = 'cp850' # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg
or if you use a source file that explicitely defines an encoding:
# -*- coding: utf-8 -*-
local_encoding = 'cp850' # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)
If you use PHP7, use Throwable in catch
for catching user exceptions and fatal errors.
For example:
DB::beginTransaction();
try {
DB::insert(...);
DB::commit();
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
If your code must be compartable with PHP5, use Exception
and Throwable
:
DB::beginTransaction();
try {
DB::insert(...);
DB::commit();
} catch (\Exception $e) {
DB::rollback();
throw $e;
} catch (\Throwable $e) {
DB::rollback();
throw $e;
}
Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link
Youtube video about entire process.
Writeup with pictures about installing SQL Server
How to select a local server:
When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:
1) Make sure you have Server Type: Database
2) Make sure you have Authentication: Windows Authentication (no username & password)
3) For the server name field look to the right and select the drop down arrow, click 'browse for more'
4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14
How do I create a local database inside of Microsoft SQL Server 2014?
1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)
2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!
You can do it via the constructor of your class:
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.
I hope it will help someone ! (works on Angular 6)
I had to add lots of select/options dynamically and following worked for me:
<div *ngFor="let option of model.q_options; let ind=index;">
<select
[(ngModel)]="model.q_options[ind].type"
[ngModelOptions]="{standalone: true}"
>
<option
*ngFor="let object of objects"
[ngValue]="object.type"
[selected]="object.type === model.q_options[ind].type"
>{{object.name}}
</option>
</select>
<div [ngSwitch]="model.q_options[ind].type">
( here <div *ngSwitchCase="'text' or 'imagelocal' or etc."> is used to add specific input forms )
</div>
</div>
and in *.ts
// initial state of the model
// q_options in html = NewOption and its second argument is option type
model = new NewQuestion(1, null, 2,
[
new NewOption(0, 'text', '', 1),
new NewOption(1, 'imagelocal', '', 1)
]);
// dropdown options
objects = [
{type: 'text', name: 'text'},
{type: 'imagelocal', name: 'image - local file'},
{type: 'imageurl', name: 'image URL'}
( and etc.)
];
When user adds one more 'input option' (pls do not confuse 'input option' with select/options - select/options are static here) specific select/option, selected by the user earlier, is preserved on each/all dynamically added 'input option's select/options.
The below query helps to get the row number in oracle,
SELECT ROWNUM AS SNO,ID,NAME,EMAIL,BRANCH FROM student WHERE NAME LIKE '%ram%';
The answer is something like:
t_start = Time.now
# time-consuming operation
t_end = Time.now
milliseconds = (t_start - t_end) * 1000.0
However, the Time.now
approach risks to be inaccurate. I found this post by Luca Guidi:
https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/
system clock is constantly floating and it doesn't move only forwards. If your calculation of elapsed time is based on it, you're very likely to run into calculation errors or even outages.
So, it is recommended to use Process.clock_gettime
instead. Something like:
def measure_time
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
yield
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
elapsed_time = end_time - start_time
elapsed_time.round(3)
end
Example:
elapsed = measure_time do
# your time-consuming task here:
sleep 2.2321
end
=> 2.232
You can better understand what Looper is in the context of GUI framework. Looper is made to do 2 things.
1) Looper transforms a normal thread, which terminates when its run() method return, into something run continuously until Android app is running, which is needed in GUI framework (Technically, it still terminates when run() method return. But let me clarify what I mean in below).
2) Looper provides a queue where jobs to be done are enqueued, which is also needed in GUI framework.
As you may know, when an application is launched, the system creates a thread of execution for the application, called “main”, and Android applications normally run entirely on a single thread by default the “main thread”. But main thread is not some secret, special thread. It's just a normal thread similar to threads you create with new Thread()
code, which means it terminates when its run() method return! Think of below example.
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Now, let's apply this simple principle to Android apps. What would happen if an Android app runs on normal thread? A thread called "main" or "UI" or whatever starts your application, and draws all UI. So, the first screen is displayed to users. So what now? The main thread terminates? No, it shouldn’t. It should wait until users do something, right? But how can we achieve this behavior? Well, we can try with Object.wait()
or Thread.sleep()
. For example, main thread finishes its initial job to display first screen, and sleeps. It awakes, which means interrupted, when a new job to do is fetched. So far so good, but at this moment we need a queue-like data structure to hold multiple jobs. Think about a case when a user touches screen serially, and a task takes longer time to finish. So, we need to have a data structure to hold jobs to be done in first-in-first-out manner. Also, you may imagine, implementing ever-running-and-process-job-when-arrived thread using interrupt is not easy, and leads to complex and often unmaintainable code. We'd rather create a new mechanism for such purpose, and that is what Looper is all about. The official document of Looper class says, "Threads by default do not have a message loop associated with them", and Looper is a class "used to run a message loop for a thread". Now you can understand what it means.
To make things more clear, let's check the code where main thread is transformed. It all happens in ActivityThread class. In its main() method, you can find below code, which turns a normal main thread into something what we need.
public final class ActivityThread {
...
public static void main(String[] args) {
...
Looper.prepareMainLooper();
Looper.loop();
...
}
}
and Looper.loop()
method loop infinitely and dequeue a message and process one at a time:
public static void loop() {
...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
msg.target.dispatchMessage(msg);
...
}
}
So, basically Looper is a class that is made to address a problem that occurs in GUI framework. But this kind of needs can also happen in other situation as well. Actually it is a pretty famous pattern for multi threads application, and you can learn more about it in "Concurrent Programming in Java" by Doug Lea(Especially, chapter 4.1.4 "Worker Threads" would be helpful). Also, you can imagine this kind of mechanism is not unique in Android framework, but all GUI framework may need somewhat similar to this. You can find almost same mechanism in Java Swing framework.
Basing on your solutions I've made some trick:
When you use it, your HTML will be only
<div data-keep-ratio="75%">
<div>Main content</div>
</div>
To use it this way make: CSS:
*[data-keep-ratio] {
display: block;
width: 100%;
position: relative;
}
*[data-keep-ratio] > * {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
and js (jQuery)
$('*[data-keep-ratio]').each(function(){
var ratio = $(this).data('keep-ratio');
$(this).css('padding-bottom', ratio);
});
And having this you just set attr data-keep-ratio
to height/width and that's it.
It seems that you are asking multiple things. To answer them:
You can extract the numbers by catching them in capturing parentheses:
.*(\d+) rofl.*
and using $1
to get the string out (.*
is for "the rest before and after on the same line)
With sed as example, the idea becomes this to replace all strings in a file with only the matching number:
sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName
or:
echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'
Another option is to ensure the file is not open anywhere else on your machine.
If working with Python =2.6 (including 3.x), you can:
from __future__ import division
import operator, itertools
def getmin(alist):
return min(
(operator.div(*pair), pair)
for pair in itertools.product(alist, repeat=2)
)[1]
getmin([1, 2, 3, 4, 5])
EDIT: Now that I think of it and if I remember my mathematics correctly, this should also give the answer assuming that all numbers are non-negative:
def getmin(alist):
return min(alist), max(alist)
I'm going to approach this as if you have a Users model:
Users.cs
public class Users
{
[Key]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual DbUserRoles DbUserRoles { get; set; }
}
and a DbUserRoles model that represented a table by that name in the database:
DbUserRoles.cs
public partial class DbUserRoles
{
[Key]
public int UserRoleId { get; set; }
[Required]
[StringLength(30)]
public string UserRole { get; set; }
}
Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:
var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;
and have these supporting functions:
private static SelectListItem[] _UserRolesList;
/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
if (_UserRolesList == null)
{
var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
{
Text = a.UserRole,
Value = a.UserRoleId.ToString()
}).ToList();
userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });
_UserRolesList = userRoles.ToArray();
}
// Have to create new instances via projection
// to avoid ModelBinding updates to affect this
// globally
return _UserRolesList
.Select(d => new SelectListItem()
{
Value = d.Value,
Text = d.Text
})
.ToArray();
}
Repository.cs
My Repository function GetAllUserRoles()
for the function, above:
public class Repository
{
Model1 db = new Model1(); // Entity Framework context
// User Roles
public IList<DbUserRoles> GetAllUserRoles()
{
return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
}
}
AddNewUser.cshtml
Then do this in your View:
<table>
<tr>
<td>
@Html.EditorFor(model => model.UserName,
htmlAttributes: new { @class = "form-control" }
)
</td>
<td>
@Html.DropDownListFor(model => model.RoleId,
new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
htmlAttributes: new { @class = "form-control" }
)
</td>
</tr>
</table>
I don't know which steps worked for me. But these are my steps to get rid of this error:
console.log()
in java is System.out.println();
to put text on the next line
And System.out.print();
puts text on the same line.
This is from the cplusplus forum
On windows:
#include <string>
#include <windows.h>
std::string getexepath()
{
char result[ MAX_PATH ];
return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
}
On Linux:
#include <string>
#include <limits.h>
#include <unistd.h>
std::string getexepath()
{
char result[ PATH_MAX ];
ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
return std::string( result, (count > 0) ? count : 0 );
}
On HP-UX:
#include <string>
#include <limits.h>
#define _PSTAT64
#include <sys/pstat.h>
#include <sys/types.h>
#include <unistd.h>
std::string getexepath()
{
char result[ PATH_MAX ];
struct pst_status ps;
if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)
return std::string();
if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)
return std::string();
return std::string( result );
}
Relying on the compiler vendor's implementation of primitive type sizes WILL come back to haunt you if you ever compile your code on another machine architecture, OS, or another vendor's compiler .
Most compiler vendors provide a header file that defines primitive types with
explict type sizes.
These primitive types should be used when ever code may be potentially ported
to another compiler (read this as ALWAYS in EVERY instance).
For example, most UNIX compilers have int8_t uint8_t int16_t int32_t uint32_t
.
Microsoft has INT8 UINT8 INT16 UINT16 INT32 UINT32
.
I prefer Borland/CodeGear's int8 uint8 int16 uint16 int32 uint32
.
These names also give a little reminder of the size/range of the intended value.
For years I have used Borland's explicit primitive type names
and #include
the following C/C++ header file (primitive.h)
which is intended to define the explicit primitive types with these names for any C/C++ compiler
(this header file might not actually cover every compiler but it covers several compilers I have used on Windows, UNIX and Linux, it also doesn't (yet) define 64bit types).
#ifndef primitiveH
#define primitiveH
// Header file primitive.h
// Primitive types
// For C and/or C++
// This header file is intended to define a set of primitive types
// that will always be the same number bytes on any operating operating systems
// and/or for several popular C/C++ compiler vendors.
// Currently the type definitions cover:
// Windows (16 or 32 bit)
// Linux
// UNIX (HP/US, Solaris)
// And the following compiler vendors
// Microsoft, Borland/Imprise/CodeGear, SunStudio, HP/UX
// (maybe GNU C/C++)
// This does not currently include 64bit primitives.
#define float64 double
#define float32 float
// Some old C++ compilers didn't have bool type
// If your compiler does not have bool then add emulate_bool
// to your command line -D option or defined macros.
#ifdef emulate_bool
# ifdef TVISION
# define bool int
# define true 1
# define false 0
# else
# ifdef __BCPLUSPLUS__
//BC++ bool type not available until 5.0
# define BI_NO_BOOL
# include <classlib/defs.h>
# else
# define bool int
# define true 1
# define false 0
# endif
# endif
#endif
#ifdef __BCPLUSPLUS__
# include <systypes.h>
#else
# ifdef unix
# ifdef hpux
# include <sys/_inttypes.h>
# endif
# ifdef sun
# include <sys/int_types.h>
# endif
# ifdef linux
# include <idna.h>
# endif
# define int8 int8_t
# define uint8 uint8_t
# define int16 int16_t
# define int32 int32_t
# define uint16 uint16_t
# define uint32 uint32_t
# else
# ifdef _MSC_VER
# include <BaseTSD.h>
# define int8 INT8
# define uint8 UINT8
# define int16 INT16
# define int32 INT32
# define uint16 UINT16
# define uint32 UINT32
# else
# ifndef OWL6
// OWL version 6 already defines these types
# define int8 char
# define uint8 unsigned char
# ifdef __WIN32_
# define int16 short int
# define int32 long
# define uint16 unsigned short int
# define uint32 unsigned long
# else
# define int16 int
# define int32 long
# define uint16 unsigned int
# define uint32 unsigned long
# endif
# endif
# endif
# endif
#endif
typedef int8 sint8;
typedef int16 sint16;
typedef int32 sint32;
typedef uint8 nat8;
typedef uint16 nat16;
typedef uint32 nat32;
typedef const char * cASCIIz; // constant null terminated char array
typedef char * ASCIIz; // null terminated char array
#endif
//primitive.h
I have the same error, make some change in the path C:\Users\Juan Jose\App---- to C:\Users\JUAN~1\App.
Try SELECT CAST(field1 AS DECIMAL(10,2)) field1
and replace 10,2
with whatever precision you need.
There can be various scenarios as people have mentioned above. A couple of things which have helped me resolve this.
If you are using IntelliJ
File -> 'Invalidate Caches/Restart'
OR
The class being referenced was in another project and that dependency was not added to the Gradle build file of my project. So I added the dependency using
compile project(':anotherProject')
and it worked. HTH!
Found this on HTML table: keep the same width for columns
If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .
Normally setting axis limit @ max of your variable is enough
a <- c(0:1000000)
b <- c(0:1000000)
plot(a, b, ylim = c(0, max(b)))
When you are running a python script on windows in subprocess you should use python in front of the script name. Try:
process = subprocess.Popen("python /the/script.py")
I had the exact same error but in my case, the problem was the result of having rebuilt Apache after an upgrade to the PHP version. Long story short, I forgot to install the Apache module 'suexec'.
It had nothing to do with group or ownership. That only took me two days to figure out, someone shoot me...
From what i can see in your logs you posted:
npm ERR! code: 'EACCES',
npm ERR! syscall: 'mkdir',
npm ERR! path: '/home/rupesh/node_modules/lodash',
npm ERR! fstream_type: 'Directory',
npm ERR! fstream_path: '/home/rupesh/node_modules/lodash',
npm ERR! fstream_class: 'DirWriter',
directory /home/rupesh/node_modules/
doesn't have necessary permissions to create directory so run chown -r rupesh:rupesh /home/rupesh/node_modules/
this should solve it.
You can make a template function, and pass the array by reference to achieve this.
Here is my code snippet
template <typename TypeOfData>
void PrintArray(TypeOfData &arrayOfType);
int main()
{
char charArray[] = "my name is";
int intArray[] = { 1,2,3,4,5,6 };
double doubleArray[] = { 1.1,2.2,3.3 };
PrintArray(charArray);
PrintArray(intArray);
PrintArray(doubleArray);
}
template <typename TypeOfData>
void PrintArray(TypeOfData &arrayOfType)
{
int elementsCount = sizeof(arrayOfType) / sizeof(arrayOfType[0]);
for (int i = 0; i < elementsCount; i++)
{
cout << "Value in elements at position " << i + 1 << " is " << arrayOfType[i] << endl;
}
}
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
Apart from "readability", no. They're functionally equivalent.
("Readability" is in quotes because I hate == false
and find !
much more readable. But others don't.)
If you want to prevent your script failing and collect the return code:
command () {
return 1 # or 0 for success
}
set -e
command && returncode=$? || returncode=$?
echo $returncode
returncode
is collected no matter whether command succeeds or fails.
This question has already great answers, but here it appears that there is a slight confusion between using single equal (=
) and double equals (==
) in
if [ "$s1" == "$s2" ]
The main difference lies in which scripting language you are using. If you are using Bash then include #!/bin/bash
in the starting of the script and save your script as filename.bash
. To execute, use bash filename.bash
- then you have to use ==
.
If you are using sh then use #!/bin/sh
and save your script as filename.sh
. To execute use sh filename.sh
- then you have to use single =
. Avoid intermixing them.
The solution is isblank(cell)=false
This is the code I usually do:
try
{
...........
throw null;//this line just works like a 'break'
...........
}
catch (NullReferenceException)
{
}
catch (System.Exception ex)
{
.........
}
This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv
, and this javascript snippet will expand that div until the page takes up the full height of the browser window.
It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv
until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv
will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv
by one pixel to make the page height exactly the height of the browser window.
By placing footerspacerdiv
just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.
<script>
//expand footerspacer div so that footer goes to bottom of page on short pages
var objSpacerDiv=document.getElementById('footerspacer');
var bresize=0;
while(document.body.scrollHeight<=document.body.clientHeight) {
objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
bresize=1;
}
if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }
</script>
I recommend GPick:
sudo apt-get install gpick
Applications -> Graphics -> GPick
It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.
If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.
It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10
here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt
.
My experience with this is that getTextBounds
will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText
assumes one line.
In order to get accurate measuring results, you should use the StaticLayout
to render the text and pull out the measurements.
For example:
String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;
StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();
For those who like terse code.
private static final Set<Class> WRAPPER_TYPES = new HashSet(Arrays.asList(
Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class));
public static boolean isWrapperType(Class clazz) {
return WRAPPER_TYPES.contains(clazz);
}
Pass by value, except when
const
reference,const
lvalue reference,const
reference or not.)Passing by pointer is virtually never advised. Optional parameters are best expressed as a std::optional
(boost::optional
for older std libs), and aliasing is done fine by reference.
C++11's move semantics make passing and returning by value much more attractive even for complex objects.
Pass arguments by const
reference, except when
const
referenceNULL
/0
/nullptr
instead; apply the previous rule to determine whether you should pass by a pointer to a const
argument(here, "pass by value" is called "pass by copy", because passing by value always creates a copy in C++03)
There's more to this, but these few beginner's rules will get you quite far.
In order for you to modify test1
while inside a function you will need to do define test1
as a global variable, for example:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
However, if you only need to read the global variable you can print it without using the keyword global
, like so:
test1 = 0
def testFunc():
print test1
testFunc()
But whenever you need to modify a global variable you must use the keyword global
.
Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as:
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
Read below for legacy browser support.
The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.
The window.onbeforeunload
is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to onbeforeunload
(including a function that returns null
).
You set window.onbeforeunload
to a function reference, but in older browsers you have to set the returnValue
of the event instead of just returning a string:
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
You can't have that confirmOnPageExit
do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off:
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
To turn it on:
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
For completeness' sake, here's the way to do it with arrow
(better dates and times for Python):
sometime = arrow.now()
abitlater = sometime.shift(seconds=3)
SELECT @LastChangeDate = GETDATE()
INT_MAX
is just a definition in limits.h. You don't make it clear whether you need to store an integer or floating point value. If integer, and using a 64-bit compiler, use a LONG
(LLONG
for 32-bit).
Use a UIWebView on iOS 5-.
On iOS 6+ you can use UITextView.attributedString
, see https://stackoverflow.com/a/20996085 for how.
There's also an undocumented -[UITextView setContentToHTMLString:]
method. Do not use this if you want to submit to AppStore.
People use it because they're inherently lazy when building dynamic SQL queries. If you start with a "where 1 = 1"
then all your extra clauses just start with "and"
and you don't have to figure out.
Not that there's anything wrong with being inherently lazy. I've seen doubly-linked lists where an "empty" list consists of two sentinel nodes and you start processing at the first->next
up until last->prev
inclusive.
This actually removed all the special handling code for deleting first
and last
nodes. In this set-up, every node was a middle node since you weren't able to delete first
or last
. Two nodes were wasted but the code was simpler and (ever so slightly) faster.
The only other place I've ever seen the "1 = 1" construct is in BIRT. Reports often use positional parameters and are modified with Javascript to allow all values. So the query:
select * from tbl where col = ?
when the user selects "*"
for the parameter being used for col
is modified to read:
select * from tbl where ((col = ?) or (1 = 1))
This allows the new query to be used without fiddling around with the positional parameter details. There's still exactly one such parameter. Any decent DBMS (e.g., DB2/z) will optimize that query to basically remove the clause entirely before trying to construct an execution plan, so there's no trade-off.
As wizzard pointed out, the correct method is,
new Date().getTime();
or under Javascript 1.5, just
Date.now();
From the documentation,
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
If you wanted to make a time stamp without milliseconds you can use,
Math.floor(Date.now() / 1000);
I wanted to make this an answer so the correct method is more visible.
You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s
on a Unix terminal.
Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:
>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0 0.41
1 0.99
2 0.10
or
>>> pd.set_option('display.float_format', '{:.2f}'.format)
If you're actually doing it just because you want to get the user's timezone then all you have to do is change your timezone in you config/applications.rb
.
Like this:
Rails, by default, will save your time record in UTC even if you specify the current timezone.
config.time_zone = "Singapore"
So this is all you have to do and you're good to go.
if you're using React I found 'react-moment'
library more easy to handle for Front-End related tasks, just import <Moment>
component and add unix
prop:
import Moment from 'react-moment'
// get date variable
const {date} = this.props
<Moment unix>{date}</Moment>
Install ipynb from your command prompt
pip install import-ipynb
Import in your notebook file
import import_ipynb
Now use regular import command to import your file
import MyOtherNotebook
Resize the bitmap using the following code
public static Bitmap decodeFile(File file, int reqWidth, int reqHeight){
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file.getPath(), options);
}
private static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
The same is also explained in the following tip/trick
http://www.codeproject.com/Tips/625810/Android-Image-Operations-Using-BitmapFactory
Basic method
$query = parse_url($url, PHP_URL_QUERY);
// Returns a string if the URL has parameters or NULL if not
if ($query) {
$url .= '&category=1';
} else {
$url .= '?category=1';
}
More advanced
$url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';
$url_parts = parse_url($url);
// If URL doesn't have a query string.
if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
parse_str($url_parts['query'], $params);
} else {
$params = array();
}
$params['category'] = 2; // Overwrite if exists
$params['tags'][] = 'cool'; // Allows multiple values
// Note that this will url_encode all values
$url_parts['query'] = http_build_query($params);
// If you have pecl_http
echo http_build_url($url_parts);
// If not
echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];
You should put this in a function at least, if not a class.
I was in a predicament where I had a signed byte array (sbyte[]
) as input to a Test class and I wanted to replace it with a normal byte array (byte[]
) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.
I wrote a helper method to print out the initializer of a given byte[]
:
public void PrintByteArray(byte[] bytes)
{
var sb = new StringBuilder("new byte[] { ");
foreach (var b in bytes)
{
sb.Append(b + ", ");
}
sb.Append("}");
Console.WriteLine(sb.ToString());
}
You can use it like this:
var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }
The ouput is valid C# which can then just be copied into your code.
And just for completeness, here is the UnsignedBytesFromSignedBytes
method:
// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
var unsigned = new byte[signed.Length];
Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
return unsigned;
}
I would like share an example to understand the usage of stream().filter
Code Snippet: Sample program to identify even number.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public void fetchEvenNumber(){
List<Integer> numberList = new ArrayList<>();
numberList.add(10);
numberList.add(11);
numberList.add(12);
numberList.add(13);
numberList.add(14);
numberList.add(15);
List<Integer> evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());
System.out.println(evenNumberListObj);
}
Output will be : [10, 12, 14]
List evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());
numberList: it is an ArrayList object contains list of numbers.
java.util.Collection.stream() : stream() will get the stream of collection, which will return the Stream of Integer.
filter: Returns a stream that match the given predicate. i.e based on given condition (i -> i%2 != 0) returns the matching stream.
collect: whatever the stream of Integer filter based in the filter condition, those integer will be put in a list.
Below is made by purely MUI Grid system,
With the code below,
// MuiGrid.js
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
paper: {
padding: theme.spacing(2),
textAlign: "center",
color: theme.palette.text.secondary,
backgroundColor: "#b5b5b5",
margin: "10px"
}
}));
export default function FullWidthGrid() {
const classes = useStyles();
return (
<div className={classes.root}>
<Grid container spacing={0}>
<Grid item xs={12}>
<Paper className={classes.paper}>xs=12</Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}>xs=12 sm=6</Paper>
</Grid>
<Grid item xs={12} sm={6}>
<Paper className={classes.paper}>xs=12 sm=6</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper className={classes.paper}>xs=6 sm=3</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper className={classes.paper}>xs=6 sm=3</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper className={classes.paper}>xs=6 sm=3</Paper>
</Grid>
<Grid item xs={6} sm={3}>
<Paper className={classes.paper}>xs=6 sm=3</Paper>
</Grid>
</Grid>
</div>
);
}
↓ CodeSandbox ↓
You can use a 'here' document with no command to send it to.
#!/bin/bash
echo "Say Something"
<<COMMENT1
your comment 1
comment 2
blah
COMMENT1
echo "Do something else"
$property_images = $_FILES['property_images']['name'];
if(!empty($property_images))
{
for($up=0;$up<count($property_images);$up++)
{
move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
}
}
Whenever you will face below error just follow it.
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
Put a @Transactional
annotation for each method of implementing classes.
Click the database symbol with the plus sign (shown in the below picture). Enter a name and click Apply
.
This worked in MySQL Workbench 6.0
You can check with this command systemctl status docker
it will show the status of the docker. If you want to start you can use systemctl start docker
instead of systemctl
you can try also with service
, service docker status
and service docker start
respectively.
In Visual Studio 2019- Tools > Command Line > Developer Command Prompt.enter image description here
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
Today I had the same error while installing an app to my device. The problem occurred after I updated to the new xCode 11.4.
What I did to fix the issue:
I combined a few answers given by others in this question to come up with another alternative solution.
Goal: To always bundle the files, to disable the JS and CSS minification in the event that <compilation debug="true" ... />
and to always apply a custom transformation to the CSS bundle.
My solution:
1) In web.config:
<compilation debug="true" ... />
2) In the Global.asax Application_Start() method:
protected void Application_Start() {
...
BundleTable.EnableOptimizations = true; // Force bundling to occur
// If the compilation node in web.config indicates debugging mode is enabled
// then clear all transforms. I.e. disable Js and CSS minification.
if (HttpContext.Current.IsDebuggingEnabled) {
BundleTable.Bundles.ToList().ForEach(b => b.Transforms.Clear());
}
// Add a custom CSS bundle transformer. In my case the transformer replaces a
// token in the CSS file with an AppConfig value representing the website URL
// in the current environment. E.g. www.mydevwebsite in Dev and
// www.myprodwebsite.com in Production.
BundleTable.Bundles.ToList()
.FindAll(x => x.GetType() == typeof(StyleBundle))
.ForEach(b => b.Transforms.Add(new MyStyleBundleTransformer()));
...
}
This is what I used to accomplish to this:
System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");
"mondate"
is somewhat similar to "Date"
except that adding n
adds n
months rather than n
days:
> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29
I suggest to use a container for each img
p
like this:
<div class="image123">
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif" height="200" width="200" />
<p style="text-align:center;">This is image 1</p>
</div>
<div style="float:left;margin-right:5px;">
<img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 2</p>
</div>
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 3</p>
</div>
</div>
Then apply float:left
to each container. I add and 5px
margin right
so there is a space between each image. Also alway close your elements. Maybe in html img
tag is not important to close but in XHTML is.
Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:
html
<div class="image123">
<div>
<img src="/images/tv.gif" />
<p>This is image 1</p>
</div>
<div>
<img class="middle-img" src="/images/tv.gif/" />
<p>This is image 2</p>
</div>
<div>
<img src="/images/tv.gif/" />
<p>This is image 3</p>
</div>
</div>
css
div{
float:left;
margin-right:5px;
}
div > img{
height:200px;
width:200px;
}
p{
text-align:center;
}
It's generally recommended that you use linked style sheets because:
For those searching for a solution not based on jQuery, this is a plain JavaScript version of the solution provided by Thomas M:
window.addEventListener("storage", message_receive);
function message_broadcast(message) {
localStorage.setItem('message',JSON.stringify(message));
}
function message_receive(ev) {
if (ev.key == 'message') {
var message=JSON.parse(ev.newValue);
}
}
Just adding a little more info.
JPA manages the version under the hood for you, however it doesn't do so when you update your record via JPAUpdateClause
, in such cases you need to manually add the version increment to the query.
Same can be said about updating via JPQL, i.e. not a simple change to the entity, but an update command to the database even if that is done by hibernate
Pedro
Do C-b
, :show
which will show you all your current settings. /green
, nnn
will find you which properties have been set to green, the default. Do C-b
, :set window-status-bg cyan
and the bottom bar should change colour.
List available colours for tmux
You can tell more easily by the titles and the colours as they're actually set in your live session :show
, than by searching through the man
page, in my opinion. It is a very well-written man
page when you have the time though.
If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf
with a line like set window-status-bg -g cyan
. Here's mine: https://gist.github.com/9083598
Here's a slightly different way:
SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LEN(ISNULL(PropertyValue,'')) = 0)
One way to fix it is by modifying the assembly redirect in the web.config file.
Modify the following:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
to
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="4.0.0.0" />
</dependentAssembly>
So the oldVersion attribute should change from "...-4.0.0.0" to "...-5.2.3.0".
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
strstr(request, "favicon") != NULL
I guess this is because your nodejs cert has expired. Type this line : npm set registry http://registry.npmjs.org/
and after that try again with npm install . This actually solved my problem.
I was working in Wildfly but I was using
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
and the correct was
org.hibernate.Session session = (Session) manager.getDelegate();
If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. 
);.
function showCursPos(){
selection = document.getSelection();
childOffset = selection.focusOffset;
const range = document.createRange();
eDiv = document.getElementById("eDiv");
range.setStart(eDiv, 0);
range.setEnd(selection.focusNode, childOffset);
var sHtml = range.toString();
p = sHtml.length;
sHtml=sHtml.replace(/(\r)/gm, "\\r");
sHtml=sHtml.replace(/(\n)/gm, "\\n");
document.getElementById("caretPosHtml").value=p;
document.getElementById("exHtml").value=sHtml;
}
_x000D_
click/type in div below:
<br>
<div contenteditable name="eDiv" id="eDiv"
onkeyup="showCursPos()" onclick="showCursPos()"
style="width: 10em; border: 1px solid; display:inline-block; white-space: pre-wrap; "
>123 456 789</div>
<p>
html caret position:<br> <input type="text" id="caretPosHtml">
<p>
html from start of div:<br> <input type="text" id="exHtml">
_x000D_
What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).
'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'
For example, if val
is "10"
then this will end up building the string:
"SELECT * FROM Employ where number = 10;"
The best and easiest way to clear a JLIST is:
myJlist.setListData(new String[0]);
I use icons next to text 99% of the time so I made the change globally:
.fa-2x {
vertical-align: middle;
}
Add 3x, 4x, etc to the same definition as needed.
After looking at pip's code for a while, it looks like the code responsible for locating packages can be found in the PackageFinder
class in pip.index
. Its method find_requirement
looks up the versions of a InstallRequirement
, but unfortunately only returns the most recent version.
The code below is almost a 1:1 copy of the original function, with the return in line 114 changed to return all versions.
The script expects one package name as first and only argument and returns all versions.
I can't guarantee for the correctness, as I'm not familiar with pip's code. But hopefully this helps.
Sample output
python test.py pip
Versions of pip
0.8.2
0.8.1
0.8
0.7.2
0.7.1
0.7
0.6.3
0.6.2
0.6.1
0.6
0.5.1
0.5
0.4
0.3.1
0.3
0.2.1
0.2 dev
The code:
import posixpath
import pkg_resources
import sys
from pip.download import url_to_path
from pip.exceptions import DistributionNotFound
from pip.index import PackageFinder, Link
from pip.log import logger
from pip.req import InstallRequirement
from pip.util import Inf
class MyPackageFinder(PackageFinder):
def find_requirement(self, req, upgrade):
url_name = req.url_name
# Only check main index if index URL is given:
main_index_url = None
if self.index_urls:
# Check that we have the url_name correctly spelled:
main_index_url = Link(posixpath.join(self.index_urls[0], url_name))
# This will also cache the page, so it's okay that we get it again later:
page = self._get_page(main_index_url, req)
if page is None:
url_name = self._find_url_name(Link(self.index_urls[0]), url_name, req) or req.url_name
# Combine index URLs with mirror URLs here to allow
# adding more index URLs from requirements files
all_index_urls = self.index_urls + self.mirror_urls
def mkurl_pypi_url(url):
loc = posixpath.join(url, url_name)
# For maximum compatibility with easy_install, ensure the path
# ends in a trailing slash. Although this isn't in the spec
# (and PyPI can handle it without the slash) some other index
# implementations might break if they relied on easy_install's behavior.
if not loc.endswith('/'):
loc = loc + '/'
return loc
if url_name is not None:
locations = [
mkurl_pypi_url(url)
for url in all_index_urls] + self.find_links
else:
locations = list(self.find_links)
locations.extend(self.dependency_links)
for version in req.absolute_versions:
if url_name is not None and main_index_url is not None:
locations = [
posixpath.join(main_index_url.url, version)] + locations
file_locations, url_locations = self._sort_locations(locations)
locations = [Link(url) for url in url_locations]
logger.debug('URLs to search for versions for %s:' % req)
for location in locations:
logger.debug('* %s' % location)
found_versions = []
found_versions.extend(
self._package_versions(
[Link(url, '-f') for url in self.find_links], req.name.lower()))
page_versions = []
for page in self._get_pages(locations, req):
logger.debug('Analyzing links from page %s' % page.url)
logger.indent += 2
try:
page_versions.extend(self._package_versions(page.links, req.name.lower()))
finally:
logger.indent -= 2
dependency_versions = list(self._package_versions(
[Link(url) for url in self.dependency_links], req.name.lower()))
if dependency_versions:
logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions]))
file_versions = list(self._package_versions(
[Link(url) for url in file_locations], req.name.lower()))
if not found_versions and not page_versions and not dependency_versions and not file_versions:
logger.fatal('Could not find any downloads that satisfy the requirement %s' % req)
raise DistributionNotFound('No distributions at all found for %s' % req)
if req.satisfied_by is not None:
found_versions.append((req.satisfied_by.parsed_version, Inf, req.satisfied_by.version))
if file_versions:
file_versions.sort(reverse=True)
logger.info('Local files found: %s' % ', '.join([url_to_path(link.url) for parsed, link, version in file_versions]))
found_versions = file_versions + found_versions
all_versions = found_versions + page_versions + dependency_versions
applicable_versions = []
for (parsed_version, link, version) in all_versions:
if version not in req.req:
logger.info("Ignoring link %s, version %s doesn't match %s"
% (link, version, ','.join([''.join(s) for s in req.req.specs])))
continue
applicable_versions.append((link, version))
applicable_versions = sorted(applicable_versions, key=lambda v: pkg_resources.parse_version(v[1]), reverse=True)
existing_applicable = bool([link for link, version in applicable_versions if link is Inf])
if not upgrade and existing_applicable:
if applicable_versions[0][1] is Inf:
logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement'
% req.satisfied_by.version)
else:
logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)'
% (req.satisfied_by.version, applicable_versions[0][1]))
return None
if not applicable_versions:
logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)'
% (req, ', '.join([version for parsed_version, link, version in found_versions])))
raise DistributionNotFound('No distributions matching the version for %s' % req)
if applicable_versions[0][0] is Inf:
# We have an existing version, and its the best version
logger.info('Installed version (%s) is most up-to-date (past versions: %s)'
% (req.satisfied_by.version, ', '.join([version for link, version in applicable_versions[1:]]) or 'none'))
return None
if len(applicable_versions) > 1:
logger.info('Using version %s (newest of versions: %s)' %
(applicable_versions[0][1], ', '.join([version for link, version in applicable_versions])))
return applicable_versions
if __name__ == '__main__':
req = InstallRequirement.from_line(sys.argv[1], None)
finder = MyPackageFinder([], ['http://pypi.python.org/simple/'])
versions = finder.find_requirement(req, False)
print 'Versions of %s' % sys.argv[1]
for v in versions:
print v[1]
You could use the Faker library, it's mainly used for testing, but is capable of providing a variety of fake data.
Install: https://pypi.org/project/Faker/
>>> from faker import Faker
>>> fake = Faker()
>>> fake.pybool()
True
eq is used to compare integers use equal '=' instead , example:
if [ 'AAA' = 'ABC' ];
then
echo "the same"
else
echo "not the same"
fi
good luck
Origin null
is the local file system, so that suggests that you're loading the HTML page that does the load
call via a file:///
URL (e.g., just double-clicking it in a local file browser or similar). Different browsers take different approaches to applying the Same Origin Policy to local files.
My guess is that you're seeing this using Chrome. Chrome's rules for applying the SOP to local files are very tight, it disallows even loading files from the same directory as the document. So does Opera. Some other browsers, such as Firefox, allow limited access to local files. But basically, using ajax with local resources isn't going to work cross-browser.
If you're just testing something locally that you'll really be deploying to the web, rather than use local files, install a simple web server and test via http://
URLs instead. That gives you a much more accurate security picture.
I just wanted to provide a bit of an update/special case since it looks like people still come here. If you're using a multi-index or otherwise using an index-slicer the inplace=True option may not be enough to update the slice you've chosen. For example in a 2x2 level multi-index this will not change any values (as of pandas 0.15):
idx = pd.IndexSlice
df.loc[idx[:,mask_1],idx[mask_2,:]].fillna(value=0,inplace=True)
The "problem" is that the chaining breaks the fillna ability to update the original dataframe. I put "problem" in quotes because there are good reasons for the design decisions that led to not interpreting through these chains in certain situations. Also, this is a complex example (though I really ran into it), but the same may apply to fewer levels of indexes depending on how you slice.
The solution is DataFrame.update:
df.update(df.loc[idx[:,mask_1],idx[[mask_2],:]].fillna(value=0))
It's one line, reads reasonably well (sort of) and eliminates any unnecessary messing with intermediate variables or loops while allowing you to apply fillna to any multi-level slice you like!
If anybody can find places this doesn't work please post in the comments, I've been messing with it and looking at the source and it seems to solve at least my multi-index slice problems.
Hilite doesn't seem to be mentioned yet in the answers, so: Hilite supports lots of languages (20+), can be used online also via API, and is on Github (so you can clone, modify, and run it on your own if you don't trust the online service). The online version can also be adjusted to one's needs via CSS rules.
I just found it some minutes ago since I needed a tool for copying xQuery into Word, but couldn't find a proper tool for doing so. The source program is baseX and for some reason, its formatting could not be transmitted to Word (also not via Keep format etc. when pasting). Also, many of the given answers are now, i.e. 06/2019, not working anymore or do not support xQuery. Hilite, however, did the job quite well.
Edit: a code block is not part of the result, unfortunatelly, just the highlighting. Nevertheless, it's better than nothing and adjusting the result by adding a block around is still less work than formating every single line by hand