i was also facing the same issue, I resolved it by after selecting the Google's font that i was using, then I clicked on (Family-Selected) minimized tab and then clicked on "CUSTOMIZE" button. Then I selected the font weights that I want and then embedded the updated link in my html..
After giving necessary permissions in DCOM configurations I also needed to change the identity of my application in the IIS to a custom account
Your schema is for its target namespace http://www.example.org/Test
so it defines an element with name MyElement
in that target namespace http://www.example.org/Test
. Your instance document however has an element with name MyElement
in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.
You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>
.
Try this:
foreach($samplearr as $key => $item){
print "<tr><td>"
. $key
. "</td><td>"
. $item['value1']
. "</td><td>"
. $item['value2']
. "</td></tr>";
}
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
You can also do like these
When you open the file you want to write to, open it with a specific encoding that can handle all the characters.
with open('filename', 'w', encoding='utf-8') as f:
print(r['body'], file=f)
No such thing. the input type=date
will pick up whatever your system default is and show that in the GUI but will always store the value in ISO format (yyyy-mm-dd). Beside be aware that not all browsers support this so it's not a good idea to depend on this input type yet.
If this is a corporate issue, force all the computer to use local regional format (dd-mm-yyyy) and your UI will show it in this format (see wufoo link before after changing your regional settings, you need to reopen the browser).
See: http://www.wufoo.com/html5/types/4-date.html for example
See: http://caniuse.com/#feat=input-datetime for browser supports
See: https://www.w3.org/TR/2011/WD-html-markup-20110525/input.date.html for spec. <- no format attr.
Your best bet is still to use JavaScript based component that will allow you to customize this to whatever you wish.
i have alreay 2 situations where directives and services/factories didnt play well.
the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).
in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.
i even tried to make a directive with a controller and an isolated-scope
only when i moved everything to a controller and it worked like magic.
example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS
Method that will work. The way it is used above will not work.
declare @str varchar(50)='79136'
select
case
when @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
declare @str2 varchar(50)='79D136'
select
case
when @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
A really nicer way would be creating a class (or classes) for the exceptions.
Something like:
class ConfigurationError : public std::exception {
public:
ConfigurationError();
};
class ConfigurationLoadError : public ConfigurationError {
public:
ConfigurationLoadError(std::string & filename);
};
The reason is that exceptions are much more preferable than just transferring a string. Providing different classes for the errors, you give developers a chance to handle a particular error in a corresponded way (not just display an error message). People catching your exception can be as specific as they need if you use a hierarchy.
a) One may need to know the specific reason
} catch (const ConfigurationLoadError & ex) {
// ...
} catch (const ConfigurationError & ex) {
a) another does not want to know details
} catch (const std::exception & ex) {
You can find some inspiration on this topic in https://books.google.ru/books?id=6tjfmnKhT24C Chapter 9
Also, you can provide a custom message too, but be careful - it is not safe to compose a message with either std::string
or std::stringstream
or any other way which can cause an exception.
Generally, there is no difference whether you allocate memory (work with strings in C++ manner) in the constructor of the exception or just before throwing - std::bad_alloc
exception can be thrown before the one which you really want.
So, a buffer allocated on the stack (like in Maxim's answer) is a safer way.
It is explained very well at http://www.boost.org/community/error_handling.html
So, the nicer way would be a specific type of the exception and be avoiding composing the formatted string (at least when throwing).
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
Fixed by enabling Groovy plugin. Enabling it also enables the "SDK manager" option.
To make an exact copy, permissions, ownership, and all use "-a" with "cp". "-r" will copy the contents of the files but not necessarily keep other things the same.
cp -av Source/* Dest/
(make sure Dest/ exists first)
If you want to repeatedly update from one to the other or make sure you also copy all dotfiles, rsync
is a great help:
rsync -av --delete Source/ Dest/
This is also "recoverable" in that you can restart it if you abort it while copying. I like "-v" because it lets you watch what is going on but you can omit it.
Remember to include System.Diagnostics
ProcessStartInfo startInfo = new ProcessStartInfo("myfile.exe"); // exe file
startInfo.WorkingDirectory = @"C:\..\MyFile\bin\Debug\netcoreapp3.1\"; // exe folder
//here you add your arguments
startInfo.ArgumentList.Add("arg0"); // First argument
startInfo.ArgumentList.Add("arg2"); // second argument
startInfo.ArgumentList.Add("arg3"); // third argument
Process.Start(startInfo);
The function:
function () {}
returns nothing (or undefined).
Sometimes we want to call a function right as we create it. You might be tempted to try this:
function () {}()
but it results in a SyntaxError
.
Using the !
operator before the function causes it to be treated as an expression, so we can call it:
!function () {}()
This will also return the boolean opposite of the return value of the function, in this case true
, because !undefined
is true
. If you want the actual return value to be the result of the call, then try doing it this way:
(function () {})()
File f = new File("Test.txt");
if(!f.exists()){
f.createNewFile();
}else{
System.out.println("File already exists");
}
Pass this f
to your FileOutputStream
constructor.
here is a demo
first you need to correct your syntax error its
display: table-cell;
not diaplay: table-cell;
.container {
display: table;
border-collapse:collapse
}
.column {
display:table-row;
}
.cell {
display: table-cell;
border: 1px solid red;
width: 120px;
height: 20px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
To clarify the excellent answer of Ryan Newsom and to adjust it for fragments and for the usual case that we want to navigate from a "master" ListView fragment to a "details" fragment and then back to the "master"
private View root;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(root == null){
root = inflater.inflate(R.layout.myfragmentid,container,false);
InitializeView();
}
return root;
}
public void InitializeView()
{
ListView listView = (ListView)root.findViewById(R.id.listviewid);
BaseAdapter adapter = CreateAdapter();//Create your adapter here
listView.setAdpater(adapter);
//other initialization code
}
The "magic" here is that when we navigate back from the details fragment to the ListView fragment, the view is not recreated, we don't set the ListView's adapter, so everything stays as we left it!
The answers given work, with added plugins.
If you want to replace/update a built-in plugin like the credentials plugin, that has dependencies, then you have to use the frontend. To automate I use:
curl -i -F [email protected] http://jenkinshost/jenkins/pluginManager/uploadPlugin
Are you simply appending string literals? Or are you going to be appending various data types (ints, floats, etc.)?
It might be easier to abstract this out into its own function (the following assumes C99):
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
int appendToStr(char *target, size_t targetSize, const char * restrict format, ...)
{
va_list args;
char temp[targetSize];
int result;
va_start(args, format);
result = vsnprintf(temp, targetSize, format, args);
if (result != EOF)
{
if (strlen(temp) + strlen(target) > targetSize)
{
fprintf(stderr, "appendToStr: target buffer not large enough to hold additional string");
return 0;
}
strcat(target, temp);
}
va_end(args);
return result;
}
And you would use it like so:
char target[100] = {0};
...
appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159);
appendToStr(target, sizeof target, "blah blah blah");
etc.
The function returns the value from vsprintf
, which in most implementations is the number of bytes written to the destination. There are a few holes in this implementation, but it should give you some ideas.
I'm using a logger_config.yaml
file to configure my logging, and to get those logs to show up, all I had to do was to add a disable_existing_loggers: False
to the end of it.
My logging setup is rather extensive and confusing, so I don't even know a good way to explain it here, but if someone's also using a YAML file to configure their logging, this might help.
https://docs.python.org/3/howto/logging.html#configuring-logging
java.util.Date date;
Timestamp timestamp = resultSet.getTimestamp(i);
if (timestamp != null)
date = new java.util.Date(timestamp.getTime()));
Then format it the way you like.
For other people trying to make a table (or something) look focused on one row using opacity. Like @Blowski said use color not opacity. Check out this fiddle: http://jsfiddle.net/2en6o43d/
.table:hover > .row:not(:hover)
We run jenkins from the .war file with the following command.
java -Xmx2500M -jar jenkins.war --httpPort=3333 --prefix=/jenkins
You can even run the command from the ~/Downloads directory
you can do like this :
<?php
$file = 'your_images.jpg';
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file));
echo file_get_contents($file);
?>
I had a similar issue and I just took the background image with photoshop and created a new .png with the opacity I needed. Problem solved without worrying about if my CSS worked accross all devices & browsers
DO NOT run php artisan migrate:fresh
that's gonna drop all the tables
from datetime import datetime
from calendar import timegm
# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
if dttm is None:
dttm = datetime.utcnow()
return timegm(dttm.utctimetuple())
print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
This works on firefox 3.6.x and IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
Installing Microsoft Visual C++ 2010 Service Pack 1 Compiler Update for the Windows SDK 7.1 worked for me. However, I experienced issues with the update because I already had VS 2010 and VS 2010 SP1 installed. As mentioned by Xv above, the readme.htm file contains solutions for the most common installation issues in the "Known Issues" section. I would follow the instructions in the readme.htm and reboot your machine after each troubleshooting attempt because some installs write to your registry.
Go to Behavior > Site Content > All Pages and put your URI into the search box.
Go To anaconda prompt(type "anaconda" in search box in your laptop). type following commands
where conda
add that location to your environment path variables. Close the cmd and open it again
For those using Laravel, this https://github.com/sitepoint-editors/google-laravel-2FA is a nice way to solve this problem.
Just create the database using createdb
CLI tool:
PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB
If the database exists, it will return an error:
createdb: database creation failed: ERROR: database "mydb" already exists
By adding a few more headers I was able to get the data:
import urllib2,cookielib
site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
content = page.read()
print content
Actually, it works with just this one additional header:
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
uint32_t
is standard, uint32
is not. That is, if you include <inttypes.h>
or <stdint.h>
, you will get a definition of uint32_t
. uint32
is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
It depends if you just care that the variable has been defined or if you want it to have a meaningful value.
Checking if the type is undefined will check if the variable has been defined yet.
=== null
or !== null
will only check if the value of the variable is exactly null
.
== null
or != null
will check if the value is undefined
or null
.
if(value)
will check if the variable is undefined
, null
, 0
, or an empty string.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
ClusterIP: Services are reachable by pods/services in the Cluster
If I make a service called myservice in the default namespace of type: ClusterIP then the following predictable static DNS address for the service will be created:
myservice.default.svc.cluster.local (or just myservice.default, or by pods in the default namespace just "myservice" will work)
And that DNS name can only be resolved by pods and services inside the cluster.
NodePort: Services are reachable by clients on the same LAN/clients who can ping the K8s Host Nodes (and pods/services in the cluster) (Note for security your k8s host nodes should be on a private subnet, thus clients on the internet won't be able to reach this service)
If I make a service called mynodeportservice in the mynamespace namespace of type: NodePort on a 3 Node Kubernetes Cluster. Then a Service of type: ClusterIP will be created and it'll be reachable by clients inside the cluster at the following predictable static DNS address:
mynodeportservice.mynamespace.svc.cluster.local (or just mynodeportservice.mynamespace)
For each port that mynodeportservice listens on a nodeport in the range of 30000 - 32767 will be randomly chosen. So that External clients that are outside the cluster can hit that ClusterIP service that exists inside the cluster.
Lets say that our 3 K8s host nodes have IPs 10.10.10.1, 10.10.10.2, 10.10.10.3, the Kubernetes service is listening on port 80, and the Nodeport picked at random was 31852.
A client that exists outside of the cluster could visit 10.10.10.1:31852, 10.10.10.2:31852, or 10.10.10.3:31852 (as NodePort is listened for by every Kubernetes Host Node) Kubeproxy will forward the request to mynodeportservice's port 80.
LoadBalancer: Services are reachable by everyone connected to the internet* (Common architecture is L4 LB is publicly accessible on the internet by putting it in a DMZ or giving it both a private and public IP and k8s host nodes are on a private subnet)
(Note: This is the only service type that doesn't work in 100% of Kubernetes implementations, like bare metal Kubernetes, it works when Kubernetes has cloud provider integrations.)
If you make mylbservice, then a L4 LB VM will be spawned (a cluster IP service, and a NodePort Service will be implicitly spawned as well). This time our NodePort is 30222. the idea is that the L4 LB will have a public IP of 1.2.3.4 and it will load balance and forward traffic to the 3 K8s host nodes that have private IP addresses. (10.10.10.1:30222, 10.10.10.2:30222, 10.10.10.3:30222) and then Kube Proxy will forward it to the service of type ClusterIP that exists inside the cluster.
You also asked:
Does the NodePort service type still use the ClusterIP? Yes*
Or is the NodeIP actually the IP found when you run kubectl get nodes? Also Yes*
Lets draw a parrallel between Fundamentals:
A container is inside a pod. a pod is inside a replicaset. a replicaset is inside a deployment.
Well similarly:
A ClusterIP Service is part of a NodePort Service. A NodePort Service is Part of a Load Balancer Service.
In that diagram you showed, the Client would be a pod inside the cluster.
I think I found a solution to hide certain JavaScript codes in the view source of the browser. But you have to use jQuery to do this.
For example:
In your index.php
<head>
<script language = 'javascript' src = 'jquery.js'></script>
<script language = 'javascript' src = 'js.js'></script>
</head>
<body>
<a href = "javascript:void(null)" onclick = "loaddiv()">Click me.</a>
<div id = "content">
</div>
</body>
You load a file in the html/php body called by a jquery function in the js.js file.
js.js
function loaddiv()
{$('#content').load('content.php');}
Here's the trick.
In your content.php file put another head tag then call another js file from there.
content.php
<head>
<script language = 'javascript' src = 'js2.js'></script>
</head>
<a href = "javascript:void(null)" onclick = "loaddiv2()">Click me too.</a>
<div id = "content2">
</div>
in the js2.js file create any function you want.
example:
js2.js
function loaddiv2()
{$('#content2').load('content2.php');}
content2.php
<?php
echo "Test 2";
?>
Please follow link then copy paste it in the filename of jquery.js
http://dl.dropbox.com/u/36557803/jquery.js
I hope this helps.
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>
NOTE: I include this answer for completeness since the OP didn't mention what the data source is and we shouldn't make any assumptions.
This query gives the correct answer, but could be slower since it might have to sort all the items in People
, depending on what data structure People
is:
var oldest = People.OrderBy(p => p.DateOfBirth ?? DateTime.MaxValue).First();
UPDATE: Actually I shouldn't call this solution "naive", but the user does need to know what he is querying against. This solution's "slowness" depends on the underlying data. If this is a array or List<T>
, then LINQ to Objects has no choice but to sort the entire collection first before selecting the first item. In this case it will be slower than the other solution suggested. However, if this is a LINQ to SQL table and DateOfBirth
is an indexed column, then SQL Server will use the index instead of sorting all the rows. Other custom IEnumerable<T>
implementations could also make use of indexes (see i4o: Indexed LINQ, or the object database db4o) and make this solution faster than Aggregate()
or MaxBy()
/MinBy()
which need to iterate the whole collection once. In fact, LINQ to Objects could have (in theory) made special cases in OrderBy()
for sorted collections like SortedList<T>
, but it doesn't, as far as I know.
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
The string representation of a DateTime can be parsed by the Time class.
> Time.parse(DateTime.now.to_s).utc
=> 2015-10-06 14:53:51 UTC
The simpler way:
h = ''
i = None
j = 0
k = 1
print h or i or j or k
Will print 1
print k or j or i or h
Will print 1
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
Here's a simple binary to decimal converter that continuously loops
t = 1
while t > 0:
binaryNumber = input("Enter a binary No.")
convertedNumber = int(binaryNumber, 2)
print(convertedNumber)
print("")
I ran into a similar issue, so maybe this answer will help someone.
The reason for the Error: no display specified
error is that Firefox is being launched, but there is no X server (GUI) running on the remote host. You can use X11 forwarding to run Firefox on the remote host, but display it on your local host. On Mac OS X, you will need to download XQuartz in order to use X11 forwarding. Without it, you won't have a $DISPLAY
variable set, so if you try and echo $DISPLAY
, it will be blank.
Add the following line on the top of your file
require 'json'
Then you can use:
car = {:make => "bmw", :year => "2003"}
car.to_json
Alternatively, you can use:
JSON.generate({:make => "bmw", :year => "2003"})
You can't do it with pure html/javascript. This is because you have a seperate connection to the webserver to retrieve a separate file (the image) and a normal webserver will serve the file with content headers set so that the browser reading the content type will decide that the type can be handled internally.
The way to force the browser not to handle the file internally is to change the headers (content-disposition prefereably, or content-type) so the browser will not try to handle the file internally. You can either do this by writing a script on the webserver that dynamically sets the headers (i.e. download.php) or by configuring the webserver to return different headers for the file you want to download. You can do this on a per-directory basis on the webserver, which would allow you to get away without writing any php or javascript - simply have all your download images in that one location.
That means that you are printing output on the main output device for the session... whatever that may be. The user's console, a tty session, a file or who knows what. What that device may be varies depending on how the program is being run and from where.
The following command will write to the standard output device (stdout)...
printf( "hello world\n" );
Which is just another way, in essence, of doing this...
fprintf( stdout, "hello world\n" );
In which case stdout
is a pointer to a FILE
stream that represents the default output device for the application. You could also use
fprintf( stderr, "that didn't go well\n" );
in which case you would be sending the output to the standard error output device for the application which may, or may not, be the same as stdout
-- as with stdout
, stderr
is a pointer to a FILE
stream representing the default output device for error messages.
Something like this:
DataTable dt = new DataTable();
// For each row, print the values of each column.
foreach(DataRow row in dt .Rows)
{
foreach(DataColumn column in dt .Columns)
{
Console.WriteLine(row[column]);
}
}
http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx
The SQL you posted in your question is one way to do it. Most things in SQL have more than one way to do it.
UPDATE
[Table1]
SET
[Description]=(SELECT [Description] FROM [Table2] t2 WHERE t2.[ID]=Table1.DescriptionID)
If you are planning on running this on a PROD DB, it is best to create a snapshot or mirror of it first and test it out. Verify the data ends up as you expect for a couple records. And if you are satisfied, run it on the real DB.
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
To remove the variable from the current environment (not permanently):
set FOOBAR=
To permanently remove the variable from the user environment (which is the default place setx
puts it):
REG delete HKCU\Environment /F /V FOOBAR
If the variable is set in the system environment (e.g. if you originally set it with setx /M
), as an administrator run:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
Note: The REG
commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.
Here is a really nice example of a pythonic way to do that:
import json
import psycopg2
def db(database_name='pepe'):
return psycopg2.connect(database=database_name)
def query_db(query, args=(), one=False):
cur = db().cursor()
cur.execute(query, args)
r = [dict((cur.description[i][0], value) \
for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return (r[0] if r else None) if one else r
my_query = query_db("select * from majorroadstiger limit %s", (3,))
json_output = json.dumps(my_query)
You get an array of JSON objects:
>>> json_output
'[{"divroad": "N", "featcat": null, "countyfp": "001",...
Or with the following:
>>> j2 = query_db("select * from majorroadstiger where fullname= %s limit %s",\
("Mission Blvd", 1), one=True)
you get a single JSON object:
>>> j2 = json.dumps(j2)
>>> j2
'{"divroad": "N", "featcat": null, "countyfp": "001",...
This worked for me:)
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Use getattr
to get an attribute from a name in a string. In other words, get the instance as
instance = getattr(modul, class_name)()
If the two files are not sorted yet, you can use:
comm -12 <(sort a.txt) <(sort b.txt)
and it will work, avoiding the error message comm: file 2 is not in sorted order
when doing comm -12 a.txt b.txt
.
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
Yes, something like this:
SELECT
id,
action_heading,
CASE
WHEN action_type = 'Income' THEN action_amount
ELSE NULL
END AS income_amt,
CASE
WHEN action_type = 'Expense' THEN action_amount
ELSE NULL
END AS expense_amt
FROM tbl_transaction;
As other answers have pointed out, MySQL also has the IF()
function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE
is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.
Here's how I got rid of mine:
.main .row .thumbnail {
display: inline-block;
border: 0px;
background-color: transparent;
}
Back in 2008 this wasn't important because of the lack of mobile OS'es but now quite important thing.
When you set accepted mime types, then in for example Android user is given system dialog with apps which can provide him the content of mime which file input accepts, what is great because navigating through files in file explorer on mobile devices is slow and often stressful.
One important thing is that some mobile browsers (based on Android version of Chrome 36 and Chrome Beta 37) does not support app filtering over extension(s) and multiple mime types.
If the user input is a String
then you can try to parse it as an integer using parseInt
method, which throws NumberFormatException
when the input is not a valid number string:
try {
int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
System.out.println("Input is not a valid integer");
}
In general, you need to use this feature when you don't want or don't have time to deal with a huge table. If this is your case, it's better to use --where option from mysqldump limiting resultset. For example, mysqldump -uuser -ppass database --where="1 = 1 LIMIT 500000" > resultset.sql
.
I guess you can do this in 5 minute without any further IP/port forwarding, for presenting your local websites temporary.
All you need to do it, go to http://ngrok.com Download small tool extract and run that tool as administrator
Enter command
ngrok http 80
You will see it will connect to server and will create a temporary URL for you which you can share to your friend and let him browse localhost or any of its folder.
You can see detailed process here.
How do I access/share xampp or localhost website from another computer
In my case it was enough to split the text at every \n
and then create a JLabel
for every line:
JPanel panel = new JPanel(new GridLayout(0,1));
String[] lines = message.split("\n");
for (String line : lines) {
JLabel label = new JLabel(line);
panel.add(label);
}
I used above in a JOptionPane.showMessageDialog
I'm aware that this question is a bit old, but I consider that my small update could help other programmers.
I didn't want to modify WhoIsRich's answer because it's really great, but I adapted it to fulfill my needs:
If the Automatically Detect Settings is unchecked then check it.
On Error Resume Next
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
sKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
sValueName = "DefaultConnectionSettings"
' Get registry value where each byte is a different setting.
oReg.GetBinaryValue &H80000001, sKeyPath, sValueName, bValue
' Check byte to see if detect is currently on.
If (bValue(8) And 8) = 8 Then
' To change the value to Off.
bValue(8) = bValue(8) And Not 8
' Check byte to see if detect is currently off.
ElseIf (bValue(8) And 8) = 0 Then
' To change the value to On.
bValue(8) = bValue(8) Or 8
End If
'Write back settings value
oReg.SetBinaryValue &H80000001, sKeyPath, sValueName, bValue
Set oReg = Nothing
Finally, you only need to save it in a .VBS file (VBScript) and run it.
// Set flash data
$this->session->set_flashdata('message_name', 'This is my message');
// After that you need to used redirect function instead of load view such as
redirect("admin/signup");
// Get Flash data on view
$this->session->flashdata('message_name');
Just use this after executing mongoimport
It will return number of objects imported
use db
db.collectionname.find().count()
will return the number of objects.
ctrl + k + 0 : Fold all levels (namespace , class , method , block)
ctrl + k + 1 : namspace
ctrl + k + 2 : class
ctrl + k + 3 : methods
ctrl + k + 4 : blocks
ctrl + k + [ or ] : current cursor block
ctrl + k + j : UnFold
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.
Leonbloy's answer is quite complete. I would only add the special case in which one needs to get the last inserted value from within a PL/pgSQL function where OPTION 3 doesn't fit exactly.
For example, if we have the following tables:
CREATE TABLE person(
id serial,
lastname character varying (50),
firstname character varying (50),
CONSTRAINT person_pk PRIMARY KEY (id)
);
CREATE TABLE client (
id integer,
CONSTRAINT client_pk PRIMARY KEY (id),
CONSTRAINT fk_client_person FOREIGN KEY (id)
REFERENCES person (id) MATCH SIMPLE
);
If we need to insert a client record we must refer to a person record. But let's say we want to devise a PL/pgSQL function that inserts a new record into client but also takes care of inserting the new person record. For that, we must use a slight variation of leonbloy's OPTION 3:
INSERT INTO person(lastname, firstname)
VALUES (lastn, firstn)
RETURNING id INTO [new_variable];
Note that there are two INTO clauses. Therefore, the PL/pgSQL function would be defined like:
CREATE OR REPLACE FUNCTION new_client(lastn character varying, firstn character varying)
RETURNS integer AS
$BODY$
DECLARE
v_id integer;
BEGIN
-- Inserts the new person record and retrieves the last inserted id
INSERT INTO person(lastname, firstname)
VALUES (lastn, firstn)
RETURNING id INTO v_id;
-- Inserts the new client and references the inserted person
INSERT INTO client(id) VALUES (v_id);
-- Return the new id so we can use it in a select clause or return the new id into the user application
RETURN v_id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
Now we can insert the new data using:
SELECT new_client('Smith', 'John');
or
SELECT * FROM new_client('Smith', 'John');
And we get the newly created id.
new_client
integer
----------
1
You can use the recursive "theirs" strategy option:
git merge --strategy-option theirs
From the man:
ours
This option forces conflicting hunks to be auto-resolved cleanly by
favoring our version. Changes from the other tree that do not
conflict with our side are reflected to the merge result.
This should not be confused with the ours merge strategy, which does
not even look at what the other tree contains at all. It discards
everything the other tree did, declaring our history contains all that
happened in it.
theirs
This is opposite of ours.
Note: as the man page says, the "ours" merge strategy-option is very different from the "ours" merge strategy.
When you have an empty route object, it's mainly due to the fact that you are not using a router-outlet in your app.component.html.
Without this, you won't be able to get a meaningful route object with non empty subObjects, particularly params & queryParams.
Try to add <router-outlet><router-outlet>
just before calling your
<app-main-component></app-main-component>
Before that, make sure you have your query param ready in app-routing > which export the class Route used by App component :
param: '/param/:dynamicParam', path: MyMainComponent
Last thing of course, to get your param, I personnaly use this.route.snapshot.params.dynamicParam
where dynamicParam is the name used in your app-routing component :)
As of API 24, sending a file://
URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content://
URI:
public File getFile(Context context, String fileName) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File storageDir = context.getExternalFilesDir(null);
return new File(storageDir, fileName);
}
public Uri getFileUri(Context context, String fileName) {
File file = getFile(context, fileName);
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
You must also define the FileProvider in your manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Example file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="name" path="path" />
</paths>
Replace "name" and "path" as appropriate.
To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION
flag to the intent:
private void displayPdf(String fileName) {
Uri uri = getFileUri(this, fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
// FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getPackageManager()) == null) {
// Show an error
} else {
startActivity(intent);
}
}
See the FileProvider documentation for more details.
This can also be done by using partial
from the standard library functools, like this:
from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)
This is what i do and it's in my opinion simplest way to do this. define an object manager for your new customized model then define your model.
from django.db import models
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager
class User_manager(BaseUserManager):
def create_user(self, username, email, gender, nickname, password):
email = self.normalize_email(email)
user = self.model(username=username, email=email, gender=gender, nickname=nickname)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, username, email, gender, password, nickname=None):
user = self.create_user(username=username, email=email, gender=gender, nickname=nickname, password=password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(PermissionsMixin, AbstractBaseUser):
username = models.CharField(max_length=32, unique=True, )
email = models.EmailField(max_length=32)
gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")]
gender = models.CharField(choices=gender_choices, default="M", max_length=1)
nickname = models.CharField(max_length=32, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
REQUIRED_FIELDS = ["email", "gender"]
USERNAME_FIELD = "username"
objects = User_manager()
def __str__(self):
return self.username
Dont forget to add this line of code in your settings.py
:
AUTH_USER_MODEL = 'YourApp.User'
This is what i do and it always works.
if (isset($_POST['remove'])) {
$key=array_search($_GET['name'],$_SESSION['name']);
if($key!==false)
unset($_SESSION['name'][$key]);
$_SESSION["name"] = array_values($_SESSION["name"]);
}
Since $_SESSION['name']
is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.
Here's an approach using the URL() interface:
new URL(location.pathname, location.href).href
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.
In HTML 4.01 and XHTML 1(.1), the type
attribute for <script>
elements is required.
The counter variable inside the loop is called loop.index in jinja2.
>>> from jinja2 import Template
>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4
See http://jinja.pocoo.org/docs/templates/ for more.
I believe the more modern and simpler way to do this now is hg uncommit
. Note this leaves behind an empty commit which can be useful if you want to reuse the commit message later. If you don't, use hg uncommit --no-keep
to not leave the empty commit.
hg uncommit [OPTION]... [FILE]...
uncommit part or all of a local changeset
This command undoes the effect of a local commit, returning the affected files to their uncommitted state. This means that files modified or deleted in the changeset will be left unchanged, and so will remain modified in the working directory. If no files are specified, the commit will be left empty, unless --no-keep
Sorry, I am not sure what the equivalent is TortoiseHg.
You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:
var remote = $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
I had a similar problem with a log4j.xml file for a unit test, did all of the above. But figured out it was because I was only re-running a failed test....if I re-run the entire test class the correct file is picked up. This is under Intelli-j 9.0.4
Just uninstall the application from emulator either from command line or go to settings and uninstall the application. This will stop the error from coming.
I placed the button group inside the title, and then added a clearfix to the bottom.
<div class="panel-heading">
<h4 class="panel-title">
Panel header
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</div>
</h4>
<div class="clearfix"></div>
</div>
Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a [
Nullable<Int32>
], pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A [Nullable<bool>
] can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.
Something like this in your form main. Double click the form in the visual editor to create the form load event.
Timer Clock=new Timer();
Clock.Interval=2700000; // not sure if this length of time will work
Clock.Start();
Clock.Tick+=new EventHandler(Timer_Tick);
Then add an event handler to do something when the timer fires.
public void Timer_Tick(object sender,EventArgs eArgs)
{
if(sender==Clock)
{
// do something here
}
}
All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems
in the NotifyCollectionChangedEventArgs
object.
this is the perfect ObservableCollection
.
public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
#region Constructors
public ObservableCollectionEX() : base()
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(IEnumerable<T> c) : base(c)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(List<T> l) : base(l)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
#endregion
public new void Clear()
{
foreach (var item in this)
if (item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
base.Clear();
}
private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (var item in e.OldItems)
if (item != null && item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
if (e.NewItems != null)
foreach (var item in e.NewItems)
if (item != null && item is INotifyPropertyChanged i)
{
i.PropertyChanged -= Element_PropertyChanged;
i.PropertyChanged += Element_PropertyChanged;
}
}
}
private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);
public ListedItemPropertyChangedEventHandler ItemPropertyChanged;
}
AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ...
.
I will expand on @User's generic solution to provide a drop
free alternative. This is for folks directed here based on the question's title (not OP 's problem)
Say you want to delete all rows with negative values. One liner solution is:-
df = df[(df > 0).all(axis=1)]
Step by step Explanation:--
Let's generate a 5x5 random normal distribution data frame
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,5), columns=list('ABCDE'))
A B C D E
0 1.764052 0.400157 0.978738 2.240893 1.867558
1 -0.977278 0.950088 -0.151357 -0.103219 0.410599
2 0.144044 1.454274 0.761038 0.121675 0.443863
3 0.333674 1.494079 -0.205158 0.313068 -0.854096
4 -2.552990 0.653619 0.864436 -0.742165 2.269755
Let the condition be deleting negatives. A boolean df satisfying the condition:-
df > 0
A B C D E
0 True True True True True
1 False True False False True
2 True True True True True
3 True True False True False
4 False True True False True
A boolean series for all rows satisfying the condition Note if any element in the row fails the condition the row is marked false
(df > 0).all(axis=1)
0 True
1 False
2 True
3 False
4 False
dtype: bool
Finally filter out rows from data frame based on the condition
df[(df > 0).all(axis=1)]
A B C D E
0 1.764052 0.400157 0.978738 2.240893 1.867558
2 0.144044 1.454274 0.761038 0.121675 0.443863
You can assign it back to df to actually delete vs filter ing done above
df = df[(df > 0).all(axis=1)]
This can easily be extended to filter out rows containing NaN s (non numeric entries):-
df = df[(~df.isnull()).all(axis=1)]
This can also be simplified for cases like: Delete all rows where column E is negative
df = df[(df.E>0)]
I would like to end with some profiling stats on why @User's drop
solution is slower than raw column based filtration:-
%timeit df_new = df[(df.E>0)]
345 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit dft.drop(dft[dft.E < 0].index, inplace=True)
890 µs ± 94.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
A column is basically a Series
i.e a NumPy
array, it can be indexed without any cost. For folks interested in how the underlying memory organization plays into execution speed here is a great Link on Speeding up Pandas:
Go to AndroidStudio projects File
You will find APK files of app here, if you have ran the app in AVD or even hardware device
As everyone else has said, there's no mapping within a dictionary from value to key.
I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.
The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) ||
secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
int x;
greek.TryGetBySecond("Beta", out x);
Console.WriteLine(x);
}
}
That looks correct to me. If I were to change anything, I would stop using the Collections.synchronizedMap() and synchronize everything the same way, just to make it clearer.
Also, I'd replace
if (synchronizedMap.containsKey(key)) {
synchronizedMap.get(key).add(value);
}
else {
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, valuesList);
}
with
List<String> valuesList = synchronziedMap.get(key);
if (valuesList == null)
{
valuesList = new ArrayList<String>();
synchronziedMap.put(key, valuesList);
}
valuesList.add(value);
Building on @Prasath's answer. This is how you do it in Swift:
if application.respondsToSelector("isRegisteredForRemoteNotifications")
{
// iOS 8 Notifications
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
application.registerForRemoteNotifications()
}
else
{
// iOS < 8 Notifications
application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
}
This will work:
override func viewDidLoad() {
super.viewDidLoad()
// Swift block syntax (iOS 10+)
let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print("Done!") }
// Swift >=3 selector syntax
let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
// Swift 2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
// Swift <2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
// must be internal or public.
@objc func update() {
// Something cool
}
For Swift 4, the method of which you want to get the selector must be exposed to Objective-C, thus @objc
attribute must be added to the method declaration.
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
if
and grep -Eq
arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
echo 'second'
fi
where:
-q
prevents grep
from producing output, it just produces the exit status-E
enables extended regular expressionsI like this because:
case
One downside is that this is likely slower than case
since it calls an external grep
program, but I tend to consider performance last when using Bash.
case
is POSIX 7
Bash appears to follow POSIX by default without shopt
as mentioned by https://stackoverflow.com/a/4555979/895245
Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":
The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]
The format for the case construct is as follows:
case word in [(] pattern1 ) compound-list ;; [[(] pattern[ | pattern] ... ) compound-list ;;] ... [[(] pattern[ | pattern] ... ) compound-list] esac
and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?
, *
and []
.
We use an ancient version of ComponentOne Chart.
Ok well this might work for you, a function that takes a path and returns an array of file names in the folder. You could use an if statement to get just the excel files when looping through the array.
Function listfiles(ByVal sPath As String)
Dim vaArray As Variant
Dim i As Integer
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
If oFiles.Count = 0 Then Exit Function
ReDim vaArray(1 To oFiles.Count)
i = 1
For Each oFile In oFiles
vaArray(i) = oFile.Name
i = i + 1
Next
listfiles = vaArray
End Function
It would be nice if we could just access the files in the files object by index number but that seems to be broken in VBA for whatever reason (bug?).
This is possible, too:
<a href="javascript:void(0)" onclick="myfunction()">
Link doesn't go anywhere by your function will be executed.
Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.
The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.
[UPDATE] This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors
Click on the link "whitespace characters" to fine tune what should be shown.
Kudos go to John Isaacks
I had to turn off my personal firewall and Windows firewall as well, and it worked in the end.
If you use a DELETE
statement on the mysql.user
table in an attempt to remove a user, then attempt to re-establish the user with CREATE USER
, you will get a 1396
error. Get rid of this error by running DROP USER 'username'@'host';
DELETE
FROM mysql.user
WHERE user = 'jack';
(You will get 1396 errors if you attempt to re-create jack)
CREATE USER 'jack'@'localhost' IDENTIFIED BY PASSWORD '*Fi47ytFF3CD5B14E7EjkjkkC1D3F8086A5C0-krn';
(Get out of this situation by running DROP USER
)
DROP USER 'jack'@'localhost';
(I suppose FLUSH PRIVILEGES
can't hurt, but definitely drop the user first.)
You can get numpy version using Terminal or a Python code.
In a Terminal (bash) using Ubuntu:
pip list | grep numpy
In python 3.6.7, this code shows the numpy version:
import numpy
print (numpy.version.version)
If you insert this code in the file shownumpy.py, you can compile it:
python shownumpy.py
or
python3 shownumpy.py
I've got this output:
1.16.1
Here is a cleaner code sample of a good way to get the IP address of the user.
$ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
Here is a shorter version that uses the elvis operator:
$_SERVER['HTTP_CLIENT_IP'] ? : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? : $_SERVER['REMOTE_ADDR']);
Here is a version that uses isset to remove notices (thank you, @shasi kanth):
$ip = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
Just install Globally
npm install -g nodemon
It worked for me on Windows 10.
nodemon app.js
My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......
function CheckLength()
{
var keyCode = event.keyCode
if (keyCode == 13)
{
document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
}
}
Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string ""
is a blank string with the length of 0.
You can add the null check also
AND (email != "" OR email IS NOT NULL)
If you want to return in full TIMESTAMP format than try it: -
SELECT TIMEDIFF(`call_end_time`, `call_start_time`) as diff from tablename;
return like
diff
- - -
00:05:15
You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.
If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.
To answer some of your comments...
To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.
The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.
The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.
One you have valid json you can use this code to convert it to an array.
json_decode($json, true);
Array
(
[bpath] => http://www.sampledomain.com/
[clist] => Array
(
[0] => Array
(
[cid] => 11
[display_type] => grid
[ctitle] => abc
[acount] => 71
[alist] => Array
(
[0] => Array
(
[aid] => 6865
[adate] => 2 Hours ago
[atitle] => test
[adesc] => test desc
[aimg] =>
[aurl] => ?nid=6865
[weburl] => news.php?nid=6865
[cmtcount] => 0
)
[1] => Array
(
[aid] => 6857
[adate] => 20 Hours ago
[atitle] => test1
[adesc] => test desc1
[aimg] =>
[aurl] => ?nid=6857
[weburl] => news.php?nid=6857
[cmtcount] => 0
)
)
)
[1] => Array
(
[cid] => 1
[display_type] => grid
[ctitle] => test1
[acount] => 2354
[alist] => Array
(
[0] => Array
(
[aid] => 6851
[adate] => 1 Days ago
[atitle] => test123
[adesc] => test123 desc
[aimg] =>
[aurl] => ?nid=6851
[weburl] => news.php?nid=6851
[cmtcount] => 7
)
[1] => Array
(
[aid] => 6847
[adate] => 2 Days ago
[atitle] => test12345
[adesc] => test12345 desc
[aimg] =>
[aurl] => ?nid=6847
[weburl] => news.php?nid=6847
[cmtcount] => 7
)
)
)
)
)
The socket has been closed by the client (browser).
A bug in your code:
byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
output.write(outputByte,0,4096);
}
The last packet read, then write may have a length < 4096, so I suggest:
byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
output.write( outputByte, 0, len );
}
It's not your question, but it's my answer... ;-)
If you're using MySQL, there is a method REGEXP that you can use...
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
So then you would use:
SELECT * FROM `shirts` WHERE `colors` REGEXP '\b1\b'
The first one generates numbers in the wrong range, while the second one is correct.
To show that the first one is incorrect, let's say min
is 10 and max
is 20. In other words, the result is expected to be greater than or equal to ten, and strictly less than twenty. If Math.random()
returns 0.75
, the result of the first formula is 25
, which is outside the range.
Scenario - 1
If you don't want selection for some specific cells on the tableview, you can set selection style in cellForRow function for those cells.
Objective-C
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Swift 4.2
cell.selectionStyle = .none
Scenario - 2
For disabling selection on the whole table view :
Objective-C
self.tableView.allowsSelection = false;
Swift 4.2
self.tableView.allowsSelection = false
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
For anyone want to replace your script.
update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%
Use:
import os
f_loc = r"C:\Users\Russell\Desktop\myfile.dat"
# Create the file if it does not exist
if not os.path.exists(f_loc):
open(f_loc, 'w').close()
# Open the file for appending and reading
with open(f_loc, 'a+') as f:
#Do stuff
Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.
you can use this one in onCreateView, you can use transaction or replace
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
//what you want to do
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
Edit the application tag in manifest file.
<application
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
Change the label attribute and give the latest name over there.
The header()
function in PHP does this, but make sure that you call it before any other file contents are sent to the browser or else you will receive an error.
JavaScript is an alternative if you have already sent the file contents.
I do this quite often on results returned from a query..
e.g.
// $MyQueryResult is an array of results from a query
foreach ($MyQueryResult as $key=>$value)
{
${$key}=$value;
}
Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']
Yep, it's probably lazy, but I've never had any problems.
I would suggest the use of exists
instead of in
because in some scenarios that implies null values the behavior is different, so
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2 childTable
WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO
LayerDrawable bgDrawable = (LayerDrawable) button.getBackground();
final GradientDrawable shape = (GradientDrawable)
bgDrawable.findDrawableByLayerId(R.id.round_button_shape);
shape.setColor(Color.BLACK);
You have a few options:
First, you can use the JoinPoint#getArgs()
method which returns an Object[]
containing all the arguments of the advised method. You might have to do some casting depending on what you want to do with them.
Second, you can use the args
pointcut expression like so:
// use '..' in the args expression if you have zero or more parameters at that point
@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..)) && args(yourString,..)")
then your method can instead be defined as
public void logBefore(JoinPoint joinPoint, String yourString)
A shorter awk alternative:
awk 1 ORS=' '
An awk program is built up of rules which consist of conditional code-blocks, i.e.:
condition { code-block }
If the code-block is omitted, the default is used: { print $0 }
. Thus, the 1
is interpreted as a true condition and print $0
is executed for each line.
When awk
reads the input it splits it into records based on the value of RS
(Record Separator), which by default is a newline, thus awk
will by default parse the input line-wise. The splitting also involves stripping off RS
from the input record.
Now, when printing a record, ORS
(Output Record Separator) is appended to it, default is again a newline. So by changing ORS
to a space all newlines are changed to spaces.
Here's my variant that allows getting both IPv4 and IPv6 addresses in a portable manner:
/**
* Collects information about the local IPv4/IPv6 addresses of
* every network interface on the local computer.
* Returns an object with the network interface name as the first-level key and
* "IPv4" or "IPv6" as the second-level key.
* For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
* (as string) of eth0
*/
getLocalIPs = function () {
var addrInfo, ifaceDetails, _len;
var localIPInfo = {};
//Get the network interfaces
var networkInterfaces = require('os').networkInterfaces();
//Iterate over the network interfaces
for (var ifaceName in networkInterfaces) {
ifaceDetails = networkInterfaces[ifaceName];
//Iterate over all interface details
for (var _i = 0, _len = ifaceDetails.length; _i < _len; _i++) {
addrInfo = ifaceDetails[_i];
if (addrInfo.family === 'IPv4') {
//Extract the IPv4 address
if (!localIPInfo[ifaceName]) {
localIPInfo[ifaceName] = {};
}
localIPInfo[ifaceName].IPv4 = addrInfo.address;
} else if (addrInfo.family === 'IPv6') {
//Extract the IPv6 address
if (!localIPInfo[ifaceName]) {
localIPInfo[ifaceName] = {};
}
localIPInfo[ifaceName].IPv6 = addrInfo.address;
}
}
}
return localIPInfo;
};
Here's a CoffeeScript version of the same function:
getLocalIPs = () =>
###
Collects information about the local IPv4/IPv6 addresses of
every network interface on the local computer.
Returns an object with the network interface name as the first-level key and
"IPv4" or "IPv6" as the second-level key.
For example you can use getLocalIPs().eth0.IPv6 to get the IPv6 address
(as string) of eth0
###
networkInterfaces = require('os').networkInterfaces();
localIPInfo = {}
for ifaceName, ifaceDetails of networkInterfaces
for addrInfo in ifaceDetails
if addrInfo.family=='IPv4'
if !localIPInfo[ifaceName]
localIPInfo[ifaceName] = {}
localIPInfo[ifaceName].IPv4 = addrInfo.address
else if addrInfo.family=='IPv6'
if !localIPInfo[ifaceName]
localIPInfo[ifaceName] = {}
localIPInfo[ifaceName].IPv6 = addrInfo.address
return localIPInfo
Example output for console.log(getLocalIPs())
{ lo: { IPv4: '127.0.0.1', IPv6: '::1' },
wlan0: { IPv4: '192.168.178.21', IPv6: 'fe80::aa1a:2eee:feba:1c39' },
tap0: { IPv4: '10.1.1.7', IPv6: 'fe80::ddf1:a9a1:1242:bc9b' } }
I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});
AFAIK, there is no good way to do this with consistency. I was writing an IE only web-based IM client. We ended up using window.focus(), which works most of the time. Sometimes it will actually cause the window to steal focus from the foreground app, which can be really annoying.
Problem solved.
Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.
So weird...
Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!
It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:
class array2D {
std::vector<double> data;
size_t columns;
public:
array2D(size_t x, size_t y) : columns(x), data(x*y) {}
double &operator(size_t x, size_t y) {
return data[y*columns+x];
}
};
Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.
In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.
If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:
11 12 13
23 34 56 78
You might want to use a std::vector<std::vector<double> >
instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.
std::vector<std::vector<double> > numbers;
std::string temp;
while (std::getline(infile, temp)) {
std::istringstream buffer(temp);
std::vector<double> line((std::istream_iterator<double>(buffer)),
std::istream_iterator<double>());
numbers.push_back(line);
}
...or, with a modern (C++11) compiler, you can use brackets for line
's initialization:
std::vector<double> line{std::istream_iterator<double>(buffer),
std::istream_iterator<double>()};
You could also use deconstruction and tuples and try something like this:
@foreach (var (index, member) in @Model.Members.Select((member, i) => (i, member)))
{
<div>@index - @member.anyProperty</div>
if(index > 0 && index % 4 == 0) { // display clear div every 4 elements
@: <div class="clear"></div>
}
}
For more info you can have a look at this link
Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.
<body>
<app-root></app-root>
<script>
myTest = 1;
</script>
</body>
..near the top right after imports:
declare const myTest: any;
...later:
console.warn(myTest); // outputs '1'
All you need to do is to add app.UseStaticFiles();
in your startup.cs -> public void Configure(IApplicationBuilder app, IHostingEnvironment env)
.
ASP.net core provides an excellent way to get static files. That is using the wwwroot folder. Please read Static files in ASP.NET Core.
Using the <Link />
is not a very good idea. Why would someone add the link tag on each HTML or cshtml for the favicon.ico?
It doesn't make sense to create a web.xml just elcipse wants it, even there is no need. This is the case if you have servlet conatiner embedded or living without xml cfg like spring-boot does. The you just diable JavaEE (useless stuff) in eclipse on project level or global
Eclipse/STS>Windows>Preferences>JavaEE>Doclet>Webdoclet> "uncheck" DeploymentDescriptor > OK
You should probably be using a more unobtrusive approach. Here's the benefits
- Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
- Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
- Progressive enhancement to support user agents that may not support advanced JavaScript functionality
Your JavaScript
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
img = images[i];
img.addEventListener("click", function() {
var a = img.getAttribute("data-a"),
b = img.getAttribute("data-b"),
c = img.getAttribute("data-c"),
d = img.getAttribute("data-d"),
e = img.getAttribute("data-e");
exportToForm(a, b, c, d, e);
});
}
Your images will look like this
<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">
no need to require the ckeditor.php, because CKEditor will not processed by PHP...
you need just following the _samples directory and see what they do.
just need to include ckeditor.js by html tag, and do some configuration in javascript.
By default require()
is not a valid function in client side javascript. I recommend you look into require.js as this does extend the client side to provide you with that function.
I implemented the following and it works well. Basically, I set the body dimensions according to the size of the iFrame content. It does mean that our non-iFrame menu can be scrolled off the screen, but otherwise, this makes our sites functional with iPad and iPhone. "workbox" is the ID of our iFrame.
// Configure for scrolling peculiarities of iPad and iPhone
if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
{
document.body.style.width = "100%";
document.body.style.height = "100%";
$("#workbox").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
iframeWidth = $("#workbox").contents().width();
if (iframeWidth > 400)
document.body.style.width = (iframeWidth + 182) + 'px';
iframeHeight = $("#workbox").contents().height();
if (iframeHeight>200)
document.body.style.height = iframeHeight + 'px';
});
}
var datetime = new Date();_x000D_
console.log(datetime.toISOString().slice(0,10));
_x000D_
Just ran into this syntax problem on a CentOS 7 machine.
On a very old Ubuntu machine running mail
, the syntax for a nicely composed email is
echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"
However on a CentOS 7 box which came with mailx
installed, it's quite different:
echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"
Consulting man mail
indicates that -r
is deprecated and the 'From' sender address should now be set directly using -S "variable=value"
.
In these and subsequent examples, I'm defining
$sender
as"Sender Name <[email protected]>"
and$recipients
as"[email protected]"
as I do in my bash script.
You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).
This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)
To get around this, I used a method which pipes the generated output through tr
before passing to mail
, and also specifies the charset of the email:
echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"
In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):
LANG="en_GB.UTF8" ; export LANG ;
(An alternate method of setting locales for cronjobs is discussed here)
More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.
Another way:
Don't set the height
attribute of the div
, but instead use padding:
to achieve the effect. Similarly to line-height, it only works if you have one line of text. Although this way, if you have more content, the text will still be centered, but the div itself will be slightly larger.
So instead of going with:
div {
height: 120px;
line-height: 120px;
}
You can say:
div {
padding: 60px 0; // Maybe 60 minus font-size divided by two, if you want to be exact
}
This will set the top and bottom padding
of the div
to 60px
, and the left and right padding
to zero, making the div
120 pixels (plus the height of your font) high, and placing the text vertically centered in the div.
I have same Issue, fixed by Adding @EnableMongoRepositories("in.topthree.util")
package in.topthree.core;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import in.topthree.util.Student;
@SpringBootApplication
@EnableMongoRepositories("in.topthree.util")
public class Run implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Run.class, args);
System.out.println("Run");
}
@Autowired
private Process pr;
@Override
public void run(String... args) throws Exception {
pr.saveDB(new Student("Testing", "FB"));
System.exit(0);
}
}
And my Repository is:
package in.topthree.util;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface StudentMongo extends MongoRepository<Student, Integer> {
public Student findByUrl(String url);
}
Now Its Working
The value is the same even though the printed representation is not what you expect:
decimal d = (decimal )1200.00;
Console.WriteLine(Decimal.Parse("1200") == d); //True
First, array_length
should be an integer and not a string:
array_length = len(array_dates)
Second, your for
loop should be constructed using range
:
for i in range(array_length): # Use `xrange` for python 2.
Third, i
will increment automatically, so delete the following line:
i += 1
Note, one could also just zip
the two lists given that they have the same length:
import csv
dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']
csv_file_patch = '/path/to/filename.csv'
with open(csv_file_patch, 'w') as fout:
csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
result_array = zip(dates, urls)
csv_file.writerows(result_array)
I am not familiar with JXL and but we use POI. POI is well maintained and can handle both the binary .xls format and the new xml based format that was introduced in Office 2007.
CSV files are not excel files, they are text based files, so these libraries don't read them. You will need to parse out a CSV file yourself. I am not aware of any CSV file libraries, but I haven't looked either.
Another recursive approach:
# change directory to target folder:
cd /Volumes/path/to/folder
# find all things of type "f" (file),
# then pipe "|" each result as an argument (xargs -0)
# to the "xattr -c" command:
find . -type f -print0 | xargs -0 xattr -c
# Sometimes you may have to use a star * instead of the dot.
# The dot just means "here" (whereever your cd'd to
find * -type f -print0 | xargs -0 xattr -c
I think what you want is mapply. You could apply the function to all columns, and then just drop the columns you don't want. However, if you are applying different functions to different columns, it seems likely what you want is mutate, from the dplyr package.
// $scope.dateField="value" in ctrl
<div ng-bind="dateField | date:'MM/dd/yyyy'"></div>
I found that xfig
did an excellent job:
pstoedit -f fig foo.pdf foo.fig
xfig foo.fig
export to svg
It did much better job than inkscape. Actually it was probably pdtoedit that did it.
If you'd like to know what is the numeric version of FireFox you can use the following snippet:
var match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
var ver = match ? parseInt(match[1]) : 0;
Possible ways to achieve this:
top
The top command is the traditional way to view your system’s resource usage and see the processes that are taking up the most system resources. Top displays a list of processes, with the ones using the most CPU at the top.
ps
The ps command lists running processes. The following command lists all processes running on your system:
ps -A
You could also pipe the output through grep to search for a specific process without using any other commands. The following command would search for the Firefox process:
ps -A | grep firefox
The most common way of passing signals to a program is with the kill command.
kill PID_of_target_process
lsof
List of all open files and the processes that opened them.
lsof -i -P | grep -i "listen"
kill -9 PID
or
lsof -i tcp:3000
I just tested in MySQL v5.0.6 and the datetime column accepted null without issue.
If you're looking for an example of an NP-complete problem then I suggest you take a look at 3-SAT.
The basic premise is you have an expression in conjunctive normal form, which is a way of saying you have a series of expressions joined by ORs that all must be true:
(a or b) and (b or !c) and (d or !e or f) ...
The 3-SAT problem is to find a solution that will satisfy the expression where each of the OR-expressions has exactly 3 booleans to match:
(a or !b or !c) and (!a or b or !d) and (b or !c or d) ...
A solution to this one might be (a=T, b=T, c=F, d=F). However, no algorithm has been discovered that will solve this problem in the general case in polynomial time. What this means is that the best way to solve this problem is to do essentially a brute force guess-and-check and try different combinations until you find one that works.
What's special about the 3-SAT problem is that ANY NP-complete problem can be reduced to a 3-SAT problem. This means that if you can find a polynomial-time algorithm to solve this problem then you get $1,000,000, not to mention the respect and admiration of computer scientists and mathematicians around the world.
The definition
const int const_value = 5;
does not always define a constant value. Some compilers (for example tcc 0.9.26) just allocate memory identified with the name "const_value". Using the identifier "const_value" you can not modify this memory. But you still could modify the memory using another identifier:
const int const_value = 5;
int *mutable_value = (int*) &const_value;
*mutable_value = 3;
printf("%i", const_value); // The output may be 5 or 3, depending on the compiler.
This means the definition
#define CONST_VALUE 5
is the only way to define a constant value which can not be modified by any means.
I feel it would be helpful for someone who is looking for passing the array in a query string to a servlet. I tested below query string and was able to get the array values using req.getgetParameterValues(); method. Below is the query string I passed through browser.
http://localhost:8080/ServletsTutorials/*.html?
myname=abc&initial=xyz&checkbox=a&checkbox=b
checkbox is my parameter array here.
try this easy
_x000D_
.btn-circle span {_x000D_
top: 0;_x000D_
_x000D_
position: absolute;_x000D_
font-size: 18px;_x000D_
text-align: center;_x000D_
text-decoration: none;_x000D_
-webkit-animation:spin 4s linear infinite;_x000D_
-moz-animation:spin 4s linear infinite;_x000D_
animation:spin 4s linear infinite;_x000D_
}_x000D_
_x000D_
.btn-circle span :hover {_x000D_
color :silver;_x000D_
}_x000D_
_x000D_
_x000D_
/* rotate 360 key for refresh btn */_x000D_
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }_x000D_
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }_x000D_
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
_x000D_
<button type="button" class="btn btn-success btn-circle" ><span class="glyphicon">↻</span></button>
_x000D_
The answer from @gunn is correct, target="_blank
makes the link open in a new tab.
But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer"
.
<a style={{display: "table-cell"}} href = "someLink" target = "_blank"
rel = "noopener noreferrer">text</a>
I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )
Deleting and restoring the entire solution from the repository resolved the issue for me. I didn't find this solution listed in any of the other answers, so thought it might help someone.
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Like this:
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
Before Java6 it was recommended to write:
String[] a = list.toArray(new String[list.size()]);
because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
If your list is not properly typed you need to do a cast before calling toArray. Like this:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
string texts[] = {"Apple", "Banana", "Orange"};
for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )
{
cout << "value of a: " << texts[a] << endl;
}
Nope. Totally a wrong way of iterating through an array. sizeof(texts)
is not equal to the number of elements in the array!
The modern, C++11 ways would be to:
std::array
if you want an array whose size is known at compile-time; orstd::vector
if its size depends on runtimeThen use range-for when iterating.
#include <iostream>
#include <array>
int main() {
std::array<std::string, 3> texts = {"Apple", "Banana", "Orange"};
// ^ An array of 3 elements with the type std::string
for(const auto& text : texts) { // Range-for!
std::cout << text << std::endl;
}
}
You may ask, how is std::array
better than the ol' C array? The answer is that it has the additional safety and features of other standard library containers, mostly closely resembling std::vector
. Further, The answer is that it doesn't have the quirks of decaying to pointers and thus losing type information, which, once you lose the original array type, you can't use range-for or std::begin/end
on it.
document.all
works in Chrome now (not sure when since), but I've been missing it the last 20 years.... Simply a shorter method name than the clunky document.getElementById
. Not sure if it works in Firefox, those guys never had any desire to be compatible with the existing web, always creating new standards instead of embracing the existing web.
just to improve answer given above: if you are getting NullPointerEx:
you can also use getApplicationContext() without context
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.
For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner
Here is a wikipedia article explaining what map-reduce
is all about
Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.
Personally, found this link quite useful to understand the concept
Copying the explanation provided in the blog (In case the link goes stale)
Finding Friends
MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.
I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:
3 : the 3 : and 3 : you 4 : then 4 : what 4 : when 5 : steve 5 : where 8 : savannah 8 : research
They get grouped as:
3 : [the, and, you] 4 : [then, what, when] 5 : [steve, where] 8 : [savannah, research]
Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:
3 : 3 4 : 3 5 : 2 8 : 2
The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...
The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.
The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of
1
. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):
Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.
Assume the friends are stored as Person->[List of Friends], our friends list is then:
A -> B C D B -> A C D E C -> A B D E D -> A B C E E -> B C D
Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:
For map(A -> B C D) : (A B) -> B C D (A C) -> B C D (A D) -> B C D For map(B -> A C D E) : (Note that A comes before B in the key) (A B) -> A C D E (B C) -> A C D E (B D) -> A C D E (B E) -> A C D E For map(C -> A B D E) : (A C) -> A B D E (B C) -> A B D E (C D) -> A B D E (C E) -> A B D E For map(D -> A B C E) : (A D) -> A B C E (B D) -> A B C E (C D) -> A B C E (D E) -> A B C E And finally for map(E -> B C D): (B E) -> B C D (C E) -> B C D (D E) -> B C D Before we send these key-value pairs to the reducers, we group them by their keys and get: (A B) -> (A C D E) (B C D) (A C) -> (A B D E) (B C D) (A D) -> (A B C E) (B C D) (B C) -> (A B D E) (A C D E) (B D) -> (A B C E) (A C D E) (B E) -> (A C D E) (B C D) (C D) -> (A B C E) (A B D E) (C E) -> (A B D E) (B C D) (D E) -> (A B C E) (B C D)
Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.
The result after reduction is:
(A B) -> (C D) (A C) -> (B D) (A D) -> (B C) (B C) -> (A D E) (B D) -> (A C E) (B E) -> (C D) (C D) -> (A B E) (C E) -> (B D) (D E) -> (B C)
Now when D visits B's profile, we can quickly look up
(B D)
and see that they have three friends in common,(A C E)
.
Try using the Worksheet.Protect
method, like so:
Sub ProtectActiveSheet()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True, Password="SamplePassword"
End Sub
You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.
Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.
I myself work in a heavily restricted server environment and unfortunately none of the solutions here are working for me. There may be no glove solution that fits all, but I figured out a swift workaround by reading the terminal output of pip freeze within my script and storing the modules labels and versions in a dictionary.
import os
os.system('pip freeze > tmpoutput')
with open('tmpoutput', 'r') as f:
modules_version = f.read()
module_dict = {item.split("==")[0]:item.split("==")[-1] for item in modules_versions.split("\n")}
Retrieve your module's versions through passing the module label key, e.g.:
>> module_dict["seaborn"]
'0.9.0'
There will be two Web.config files. I think you may have confused with those two files.
Check this image:
In this image you can see two Web.config files. You should add your constants to the one which is in the project folder not in the views folder
Hope this may help you
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
You could use assign
with a dict of column names and values.
In [1069]: df.assign(**{'col_new_1': np.nan, 'col2_new_2': 'dogs', 'col3_new_3': 3})
Out[1069]:
col_1 col_2 col2_new_2 col3_new_3 col_new_1
0 0 4 dogs 3 NaN
1 1 5 dogs 3 NaN
2 2 6 dogs 3 NaN
3 3 7 dogs 3 NaN
After a lot of search and tests i found the solution : if you are in windows :
1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools
$ show data_directory;
result :
------------------------ - D:/PG_DATA/data - ------------------------
2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"
and open a command prompt (CMD) and execute this command :
pg_ctl -D "D:\PSG_SQL\data" restart
This should do it.
Try using copy()
function instead of move_uploaded_file()
. It worked for me.
copy($_FILES['file']['tmp_name'], $path);
I would be inclined to use a class in your css that alters the border style or border width when the button is depressed, so it gives the appearance of a toggle button.
C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]
* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.
Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.
A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.
Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]
Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]
Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.
Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]
More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.
Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]
More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]
Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]
C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]
C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]
C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]
C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]
Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.
Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format
throughout all examples.
Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]
C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)
C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]
Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.
The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".
C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]
The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]
C++11/14/17/… References:
The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.
The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.
Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.
The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.
The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.
cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.
Note: Some information contained within these books may not be up-to-date or no longer considered best practice.
The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.
Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]
Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.
Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.
Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.
The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.
Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const
), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.
Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.
See man git-add
:
-f, --force
Allow adding otherwise ignored files.
So run this
git add --force my/ignore/file.foo
Try to export the correct profile i.e. $ export AWS_PROFILE="default"
If you only have a default profile make sure the keys are correct and rerun aws configure
in windows form application I do this, Right-click on Project->Properties->Build->Check Prefer 32-bit checkbox. Thanks all
If you want to use another method after you need something like this:
( str.strip || str ).split(',')
This way you can strip and still do something after :)
"12345".each_char.map(&:to_i)
each_char
does basically the same as split('')
: It splits a string into an array of its characters.
hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..
You'd better not transpose the data.frame while the name column is in it - all numeric values will then be turned into strings!
Here's a solution that keeps numbers as numbers:
# first remember the names
n <- df.aree$name
# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))
str(df.aree) # Check the column types
Add it to your project/index.php
file, and it will work on all over your site.
date_default_timezone_set('Asia/kabul');
Use textract.
It supports many types of files including PDFs
import textract
text = textract.process("path/to/file.extension")
Using IReadOnlyCollection<T>
or IReadOnlyList<T>
in the method signature instead of IEnumerable<T>
, has the advantage of making explicit that you might need to check the count before iterating, or to iterate multiple times for some other reason.
However they have a huge downside that will cause problems if you try to refactor your code to use interfaces, for instance to make it more testable and friendly to dynamic proxying. The key point is that IList<T>
does not inherit from IReadOnlyList<T>
, and similarly for other collections and their respective read-only interfaces. (In short, this is because .NET 4.5 wanted to keep ABI compatibility with earlier versions. But they didn't even take the opportunity to change that in .NET core.)
This means that if you get an IList<T>
from some part of the program and want to pass it to another part that expects an IReadOnlyList<T>
, you can't! You can however pass an IList<T>
as an IEnumerable<T>
.
In the end, IEnumerable<T>
is the only read-only interface supported by all .NET collections including all collection interfaces. Any other alternative will come back to bite you as you realize that you locked yourself out from some architecture choices. So I think it's the proper type to use in function signatures to express that you just want a read-only collection.
(Note that you can always write a IReadOnlyList<T> ToReadOnly<T>(this IList<T> list)
extension method that simple casts if the underlying type supports both interfaces, but you have to add it manually everywhere when refactoring, where as IEnumerable<T>
is always compatible.)
As always this is not an absolute, if you're writing database-heavy code where accidental multiple enumeration would be a disaster, you might prefer a different trade-off.
This works for me:
select date_format(date(starttime),'%Y-%m-%d') from data
where date(starttime) >= date '2012-11-02';
Note the format string '%Y-%m-%d' and the format of the input date.
You can download the free Name Manager addin developed by myself and Jan Karel Pieterse from http://www.decisionmodels.com/downloads.htm This enables many name operations that the Excel 2007 Name manager cannot handle, including changing scope of names.
In VBA:
Sub TestName()
Application.Calculation = xlManual
Names("TestName").Delete
Range("Sheet1!$A$1:$B$2").Name = "Sheet1!TestName"
Application.Calculation = xlAutomatic
End Sub
You cannot have spaces and tabs in the tag (i.e., name) of an XML elements, see the specs: http://www.w3.org/TR/REC-xml/#NT-STag. Beside alphanumeric characters, colon, underscore, dash and dot characters are allowed in a name, and the first letter cannot be a dash or a dot. Certain unicode characters are also permitted, without actually double-checking, I'd say that these are international letters.
Assuming that empty spaces and all leading and trailing white spaces should be removed:
import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }
Because :
len("") // is 0
len(" ") // one empty space is 1
len(" ") // two empty spaces is 2
Swift 4
Don't forget to write ".first as? CustomView".
if let customView = Bundle.main.loadNibNamed("myXib", owner: self, options: nil)?.first as? CustomView {
self.view.addSubview(customView)
}
If you want to use anywhere
The Best Solution is Robert Gummesson's answer.
extension UIView {
class func fromNib<T: UIView>() -> T {
return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)![0] as! T
}
}
Then call it like this:
let myCustomView: CustomView = UIView.fromNib()
Building on the previous answers, you can leverage the fact that True
is -1 and False
is 0 and shorten your code like this:
Sub Button167_Click()
Range("Y12").Value = _
Abs(Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0)
End Sub
If the checkbox is checked, .Value
= 1.
Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0
returns True
.
Applying the Abs
function converts True
to 1
.
If the checkbox is unchecked, .Value
= -4146.
Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value > 0
returns False
.
Applying the Abs
function converts False
to 0
.
The most obvious solution is to forbid y-coordinate changes in your subclass.
override var contentOffset: CGPoint {
get {
return super.contentOffset
}
set {
super.contentOffset = CGPoint(x: newValue.x, y: 0)
}
}
This is the only suitable solution in situations when:
You can use the fgets()
function to read the file line by line:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
fclose($handle);
} else {
// error opening the file.
}
This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.
You'll have to do:
= A1 & TEXT(A2, "mm/dd/yyyy")
The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.
Now, you could have a user-defined function:
public function AsDisplayed(byval c as range) as string
AsDisplayed = c.Text
end function
and then
= A1 & AsDisplayed(A2)
But then there's a bug (feature?) in Excel because of which the .Text
property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE
instead of what they should.
That is, it's bad either way.
MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:
INSERT INTO `receiving_table`
(id,
first_name,
last_name)
VALUES
(1002,'Charles','Babbage'),
(1003,'George', 'Boole'),
(1001,'Donald','Chamberlin'),
(1004,'Alan','Turing'),
(1005,'My','Widenius');
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}