Any number of files in a directory are a single package; symbols declared in one file are available to the others without any import
s or qualifiers. All of the files do need the same package foo
declaration at the top (or you'll get an error from go build
).
You do need GOPATH
set to the directory where your pkg
, src
, and bin
directories reside. This is just a matter of preference, but it's common to have a single workspace for all your apps (sometimes $HOME
), not one per app.
Normally a Github path would be github.com/username/reponame
(not just github.com/xxxx
). So if you want to have main
and another package, you may end up doing something under workspace/src
like
github.com/
username/
reponame/
main.go // package main, importing "github.com/username/reponame/b"
b/
b.go // package b
Note you always import with the full github.com/...
path: relative imports aren't allowed in a workspace. If you get tired of typing paths, use goimports
. If you were getting by with go run
, it's time to switch to go build
: run
deals poorly with multiple-file main
s and I didn't bother to test but heard (from Dave Cheney here) go run
doesn't rebuild dirty dependencies.
Sounds like you've at least tried to set GOPATH to the right thing, so if you're still stuck, maybe include exactly how you set the environment variable (the command, etc.) and what command you ran and what error happened. Here are instructions on how to set it (and make the setting persistent) under Linux/UNIX and here is the Go team's advice on workspace setup. Maybe neither helps, but take a look and at least point to which part confuses you if you're confused.
@Hesam 's answer is correct, CameraPreview
will work in all portrait devices, but if the device is in landscape mode or in multi-window mode, this code is working perfect, just replace onMeasure()
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
int rotation = ((Activity) mContext).getWindowManager().getDefaultDisplay().getRotation();
if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {//portrait
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, height, width);
} else
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);//landscape
if (mPreviewSize == null) return;
float ratio;
if (mPreviewSize.height >= mPreviewSize.width) {
ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
} else ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && ((Activity) mContext).isInMultiWindowMode()) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ||
!(Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
setMeasuredDimension(width, (int) (width / ratio));
} else {
setMeasuredDimension((int) (height / ratio), height);
}
} else {
if ((Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation)) {
Log.e("---", "onMeasure: " + height + " - " + width * ratio);
//2264 - 2400.0 pix c -- yes
//2240 - 2560.0 samsung -- yes
//1582 - 1440.0 pix 2 -- no
//1864 - 2048.0 sam tab -- yes
//848 - 789.4737 iball -- no
//1640 - 1600.0 nexus 7 -- no
//1093 - 1066.6667 lenovo -- no
//if width * ratio is > height, need to minus toolbar height
if ((width * ratio) < height)
setMeasuredDimension(width, (int) (width * ratio));
else
setMeasuredDimension(width, (int) (width * ratio) - toolbarHeight);
} else {
setMeasuredDimension((int) (height * ratio), height);
}
}
requestLayout();
}
Float:left
... Although I presume you want the input to be styled not the div?
.button input{
color:#08233e;float:left;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:14px;
background:url(overlay.png) repeat-x center #ffcc00;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
}
.button input:hover{
background-color:rgba(255,204,0,0.8);
}
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
Answer: NO
Here's Why ... I think a key reason for having stored procs in a database is that you're executing SP code in the same process as the SQL engine. This makes sense for database engines designed to work as a network connected service but the imperative for SQLite is much less given that it runs as a DLL in your application process rather than in a separate SQL engine process. So it makes more sense to implement all your business logic including what would have been SP code in the host language.
You can however extend SQLite with your own user defined functions in the host language (PHP, Python, Perl, C#, Javascript, Ruby etc). You can then use these custom functions as part of any SQLite select/update/insert/delete. I've done this in C# using DevArt's SQLite to implement password hashing.
The following assumes that your hours and minutes are stored as ints in variables named hh
and mm
respectively.
if ((hh > START_HOUR || (hh == START_HOUR && mm >= START_MINUTE)) &&
(hh < END_HOUR || (hh == END_HOUR && mm <= END_MINUTE))) {
...
}
The fastest way.
Make sure you don't have ROOT app deployed, undeploy if you have one
Rename your war to ROOT.war, deploy, thats all, no configuration changes needed
IF the table is alias t
SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM temp1 as t
You need to wait for Javascript and jQuery to finish loading.
Execute Javascript to check if jQuery.active
is 0
and document.readyState
is complete
, which means the JS and jQuery load is complete.
public boolean waitForJStoLoad() {
WebDriverWait wait = new WebDriverWait(driver, 30);
// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return ((Long)executeJavaScript("return jQuery.active") == 0);
}
catch (Exception e) {
return true;
}
}
};
// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return executeJavaScript("return document.readyState")
.toString().equals("complete");
}
};
return wait.until(jQueryLoad) && wait.until(jsLoad);
}
I had a similar issue when not using inline
for my global function that was included in two places.
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
I too had this problem. My solution was:
sc.setSoLinger(true, 10);
COPY FROM A WEBSITE -->By using the setSoLinger()
method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.
Maybe it is not the answer to everybody but to some people.
This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:
git checkout some-branch # where some-branch can be replaced by any other branch
git branch base-branch -D # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch # recreating branch with correct commits
Note: You can combine these all by putting && between them
Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?
Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.
Ex:
git checkout feature-old # some branch with the extra commits
git log # gives commits (write down the id of the ones you want)
git checkout base-branch # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch
Now feature-new is your branch without the extra (possibly bad) commits!
function unzip {
param (
[string]$archiveFilePath,
[string]$destinationPath
)
if ($archiveFilePath -notlike '?:\*') {
$archiveFilePath = [System.IO.Path]::Combine($PWD, $archiveFilePath)
}
if ($destinationPath -notlike '?:\*') {
$destinationPath = [System.IO.Path]::Combine($PWD, $destinationPath)
}
Add-Type -AssemblyName System.IO.Compression
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archiveFile = [System.IO.File]::Open($archiveFilePath, [System.IO.FileMode]::Open)
$archive = [System.IO.Compression.ZipArchive]::new($archiveFile)
if (Test-Path $destinationPath) {
foreach ($item in $archive.Entries) {
$destinationItemPath = [System.IO.Path]::Combine($destinationPath, $item.FullName)
if ($destinationItemPath -like '*/') {
New-Item $destinationItemPath -Force -ItemType Directory > $null
} else {
New-Item $destinationItemPath -Force -ItemType File > $null
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($item, $destinationItemPath, $true)
}
}
} else {
[System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($archive, $destinationPath)
}
}
Using:
unzip 'Applications\Site.zip' 'C:\inetpub\wwwroot\Site'
I just found a solution that I think works really well and gets around all of the pitfalls of custom symbols. The main problem with the li:before solution is that if list-items are longer than one line will not indent properly after the first line of text. By using text-indent with a negative padding we can circumvent that problem and have all the lines aligned properly:
ul{
padding-left: 0; // remove default padding
}
li{
list-style-type: none; // remove default styles
padding-left: 1.2em;
text-indent:-1.2em; // remove padding on first line
}
li::before{
margin-right: 0.5em;
width: 0.7em; // margin-right and width must add up to the negative indent-value set above
height: 0.7em;
display: inline-block;
vertical-align: middle;
border-radius: 50%;
background-color: orange;
content: ' '
}
Take a look at the man page of the pt-deadlock-logger
utility:
brew install percona-toolkit
pt-deadlock-logger --ask-pass server_name
It extracts information from the engine innodb status
mentioned above and also
it can be used to create a daemon
which runs every 30 seconds.
The general way to find any type is by example. The beauty of typescript is that you have access to all types, so long as you have the correct @types/
files.
To answer this myself I just thought of a component react uses that has the children
prop. The first thing that came to mind? How about a <div />
?
All you need to do is open vscode and create a new .tsx
file in a react project with @types/react
.
import React from 'react';
export default () => (
<div children={'test'} />
);
Hovering over the children
prop shows you the type. And what do you know -- Its type is ReactNode
(no need for ReactNode[]
).
Then if you click into the type definition it brings you straight to the definition of children
coming from DOMAttributes
interface.
// node_modules/@types/react/index.d.ts
interface DOMAttributes<T> {
children?: ReactNode;
...
}
Note: This process should be used to find any unknown type! All of them are there just waiting for you to find them :)
You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.
How do I write asynchronous functions for Node?
Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.
How should I implement error event handling correctly
Generally API's give you a callback with an err as the first argument. For example
database.query('something', function(err, result) {
if (err) handle(err);
doSomething(result);
});
Is a common pattern.
Another common pattern is on('error')
. For example
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
Edit:
var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};
The above function when called as
async_function(42, function(val) {
console.log(val)
});
console.log(43);
Will print 42
to the console asynchronously. In particular process.nextTick
fires after the current eventloop callstack is empty. That call stack is empty after async_function
and console.log(43)
have run. So we print 43 followed by 42.
You should probably do some reading on the event loop.
quoting @user2993582's answer
export PATH=$PATH:$ANDROID_HOME/bin
The 'bin' part has changed and it should be
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
It waits for client.GetAsync("aaaaa");
, but doesn't wait for result = Print(x)
Try responseTask.ContinueWith(x => result = Print(x)).Wait()
--EDIT--
Task responseTask = Task.Run(() => {
Thread.Sleep(1000);
Console.WriteLine("In task");
});
responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
responseTask.Wait();
Console.WriteLine("End");
Above code doesn't guarantee the output:
In task
In ContinueWith
End
But this does (see the newTask
)
Task responseTask = Task.Run(() => {
Thread.Sleep(1000);
Console.WriteLine("In task");
});
Task newTask = responseTask.ContinueWith(t=>Console.WriteLine("In ContinueWith"));
newTask.Wait();
Console.WriteLine("End");
Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.
varLines = Split(.responsetext, """,""")
strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)
yes you can ;-)
the simplest way is using this ->http://www.androidfanatic.com/community-forums.html?func=view&catid=9&id=2248
The old link is dead it was for a Debian install script There is an app for that in the android market but you will need root
add tells git to start tracking a file.
commit commits your current changes on your local repository
push pushes you local repo upstream.
pill ${this.props.styleName}
will get "pill undefined" when you don't set the props
I prefer
className={ "pill " + ( this.props.styleName || "") }
or
className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }
While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).
Adding the following css fixed the problem for me:
#myListView.k-widget, #catalog-items.k-widget * {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
To access another drive, type the drive's letter, followed by ":".
D:
Then enter:
cd d:\windows\movie
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).
You can just compare the boolean array. For example
X = [True, False, True]
then
Y = X == False
would give you
Y = [False, True, False]
You should specify it in your tmux config file (~/.tmux.conf
), for example:
new mocp
neww mutt
new -d
neww
neww
(opens one session with 2 windows with mocp launched in first and mutt in second, and another detached session with 3 empty windows).
I also issued this problem, and the server admins solved it by following the same solution as indu_teja proposed in http://www.sqlservercentral.com/Forums/Topic546566-146-1.aspx
The solution proposed by indu_teja says :
If you get this "SSPI Context Error". The issues we face are:
- We will not be able to connect to SQL Server remotely.
- However we will be able to connect to server with local account.
CAUSE: The issue might be becasue of no proper sync happenign fro the SPNs in Active directory.
RESOLUTION:
- You need to reset SPN. Use the synytax "SET SPN". You can check the syntax in net once.
- Change your sql server service account from domain account to Local account, recycle sql, and then reset again with your domain account and recycle sql server.
I personally think that sizeof(a) / sizeof(*a) looks cleaner.
I also prefer to define it as a macro:
#define NUM(a) (sizeof(a) / sizeof(*a))
Then you can use it in for-loops, thusly:
for (i = 0; i < NUM(a); i++)
Use wmic computersystem get TotalPhysicalMemory
. E.g.:
C:\>wmic computersystem get TotalPhysicalMemory
TotalPhysicalMemory
4294500352
This might work for you:
printf "{new\nto\nlinux}" | paste -sd' '
{new to linux}
or:
printf "{new\nto\nlinux}" | tr '\n' ' '
{new to linux}
or:
printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
if you are getting this error
.............ERROR! The server quit without updating PID file
Try this
Go to /Applications/XAMPP/xamppfiles/var/mysql/
if there is no file with the name Your_Username.local.pid
Your_Username should replace with your Mac Username
Create a file with this name
Then try
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
its worked for me
In CLI
$ webpack --version
webpack-cli 4.1.0
webpack 5.3.2
In Code (node runtime)
process.env.npm_package_devDependencies_webpack // ^5.3.2
or
process.env.npm_package_dependencies_webpack // ^5.3.2
In Plugin
compiler.webpack.version // 5.3.2
Drop the hash - that's for identifying the id attribute.
The following will return true if the JTextField "name" does not contain text:
name.getText().isEmpty
/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
Supports :
You can find the latest features of the .NET Framework 4.5 beta here
It breaks down the changes to the framework in the following categories:
You sound like you are more interested in the Web section as this shows the changes to ASP.NET 4.5. The rest of the changes can be found under the other headings.
You can also see some of the features that were new when the .NET Framework 4.0 was shipped here.
setTimeout(function(){
}, 500);
Place your code inside of the { }
500
= 0.5 seconds
2200
= 2.2 seconds
etc.
update Hotels set Discount=30 where Hotelid >= 1 and Hotelid <= 5504
I made a Windows context item to fast delete node_modules or other folders. I use it when Windows doesn't delete a folder because of some invalid chars in the directory path.
Install rimraf => npm install rimraf -g
Create a new file named delete.bat
, set the content as below and copy it into c:\windows\system32\
delete.bat:
@ECHO OFF
ECHO.
ECHO %CD%
ECHO.
ECHO Are you sure to delete the folder with Rimraf?
PAUSE
SET FOLDER=%CD%
CD /
rimraf "%FOLDER%"
rem DEL /F/Q/S "%FOLDER%" > NUL
rem RMDIR /Q/S "%FOLDER%"
EXIT
Run fast-delete.reg file to import into registry.
Done!
I tested the accepted answer AND @thewolf's fastest solution against a very basic loop and the loop was faster than both:
import time
import operator
d = {"a"+str(i): i for i in range(1000000)}
def t1(dct):
mx = float("-inf")
key = None
for k,v in dct.items():
if v > mx:
mx = v
key = k
return key
def t2(dct):
v=list(dct.values())
k=list(dct.keys())
return k[v.index(max(v))]
def t3(dct):
return max(dct.items(),key=operator.itemgetter(1))[0]
start = time.time()
for i in range(25):
m = t1(d)
end = time.time()
print ("Iterating: "+str(end-start))
start = time.time()
for i in range(25):
m = t2(d)
end = time.time()
print ("List creating: "+str(end-start))
start = time.time()
for i in range(25):
m = t3(d)
end = time.time()
print ("Accepted answer: "+str(end-start))
results:
Iterating: 3.8201940059661865
List creating: 6.928712844848633
Accepted answer: 5.464320182800293
As far I think I understood your question I believe that u can simply declare your variable inside "DECLARE" and then after the "begin" u can use 'select into " you variable" ' statement. the code would look like this:
DECLARE
YourVar varchar(50);
begin
select ID into YourVar from table
where ...
You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:
"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html
You should either write or download a little tool that will allow you to generate config files from placeholder config files.
Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.
e.g. my nginx source config file looks like this:
location / {
try_files $uri /routing.php?$args;
fastcgi_pass unix:%phpfpm.socket%/php-fpm-www.sock;
include %mysite.root.directory%/conf/fastcgi.conf;
}
And then I have a config file with the variables defined:
phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite
And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:
<?php
require_once('path.php');
$filesToGenerate = array(
'conf/nginx.conf' => 'autogen/nginx.conf',
'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
'conf/my.cnf' => 'autogen/my.cnf',
);
$environment = 'amazonec2';
if ($argc >= 2){
$environmentRequired = $argv[1];
$allowedVars = array(
'amazonec2',
'macports',
);
if (in_array($environmentRequired, $allowedVars) == true){
$environment = $environmentRequired;
}
}
else{
echo "Defaulting to [".$environment."] environment";
}
$config = getConfigForEnvironment($environment);
foreach($filesToGenerate as $inputFilename => $outputFilename){
generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}
function getConfigForEnvironment($environment){
$config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
$configWithMarkers = array();
foreach($config[$environment] as $key => $value){
$configWithMarkers['%'.$key.'%'] = $value;
}
return $configWithMarkers;
}
function generateConfigFile($inputFilename, $outputFilename, $config){
$lines = file($inputFilename);
if($lines === FALSE){
echo "Failed to read [".$inputFilename."] for reading.";
exit(-1);
}
$fileHandle = fopen($outputFilename, "w");
if($fileHandle === FALSE){
echo "Failed to read [".$outputFilename."] for writing.";
exit(-1);
}
$search = array_keys($config);
$replace = array_values($config);
foreach($lines as $line){
$line = str_replace($search, $replace, $line);
fwrite($fileHandle, $line);
}
fclose($fileHandle);
}
?>
And then deployConfig.ini looks something like:
[global]
;global variables go here.
[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory = /var/run
nginx.user = nginx
[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory = /opt/local/var/run
nginx.user = _www
You can do this in jquery by setting the attribute disabled to 'disabled'.
$(this).prop('disabled', true);
I have made a simple example http://jsfiddle.net/4gnXL/2/
You can use ElementRef as shown below,
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[move]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight); //<<<===here
console.log('width---' + this.el.nativeElement.offsetWidth); //<<<===here
}
}
Same way you can use it within component itself wherever you need it.
When a folder is created, many Linux filesystems allocate 4096 bytes to store some metadata about the directory itself. This space is increased by a multiple of 4096 bytes as the directory grows.
du command (with or without -b option) take in count this space, as you can see typing:
mkdir test && du -b test
you will have a result of 4096 bytes for an empty dir. So, if you put 2 files of 10000 bytes inside the dir, the total amount given by du -sb would be 24096 bytes.
If you read carefully the question, this is not what asked. The questioner asked:
the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes
that in the example above should be 20000 bytes, not 24096.
So, the correct answer IMHO could be a blend of Nelson answer and hlovdal suggestion to handle filenames containing spaces:
find . -type f -print0 | xargs -0 stat --format=%s | awk '{s+=$1} END {print s}'
I have used in Google Sheets
={sheetname!columnnamefrom:columnnameto}
Example:
={sheet1!A:A}
={sheet2!A4:A20}
From http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/:
SELECT CUST, PRODUCT, QTY
FROM Product) up
PIVOT
( SUM(QTY) FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)) AS pvt) p
UNPIVOT
(QTY FOR PRODUCT IN (VEG, SODA, MILK, BEER, CHIPS)
) AS Unpvt
GO
Try this
var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);
var i = 0, req_index = "";
$.each(json, function(index, value){
if(index == 'key2'){
req_index = i;
}
i++;
});
alert(req_index);
InvariantCulture
is similar to en-US
, so i would use the correct CultureInfo
instead:
var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);
And what about when the culture is en-us? Will I have to code for every single language there is out there?
If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US"))
.
For me this worked:
int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());
MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
lp.setMargins(0,0,imgCarMarginRightPx,0);
imgCar.setLayoutParams(lp);
You could use a regular expression like this
If Regex.IsMatch(number, "^[0-9 ]+$") Then
...
End If
A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.
I'll use this example to simulate a coroutine that will raise exceptions, sometimes -
import asyncio
import random
async def a_flaky_tsk(i):
await asyncio.sleep(i) # bit of fuzz to simulate a real-world example
if i % 2 == 0:
print(i, "ok")
else:
print(i, "crashed!")
raise ValueError
coros = [a_flaky_tsk(i) for i in range(10)]
await asyncio.gather(*coros)
outputs -
0 ok
1 crashed!
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
asyncio.run(main())
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
await asyncio.gather(*coros)
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
As you can see, the coros after index 1
never got to execute.
But await asyncio.wait(coros)
continues to execute tasks, even if some of them fail -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Ofcourse, this behavior can be changed for both by using -
asyncio.gather(..., return_exceptions=True)
or,
asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)
But it doesn't end here!
Notice:
Task exception was never retrieved
in the logs above.
asyncio.wait()
won't re-raise exceptions from the child tasks until you await
them individually. (The stacktrace in the logs are just messages, they cannot be caught!)
done, pending = await asyncio.wait(coros)
for tsk in done:
try:
await tsk
except Exception as e:
print("I caught:", repr(e))
Output -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
On the other hand, to catch exceptions with asyncio.gather()
, you must -
results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
if isinstance(result_or_exc, Exception):
print("I caught:", repr(result_or_exc))
(Same output as before)
There are two major purposes of hashing functions:
It's impossible to recommend a hash without knowing what you're using it for.
If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.
If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.
Here is a cheap linq trick.
SecureString sec = new SecureString();
string pwd = "abc123"; /* Not Secure! */
pwd.ToCharArray().ToList().ForEach(sec.AppendChar);
/* and now : seal the deal */
sec.MakeReadOnly();
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
Specify window "features" to the open
call:
window.open(url, windowName, "height=200,width=200");
When you specify a width/height, it will open it in a new window instead of a tab.
See https://developer.mozilla.org/en-US/docs/Web/API/Window.open#Position_and_size_features for all the possible features.
Currently, there is no cross browser, script-free way of styling a native date picker.
As for what's going on inside WHATWG/W3C... If this functionality does emerge, it will likely be under the CSS-UI standard or some Shadow DOM-related standard. The CSS4-UI wiki page lists a few appearance-related things that were dropped from CSS3-UI, but to be honest, there doesn't seem to be a great deal of interest in the CSS-UI module.
I think your best bet for cross browser development right now, is to implement pretty controls with JavaScript based interface, and then disable the HTML5 native UI and replace it. I think in the future, maybe there will be better native control styling, but perhaps more likely will be the ability to swap out a native control for your own Shadow DOM "widget".
It is annoying that this isn't available, and petitioning for standard support is always worthwhile. Though it does seem like jQuery UI's lead has tried and was unsuccessful.
While this is all very discouraging, it's also worth considering the advantages of the HTML5 date picker, and also why custom styles are difficult and perhaps should be avoided. On some platforms, the datepicker looks extremely different and I personally can't think of any generic way of styling the native datepicker.
Simply: DO NOT DO IT. Http Content within a HTTPS page is inherently insecure. Point. This is why IE shows a warning. Getting rid of the warning is a stupid hogwash approach.
Instead, a HTTPS page should only have HTTPS content. Make sure the content can be loaded via HTTPS, too, and reference it via https if the page is loaded via https. For external content this will mean loading and caching the elements locally so that they are available via https - sure. No way around that, sadly.
The warning is there for a good reason. Seriously. Spend 5 minutes thinking how you could take over a https shown page with custom content - you will be surprised.
Float each div and set clear;both for the row. No need to set widths if you dont want to. Works in Chrome 41,Firefox 37, IE 11
<div class="stack">
<div class="row">
<div class="col">
One
</div>
<div class="col">
Two
</div>
</div>
<div class="row">
<div class="col">
One
</div>
<div class="col">
Two
</div>
<div class="col">
Three
</div>
</div>
</div>
.stack .row {
clear:both;
}
.stack .row .col {
float:left;
border:1px solid;
}
You can use datetime.strftime
to get the time in Epoch form, using the %s
format string:
def expires():
future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
return int(future.strftime("%s"))
Note: This only works under linux, and this method doesn't work with timezones.
I'm facing the same issue.
The issue because of X-Code.
Solution: 1. Open X-code and accept user agreement (T&C). or 2. Restart your MAC, It will resolve automatically.
(oldSize * 3)/2 + 1
If you are using default constructor then initial size of ArrayList
will be 10
else you can pass the initial size of array while creating the object of ArrayList
.
Example: In case default constructor
List<String> list = new ArrayList<>();
list.size()
Example: In case parameterized constructor
List<String> list = new ArrayList<>(5);
list.size()
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
When you use a CASE
expression (not statement) you have to be aware of data type precedence. In this case you can't just set a DATETIME
to an empty string. Try it:
SELECT CONVERT(DATETIME, '');
One workaround is to present your date as a string:
CASE WHEN CONVERT(DATE, CreatedDate) = '1900-01-01' -- to account for accidental time
THEN ''
ELSE CONVERT(CHAR(10), CreatedDate, 120)
+ ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END
Or you could fiddle with the presentation stuff where it belongs, at the presentation tier.
Here is an example that works exactly as you seem to want:
DECLARE @d TABLE(CreatedDate DATETIME);
INSERT @d SELECT '19000101' UNION ALL SELECT '20130321';
SELECT d = CASE WHEN CreatedDate = '19000101'
THEN ''
ELSE CONVERT(CHAR(10), CreatedDate, 120)
+ ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END FROM @d;
Results:
d
-------------------
<-- empty string
2013-03-21 00:00:00
Goto SolutionExplorer (should be already visible, if not use menu: View->SolutionExplorer).
Find your .cxx file in the solution tree, right click on it and choose "Properties" from the popup menu. You will get window with your file's properties.
Using tree on the left side go to the "C++/Precompiled Headers" section. On the right side of the window you'll get three properties. Set property named "Create/Use Precompiled Header" to the value of "Not Using Precompiled Headers".
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Datetime formatting is performed by the org.joda.time.format.DateTimeFormatter class
. Three classes provide factory methods to create formatters, and this is one. The others are ISODateTimeFormat
and DateTimeFormatterBuilder
.
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MMM-dd");
LocalDate lDate = new LocalDate().parse("2005-nov-12",format);
final org.joda.time.LocalDate class
is an immutable datetime class representing a date without a time zone. LocalDate
is thread-safe and immutable, provided that the Chronology is as well. All standard Chronology classes supplied are thread-safe and immutable.
I use the multithread HTML5 Worker which will be able to abort an synchronous XMLHttpRequest pointing to an unresponsive URL. This does not block the browser.
C# in .NET 3.5 using System.DirectoryServices.AccountManagement.
bool valid = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials( username, password );
}
This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.
For anyone else getting
Nginx 403 error: directory index of [folder] is forbidden
when using index.php
while index.html
works perfectly and having included index.php
in the index in the server block of their site config in sites-enabled
server {
listen 80;
# this path MUST be exactly as docker-compose php volumes
root /usr/share/nginx/html;
index index.php
...
}
Make sure your nginx.conf file at /etc/nginx/nginx.conf
actually loads your site config in the http
block...
http {
...
include /etc/nginx/conf.d/*.conf;
# Load our websites config
include /etc/nginx/sites-enabled/*;
}
Look this http://iswift.org/cookbook/compare-2-dates
Get Dates:
// Get current date
let dateA = NSDate()
// Get a later date (after a couple of milliseconds)
let dateB = NSDate()
Using SWITCH Statement
// Compare them
switch dateA.compare(dateB) {
case .OrderedAscending : print("Date A is earlier than date B")
case .OrderedDescending : print("Date A is later than date B")
case .OrderedSame : print("The two dates are the same")
}
using IF Statement
if dateA.compare(dateB) == .orderedAscending {
datePickerTo.date = datePicker.date
}
//OR
if case .orderedAcending = dateA.compare(dateB) {
}
If you're using JPA1, you might have to drop a persistence.xml
file in there which specifies the name of a persistence-unit you might want to use. A persistence-unit provides a convenient way of specifying a set of metadata files, and classes, and jars that contain all classes to be persisted in a grouping.
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
// ...
EntityManagerFactory emf =
Persistence.createEntityManagerFactory(persistenceUnitName);
See more here: http://www.datanucleus.org/products/datanucleus/jpa/emf.html
Wrap all the children inside of another LinearLayout with wrap_content
for both the width and the height as well as the vertical orientation.
I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%"
from framework.session
in the config.yml
caused cookies to default to whatever domain the form was on, and that fixed the problem.
Another easy way to test without installing anything, neither is it dependent on IIS version. Paste your url to this link - SEO Checkup
To add to web.config: http://www.iis.net/configreference/system.webserver/httpcompression
This is a little bit fancy... but it works:
Step 1: Create a Powershell Profile:
FILE: install_profile.ps1
# THIS SCRIPT BLOWS AWAY YOUR DEFAULT POWERSHELL PROFILE SCRIPT
# AND INSTALLS A POINTER TO A GLOBAL POWERSHELL PROFILE
$ErrorActionPreference = "Stop"
function print ([string]$msg)
{
Write-Host -ForegroundColor Green $msg
}
print ""
# User's Powershell Profile
$psdir = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"
print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null
# this is your auto-generated powershell profile to be installed
$content = @(
"",
". ~/Documents/tools/profile.ps1",
""
)
print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)
print ""
# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted
Step 2: then in tools ~/Documents/tools/profile.ps1:
function Do-ActualThing {
# do actual thing
}
Set-Alias MyAlias Do-ActualThing
Step 3:
$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1
I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error
UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates
It works:
df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5],
'information':['phon','phon','phone','phone1','phone','phone1','phone'],
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')
it doesn't work:
df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5],
'information':['phone','phone','phone','phone','phone','phone','phone'],
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')
Java Advanced Imaging is now open source, and provides the operations you need.
Change the permissions of the directory you want to save to so that all users have read and write permissions.
Thanks to the answers below combined I've got it working.
python setup.py install
had to point cmd towards the correct folder. I did this by pushd C:\Users\absolutefilepathtotarunpackedfolder
python setup.py install
Thanks Tales Padua & Hugo Honorem
I found that we can use extend() to implement the function of copy()
a=['help', 'copyright', 'credits', 'license']
b = []
b.extend(a)
b.append("XYZ")
The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.
Tested with the following code:
function a(){
var s = "hello";
var p = "world";
s = s + p;
return s;
}
function b(){
var s = new Buffer("hello");
var p = new Buffer("world");
s = Buffer.concat([s,p]);
return s;
}
var times = 100000;
var t1 = new Date();
for( var i = 0; i < times; i++){
a();
}
var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
b();
}
var t3 = new Date();
console.log("Buffer took: " + (t3-t2) + " ms.");
Output:
Normal took: 4 ms.
Buffer took: 458 ms.
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
If you cannot disable the expose_php directive to mute PHP’s talkativeness (requires access to the php.ini), you could use Apache’s Header
directive to remove the header field:
Header unset X-Powered-By
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
I had the same issue for a different reason. I've created a new configuration to Debug and Release (under PROJECT -> Info tab -> Configuration). And I had to change my pod frameworks shell script (Pods-"appName"-frameworks.sh , under Targets Support Files) to make it work.
[Xcode 9]
I think somebody chose very unfortunate name for STATELESS concept and that's why the whole misunderstanding is caused. It's not about storing any kind of resources, but rather about the relationship between the client and the server.
Client: I'm keeping all the resources on my side and send you the "list" of all the important items which need to processed. Do your job.
Server: All right.. let me take the responsibility on filtering what's important to give you the proper response.
Which means that the server is the "slave" of the client and has to forget about his "master" after each request. Actually, STATELESS refers only to the state of the server.
https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_3
I like to think of an extern variable as a promise that you make to the compiler.
When encountering an extern, the compiler can only find out its type, not where it "lives", so it can't resolve the reference.
You are telling it, "Trust me. At link time this reference will be resolvable."
If you need not equal object condition use cross join sequences:
var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]
static_cast
vs dynamic_cast
vs reinterpret_cast
internals view on a downcast/upcast
In this answer, I want to compare these three mechanisms on a concrete upcast/downcast example and analyze what happens to the underlying pointers/memory/assembly to give a concrete understanding of how they compare.
I believe that this will give a good intuition on how those casts are different:
static_cast
: does one address offset at runtime (low runtime impact) and no safety checks that a downcast is correct.
dyanamic_cast
: does the same address offset at runtime like static_cast
, but also and an expensive safety check that a downcast is correct using RTTI.
This safety check allows you to query if a base class pointer is of a given type at runtime by checking a return of nullptr
which indicates an invalid downcast.
Therefore, if your code is not able to check for that nullptr
and take a valid non-abort action, you should just use static_cast
instead of dynamic cast.
If an abort is the only action your code can take, maybe you only want to enable the dynamic_cast
in debug builds (-NDEBUG
), and use static_cast
otherwise, e.g. as done here, to not slow down your fast runs.
reinterpret_cast
: does nothing at runtime, not even the address offset. The pointer must point exactly to the correct type, not even a base class works. You generally don't want this unless raw byte streams are involved.
Consider the following code example:
main.cpp
#include <iostream>
struct B1 {
B1(int int_in_b1) : int_in_b1(int_in_b1) {}
virtual ~B1() {}
void f0() {}
virtual int f1() { return 1; }
int int_in_b1;
};
struct B2 {
B2(int int_in_b2) : int_in_b2(int_in_b2) {}
virtual ~B2() {}
virtual int f2() { return 2; }
int int_in_b2;
};
struct D : public B1, public B2 {
D(int int_in_b1, int int_in_b2, int int_in_d)
: B1(int_in_b1), B2(int_in_b2), int_in_d(int_in_d) {}
void d() {}
int f2() { return 3; }
int int_in_d;
};
int main() {
B2 *b2s[2];
B2 b2{11};
D *dp;
D d{1, 2, 3};
// The memory layout must support the virtual method call use case.
b2s[0] = &b2;
// An upcast is an implicit static_cast<>().
b2s[1] = &d;
std::cout << "&d " << &d << std::endl;
std::cout << "b2s[0] " << b2s[0] << std::endl;
std::cout << "b2s[1] " << b2s[1] << std::endl;
std::cout << "b2s[0]->f2() " << b2s[0]->f2() << std::endl;
std::cout << "b2s[1]->f2() " << b2s[1]->f2() << std::endl;
// Now for some downcasts.
// Cannot be done implicitly
// error: invalid conversion from ‘B2*’ to ‘D*’ [-fpermissive]
// dp = (b2s[0]);
// Undefined behaviour to an unrelated memory address because this is a B2, not D.
dp = static_cast<D*>(b2s[0]);
std::cout << "static_cast<D*>(b2s[0]) " << dp << std::endl;
std::cout << "static_cast<D*>(b2s[0])->int_in_d " << dp->int_in_d << std::endl;
// OK
dp = static_cast<D*>(b2s[1]);
std::cout << "static_cast<D*>(b2s[1]) " << dp << std::endl;
std::cout << "static_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
// Segfault because dp is nullptr.
dp = dynamic_cast<D*>(b2s[0]);
std::cout << "dynamic_cast<D*>(b2s[0]) " << dp << std::endl;
//std::cout << "dynamic_cast<D*>(b2s[0])->int_in_d " << dp->int_in_d << std::endl;
// OK
dp = dynamic_cast<D*>(b2s[1]);
std::cout << "dynamic_cast<D*>(b2s[1]) " << dp << std::endl;
std::cout << "dynamic_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
// Undefined behaviour to an unrelated memory address because this
// did not calculate the offset to get from B2* to D*.
dp = reinterpret_cast<D*>(b2s[1]);
std::cout << "reinterpret_cast<D*>(b2s[1]) " << dp << std::endl;
std::cout << "reinterpret_cast<D*>(b2s[1])->int_in_d " << dp->int_in_d << std::endl;
}
Compile, run and disassemble with:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
setarch `uname -m` -R ./main.out
gdb -batch -ex "disassemble/rs main" main.out
where setarch
is used to disable ASLR to make it easier to compare runs.
Possible output:
&d 0x7fffffffc930
b2s[0] 0x7fffffffc920
b2s[1] 0x7fffffffc940
b2s[0]->f2() 2
b2s[1]->f2() 3
static_cast<D*>(b2s[0]) 0x7fffffffc910
static_cast<D*>(b2s[0])->int_in_d 1
static_cast<D*>(b2s[1]) 0x7fffffffc930
static_cast<D*>(b2s[1])->int_in_d 3
dynamic_cast<D*>(b2s[0]) 0
dynamic_cast<D*>(b2s[1]) 0x7fffffffc930
dynamic_cast<D*>(b2s[1])->int_in_d 3
reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940
reinterpret_cast<D*>(b2s[1])->int_in_d 32767
Now, as mentioned at: https://en.wikipedia.org/wiki/Virtual_method_table in order to support the virtual method calls efficiently, the memory data structure of D
has to look something like:
B1:
+0: pointer to virtual method table of B1
+4: value of int_in_b1
B2:
+0: pointer to virtual method table of B2
+4: value of int_in_b2
D:
+0: pointer to virtual method table of D (for B1)
+4: value of int_in_b1
+8: pointer to virtual method table of D (for B2)
+12: value of int_in_b2
+16: value of int_in_d
The key fact is that the memory data structure of D
contains inside it memory structure compatible with that of B1
and that of B2
internally.
Therefore we reach the critical conclusion:
an upcast or downcast only needs to shift the pointer value by a value known at compile time
This way, when D
gets passed to the base type array, the type cast actually calculates that offset and points something that looks exactly like a valid B2
in memory:
b2s[1] = &d;
except that this one has the vtable for D
instead of B2
, and therefore all virtual calls work transparently.
Now, we can finally get back to type casting and the analysis of our concrete example.
From the stdout output we see:
&d 0x7fffffffc930
b2s[1] 0x7fffffffc940
Therefore, the implicit static_cast
done there did correctly calculate the offset from the full D
data structure at 0x7fffffffc930 to the B2
like one which is at 0x7fffffffc940. We also infer that what lies between 0x7fffffffc930 and 0x7fffffffc940 is likely be the B1
data and vtable.
Then, on the downcast sections, it is now easy to understand how the invalid ones fail and why:
static_cast<D*>(b2s[0]) 0x7fffffffc910
: the compiler just went up 0x10 at compile time bytes to try and go from a B2
to the containing D
But because b2s[0]
was not a D
, it now points to an undefined memory region.
The disassembly is:
49 dp = static_cast<D*>(b2s[0]);
0x0000000000000fc8 <+414>: 48 8b 45 d0 mov -0x30(%rbp),%rax
0x0000000000000fcc <+418>: 48 85 c0 test %rax,%rax
0x0000000000000fcf <+421>: 74 0a je 0xfdb <main()+433>
0x0000000000000fd1 <+423>: 48 8b 45 d0 mov -0x30(%rbp),%rax
0x0000000000000fd5 <+427>: 48 83 e8 10 sub $0x10,%rax
0x0000000000000fd9 <+431>: eb 05 jmp 0xfe0 <main()+438>
0x0000000000000fdb <+433>: b8 00 00 00 00 mov $0x0,%eax
0x0000000000000fe0 <+438>: 48 89 45 98 mov %rax,-0x68(%rbp)
so we see that GCC does:
D
which does not existdynamic_cast<D*>(b2s[0]) 0
: C++ actually found that the cast was invalid and returned nullptr
!
There is no way this can be done at compile time, and we will confirm that from the disassembly:
59 dp = dynamic_cast<D*>(b2s[0]);
0x00000000000010ec <+706>: 48 8b 45 d0 mov -0x30(%rbp),%rax
0x00000000000010f0 <+710>: 48 85 c0 test %rax,%rax
0x00000000000010f3 <+713>: 74 1d je 0x1112 <main()+744>
0x00000000000010f5 <+715>: b9 10 00 00 00 mov $0x10,%ecx
0x00000000000010fa <+720>: 48 8d 15 f7 0b 20 00 lea 0x200bf7(%rip),%rdx # 0x201cf8 <_ZTI1D>
0x0000000000001101 <+727>: 48 8d 35 28 0c 20 00 lea 0x200c28(%rip),%rsi # 0x201d30 <_ZTI2B2>
0x0000000000001108 <+734>: 48 89 c7 mov %rax,%rdi
0x000000000000110b <+737>: e8 c0 fb ff ff callq 0xcd0 <__dynamic_cast@plt>
0x0000000000001110 <+742>: eb 05 jmp 0x1117 <main()+749>
0x0000000000001112 <+744>: b8 00 00 00 00 mov $0x0,%eax
0x0000000000001117 <+749>: 48 89 45 98 mov %rax,-0x68(%rbp)
First there is a NULL check, and it returns NULL if th einput is NULL.
Otherwise, it sets up some arguments in the RDX, RSI and RDI and calls __dynamic_cast
.
I don't have the patience to analyze this further now, but as others said, the only way for this to work is for __dynamic_cast
to access some extra RTTI in-memory data structures that represent the class hierarchy.
It must therefore start from the B2
entry for that table, then walk this class hierarchy until it finds that the vtable for a D
typecast from b2s[0]
.
This is why reinterpret cast is potentially expensive! Here is an example where a one liner patch converting a dynamic_cast
to a static_cast
in a complex project reduced runtime by 33%!.
reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940
this one just believes us blindly: we said there is a D
at address b2s[1]
, and the compiler does no offset calculations.
But this is wrong, because D is actually at 0x7fffffffc930, what is at 0x7fffffffc940 is the B2-like structure inside D! So trash gets accessed.
We can confirm this from the horrendous -O0
assembly that just moves the value around:
70 dp = reinterpret_cast<D*>(b2s[1]);
0x00000000000011fa <+976>: 48 8b 45 d8 mov -0x28(%rbp),%rax
0x00000000000011fe <+980>: 48 89 45 98 mov %rax,-0x68(%rbp)
Related questions:
Tested on Ubuntu 18.04 amd64, GCC 7.4.0.
The above answers may help you but you may also want to know how to use array of function pointers.
void fun1()
{
}
void fun2()
{
}
void fun3()
{
}
void (*func_ptr[3])() = {fun1, fun2, fun3};
main()
{
int option;
printf("\nEnter function number you want");
printf("\nYou should not enter other than 0 , 1, 2"); /* because we have only 3 functions */
scanf("%d",&option);
if((option>=0)&&(option<=2))
{
(*func_ptr[option])();
}
return 0;
}
You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.
You can also pass arguments like below if all the above functions are having the same number of arguments of same type.
(*func_ptr[option])(argu1);
Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example fun1
can be called if option=0, fun2
can be called if option=1 and fun3
can be called if option=2.
SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
Are you sure you should be using POST not PUT?
POST is usually used with application/x-www-urlencoded
formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data
. Not always, but usually, that is the right thing to do..
Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.
Assign a int -1
to an unsigned
: As -1
does not fit in the range [0...UINT_MAX]
, multiples of UINT_MAX+1
are added until the answer is in range. Evidently UINT_MAX
is pow(2,32)-1 or 429496725
on OP's machine so a
has the value of 4294967295.
unsigned int a = -1;
The "%x"
, "%u"
specifier expects a matching unsigned
. Since these do not match, "If a conversion specification is invalid, the behavior is undefined.
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b
.
printf("%x\n", b); // UB
printf("%u\n", b); // UB
The "%d"
specifier expects a matching int
. Since these do not match, more UB.
printf("%d\n", a); // UB
Given undefined behavior, the conclusions are not supported.
both cases, the bytes are the same (ffffffff).
Even with the same bit pattern, different types may have different values. ffffffff
as an unsigned
has the value of 4294967295. As an int
, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float
it may be a NAN.
what is unsigned word for?
unsigned
stores a whole number in the range [0 ... UINT_MAX]
. It never has a negative value. If code needs a non-negative number, use unsigned
. If code needs a counting number that may be +, - or 0, use int
.
Update: to avoid a compiler warning about assigning a signed int
to unsigned
, use the below. This is an unsigned
1u
being negated - which is well defined as above. The effect is the same as a -1
, but conveys to the compiler direct intentions.
unsigned int a = -1u;
In MySQL:
create table temp as select * from original_table
I've built up on @user1032613's answer and on this answer and created a "on press enter click element with querystring" hook. enjoy!
const { useEffect } = require("react");
const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
useEffect(() => {
//https://stackoverflow.com/a/59147255/828184
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
handlePressEnter();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
const handlePressEnter = () => {
//https://stackoverflow.com/a/54316368/828184
const mouseClickEvents = ["mousedown", "click", "mouseup"];
function simulateMouseClick(element) {
mouseClickEvents.forEach((mouseEventType) =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1,
})
)
);
}
var element = document.querySelector(querySelectorToExecuteClick);
simulateMouseClick(element);
};
};
export default useEnterKeyListener;
This is how you use it:
useEnterKeyListener({
querySelectorToExecuteClick: "#submitButton",
});
https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407
The Y in atan2 is, by default, the first parameter. Here is the documentation. You will need to switch your inputs to get the correct bearing angle.
bearing = atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2)in(lat1)*cos(lat2)*cos(lon2-lon1))
bearing = degrees(bearing)
bearing = (bearing + 360) % 360
Just close the file in case it is opened in the background. The error disappears by itself
The other answer didn't work for me (on Windows 7). But this worked:
telnet localhost 5554
kill
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF)
or Unix(LF)
It may be worth getting into the habit of using printf
rather then echo
on the command line.
In this example it doesn't give much benefit but it can be more useful with more complex output.
FOO="BAR * BAR"
printf %s "$FOO"
There is only one PNG format, but it supports 5 color types.
PNG-8 refers to palette variant, which supports only 256 colors, but is usually smaller in size. PNG-8 can be a GIF substitute.
PNG-24 refers to true color variant, which supports more colors, but might be bigger. PNG-24 can be used instead of JPEG, if lossless image format is needed.
Any modern web browser will support both variants.
Adding the following on top of your JS file will tell JSHint to supress the radix warning:
/*jshint -W065 */
See also: http://jshint.com/docs/#options
add this code in .htaccess (as an alternative of php.ini / ini_set function):
<IfModule mod_php5.c>
php_flag log_errors on
php_value error_log ./path_to_MY_PHP_ERRORS.log
# php_flag display_errors on
</IfModule>
* as commented: this is for Apache-type servers, and not for Nginx or others.
You can permanently include the directory of the MinGW file, by clicking on My Computer, Properties, Advanced system settings, Environment variables, then edit and paste your directory.
When the return key is pressed, call:
[uitextfield resignFirstResponder];
Reason is , {}
is the syntax of .format()
so in your case .format()
doesn't recognize {Hello}
so it threw an error.
you can override it by using double curly braces {{}},
x = " {{ Hello }} {0} "
or
try %s
for text formatting,
x = " { Hello } %s"
print x%(42)
I looked at several of the options. Here are my two favorites, because I needed to round the value.
,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2 = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy ---------
--- Hank Freeman : [email protected]
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
SELECT
FileGroupName = DS.name
,FileGroupType =
CASE DS.[type]
WHEN 'FG' THEN 'Filegroup'
WHEN 'FD' THEN 'Filestream'
WHEN 'FX' THEN 'Memory-optimized'
WHEN 'PS' THEN 'Partition Scheme'
ELSE 'Unknown'
END
,SchemaName = SCH.name
,TableName = OBJ.name
,IndexType =
CASE IDX.[type]
WHEN 0 THEN 'Heap'
WHEN 1 THEN 'Clustered'
WHEN 2 THEN 'Nonclustered'
WHEN 3 THEN 'XML'
WHEN 4 THEN 'Spatial'
WHEN 5 THEN 'Clustered columnstore'
WHEN 6 THEN 'Nonclustered columnstore'
WHEN 7 THEN 'Nonclustered hash'
END
,IndexName = IDX.name
,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','') --- MUST show for all types when no Primary key
--,( Case WHEN IDX.[type] IN (2,6,7) then 0 else p.rows end )as Rowcounts_T
,AllocationDesc = AU.type_desc
/*
,RowCounts = p.rows --- MUST show for all types when no Primary key
,TotalSizeKB2 = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
,UsedSizeKB = Cast(Round(SUM(AU.used_pages / 0.128),0)as int)
,DataSizeKB = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
--replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
,TotalSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
,UsedSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','')
,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
,DataSizeKB2 = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
,DataSizeKB3 = format(SUM(AU.data_pages / 0.128),'##,##0')
--SELECT Format(1234567.8, '##,##0.00')
---
,is_default = CONVERT(INT,DS.is_default)
,is_read_only = CONVERT(INT,DS.is_read_only)
FROM
sys.filegroups DS -- you could also use sys.data_spaces
LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
LEFT JOIN sys.partitions PA
ON (AU.[type] IN (1,3) AND
AU.container_id = PA.hobt_id) OR
(AU.[type] = 2 AND
AU.container_id = PA.[partition_id])
LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
LEFT JOIN sys.indexes IDX
ON PA.[object_id] = IDX.[object_id] AND
PA.index_id = IDX.index_id
-----
INNER JOIN
sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
WHERE
OBJ.type_desc = 'USER_TABLE' -- only include user tables
OR
DS.[type] = 'FD' -- or the filestream filegroup
GROUP BY
DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type] ,DS.is_default ,DS.is_read_only -- discard different allocation units
,p.rows ,AU.type_desc ---
ORDER BY
DS.name ,SCH.name ,OBJ.name ,IDX.name
---
;
I'm going to cheat a little and throw out a new answer to this that seems to sum up the best of everything on here instead of sticking it inside of a comment.
So you can one line this:
List<string> strings = new List<string>() { "one", "two", "three" };
string concat = strings
.Aggregate(new StringBuilder("\a"),
(current, next) => current.Append(", ").Append(next))
.ToString()
.Replace("\a, ",string.Empty);
Edit: You'll either want to check for an empty enumerable first or add an .Replace("\a",string.Empty);
to the end of the expression. Guess I might have been trying to get a little too smart.
The answer from @a.friend might be slightly more performant, I'm not sure what Replace does under the hood compared to Remove. The only other caveat if some reason you wanted to concat strings that ended in \a's you would lose your separators... I find that unlikely. If that is the case you do have other fancy characters to choose from.
I tried a method of Diego Ramírez, it works. In AndroidManifest:
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateHidden|adjustResize">
...
</activity>
In activity_main.xml:
<LinearLayout ...
android:orientation="vertical">
<Space
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1" />
<EditText
android:id="@+id/edName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/first_name"
android:inputType="textPersonName" />
<EditText ...>
...
</LinearLayout>
In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.
To add Hassou's solution to your .bashrc, try:
alias lst='ls -R | grep ":$" | sed -e '"'"'s/:$//'"'"' -e '"'"'s/[^-][^\/]*\//--/g'"'"' -e '"'"'s/^/ /'"'"' -e '"'"'s/-/|/'"'"
If you want to revert the element to the source position if it's not dropped inside a #droppable
element, just save the original parent element of the draggable at the start of the script (instead of the position), and if you verify that it's not dropped into #droppable
, then just restore the parent of #draggable
to this original element.
So, replace this:
}).each(function() {
var top = $(this).position().top;
var left = $(this).position().left;
$(this).data('orgTop', top);
$(this).data('orgLeft', left);
});
with this:
}).each(function() {
$(this).data('originalParent', $(this).parent())
});
Here, you'll have the original parent element of the draggable. Now, you have to restore it's parent in a precise moment.
drop
is called every time the element is dragged out from the droppable, not at the stop. So, you're adding a lot of event callbacks. This is wrong, because you never clean the mouseup
event. A good place where you can hook a callback and check if the element was dropped inside or outside the #droppable
element, is revert
, and you're doing it right now, so, just delete the drop
callback.
When the element is dropped, and needs to know if it should be reverted or not, you know for sure that you'll not have any other interaction from the user until the new drag start. So, using the same condition you're using to know if it should revert or know, let's replace this alert
with a fragment of code that: restores the parent element to the original div, and resets the originalPosition
from the draggable
internals. The originalPosition
proeprty is setted at the time of _mouseStart
, so, if you change the owner of the element, you should reset it, in order to make the animation of revert go to the proper place. So, let's set this to {top: 0, left: 0}
, making the animation go to the origin point of the element:
revert: function(dropped) {
var dropped = dropped && dropped[0].id == "droppable";
if(!dropped) {
$(this).data("draggable").originalPosition = {top:0, left:0}
$(this).appendTo($(this).data('originalParent'))
}
return !dropped;
}
And that's it! You can check this working here: http://jsfiddle.net/eUs3e/1/
Take into consideration that, if in any jQuery's UI update, the behavior of revert
or originalPosition
changes, you'll need to update your code in order to make it work. Keep in mind that.
If you need a solution which doesn't make use of calls to the internals of ui.draggable, you can make your body
an droppable element with greedy
option defined as false
. You'll have to make sure that your body
elements take the full screen.
Good luck!
Use the following standard Java solution (passes around 100 of the testcases provided by Web Plattform Tests):
0. Test if URL is already encoded.
1. Split URL into structural parts. Use java.net.URL
for it.
2. Encode each structural part properly!
3. Use IDN.toASCII(putDomainNameHere)
to Punycode encode the host name!
4. Use java.net.URI.toASCIIString()
to percent-encode, NFC encoded unicode - (better would be NFKC!).
Find more here: https://stackoverflow.com/a/49796882/1485527
As an alternate option, if you have the Sqlite Database Browser and are more inclined to a GUI solution, you can edit the sqlite_sequence table where field name is the name of your table. Double click the cell for the field seq and change the value to 0 in the dialogue box that pops up.
Here is a tutorial for building a Debian package.
Basically, you need to:
I usually do all of this in my Makefile so I can just type make to spit out the binary and package it in one go.
import pandas as pd
print(pd.json_normalize(your_json))
This will Normalize semi-structured JSON data into a flat table
Output
FirstName LastName MiddleName password username
John Mark Lewis 2910 johnlewis2
Function is not a property/method from range.
If you want to sum values then use the following:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
EDIT:
if you want the formula then use as follows:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"
'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).
In case you are allways going to use the same range address then you can use as Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
when using (i.e.) getConstructor(String.lang)
the constructor has to be declared public.
Otherwise a NoSuchMethodException
is thrown.
if you want to access a non-public constructor you have to use instead (i.e.) getDeclaredConstructor(String.lang)
.
:: ------- Self-elevating.bat --------------------------------------
@whoami /groups | find "S-1-16-12288" > nul && goto :admin
set "ELEVATE_CMDLINE=cd /d "%~dp0" & call "%~f0" %*"
findstr "^:::" "%~sf0">temp.vbs
cscript //nologo temp.vbs & del temp.vbs & exit /b
::: Set objShell = CreateObject("Shell.Application")
::: Set objWshShell = WScript.CreateObject("WScript.Shell")
::: Set objWshProcessEnv = objWshShell.Environment("PROCESS")
::: strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
::: objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
:admin -------------------------------------------------------------
@echo off
echo Running as elevated user.
echo Script file : %~f0
echo Arguments : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k
For a demo: self-elevating.bat "path with spaces" arg2 3 4 "another long argument"
And this is another version that does not require creating a temp file.
<!-- : --- Self-Elevating Batch Script ---------------------------
@whoami /groups | find "S-1-16-12288" > nul && goto :admin
set "ELEVATE_CMDLINE=cd /d "%~dp0" & call "%~f0" %*"
cscript //nologo "%~f0?.wsf" //job:Elevate & exit /b
-->
<job id="Elevate"><script language="VBScript">
Set objShell = CreateObject("Shell.Application")
Set objWshShell = WScript.CreateObject("WScript.Shell")
Set objWshProcessEnv = objWshShell.Environment("PROCESS")
strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
</script></job>
:admin -----------------------------------------------------------
@echo off
echo Running as elevated user.
echo Script file : %~f0
echo Arguments : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k
As any static method is part of class not instance so it is not possible to override static method
there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.
Detect if user pressed "Back" button on current page:
Detect if current page is visited after pressing "Back" button on previous("Forward") page:
All the validation from model are skipped when we use validate: false
user = User.new(....)
user.save(validate: false)
Created the Data frame:
import pandas as pd
dk=pd.DataFrame({"BrandName":['A','B','ABC','D','AB'],"Specialty":['H','I','J','K','L']})
Now use DataFrame.replace()
function:
dk.BrandName.replace(to_replace=['ABC','AB'],value='A')
If your page is deeply pathed or might move around and your JS script is at "~/JS/Registration.js" of your web folder, you can try the following:
<script src='<%=ResolveClientUrl("~/JS/Registration.js") %>'
type="text/javascript"></script>
It is very simple, just do this:
t4.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
launchQuiz2(); // TODO Auto-generated method stub
}
private void launchQuiz2() {
Intent i = new Intent(MainActivity.this, Quiz2.class);
startActivity(i);
// TODO Auto-generated method stub
}
});
defaultOrder contain a array where key is a column name and value is a SORT_DESC
or SORT_ASC
that's why below code not working.
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
Correct Way
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'topic_order' => SORT_ASC,
]
],
]);
Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).
You can detail learn from Yii2 Guide of Data Provider
Sorting By passing Sort object in query
$sort = new Sort([
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
]);
$models = Article::find()
->where(['status' => 1])
->orderBy($sort->orders)
->all();
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
use DECIMAL()
or NUMERIC()
as they are fixed precision and scale numbers.
SELECT fullName,
CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info
ORDER BY _totalBal DESC
Why do you need it to be of type GenericWebApplicationContext
?
I think you can probably work with any ApplicationContext type.
Usually you would use an init method (in addition to your setter method):
@PostConstruct
public void init(){
AutowireCapableBeanFactory bf = this.applicationContext
.getAutowireCapableBeanFactory();
// wire stuff here
}
And you would wire beans by using either
AutowireCapableBeanFactory.autowire(Class, int mode, boolean dependencyInject)
or
AutowireCapableBeanFactory.initializeBean(Object existingbean, String beanName)
Just wanted to add -- apparently this can also be caused by installing Instant Client for 10, then realizing you want the full install and installing it again in a parallel directory. I don't know why this broke it.
Here's what worked for me using the Git Bash terminal in VS Code on windows in succinct steps:
source activate env-name
- You should see your line appended by the (base) tag now.
After calling on source activate
, I've found following conda activate
commands to work: i.e. conda activate env2-name
What didn't work for Git Bash (as a VS Code terminal) for me: activate env-name
and conda activate env-name
.
Not exactly sure why this specific behaviour occurs on the Git Bash terminal on VS Code, but the accepted answer + this stackoverflow question I've found might provide clues.
split
(from GNU coreutils, since version 8.8 from 2010-12-22) includes the following parameter:
-n, --number=CHUNKS generate CHUNKS output files; see explanation below
CHUNKS may be:
N split into N files based on size of input
K/N output Kth of N to stdout
l/N split into N files without splitting lines/records
l/K/N output Kth of N to stdout without splitting lines/records
r/N like 'l' but use round robin distribution
r/K/N likewise but only output Kth of N to stdout
Thus, split -n 4 input output.
will generate four files (output.a{a,b,c,d}
) with the same amount of bytes, but lines might be broken in the middle.
If we want to preserve full lines (i.e. split by lines), then this should work:
split -n l/4 input output.
Related answer: https://stackoverflow.com/a/19031247
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timewithRouter
, history.listen
, and useEffect
(React Hooks) works quite nicely together:
import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
const Component = ({ history }) => {
useEffect(() => history.listen(() => {
// do something on route change
// for my example, close a drawer
}), [])
//...
}
export default withRouter(Component)
The listener callback will fire any time a route is changed, and the return for history.listen
is a shutdown handler that plays nicely with useEffect
.
I had the right public/private key, but seemed like it didn't work anyway (got same errors, prompting for the git-user password). After a computer-restart it worked though!
So by default you can open CMD and write
java -jar jenkins.war
But if your port 8080 is already is in use,so you have to change the Jenkins port number, so for that open Jenkins folder in Program File and open Jenkins.XML file and change the port number such as 8088
Now Open CMD and write
java -jar jenkins.war --httpPort=8088
There is only a small amount of information that you can get via an HTTP connection.
IP - But as others have said, this is not fixed for many, if not most Internet users due to their ISP's dynamic allocation policies.
Useragent String - Nearly all browsers send what kind of browser they are with every request. However, this can be set by the user in many browsers today.
Collection of request fields - There are other fields sent with each request, such as supported encodings, etc. These, if used in the aggregate can help to ID a user's machine, but again are browser dependent and can be changed.
Cookies - Setting a cookie is another way to identify a machine, or more specifically a browser on a machine, but as others have said, these can be deleted, or turned off by the users, and are only applicable on a browser, not a machine.
So, the correct response is that you cannot achieve what you would live via the HTTP over IP protocols alone. However, using a combination of cookies, as well as IP, and the fields in the HTTP request, you have a good chance at guessing, sort of, what machine it is. Users tend to use only one browser, and often from one machine, so this may be fairly relieable, but this will vary depending on the audience...techies are more likely to mess with this stuff, and use more machines/browsers. Additionally, this could even be coupled with some attempt to geo-locate the IP, and use that data as well. But in any case, there is no solution that will be correct all of the time.
Other than syntax, a switch can be implemented using a tree which makes it O(log n)
, while a if/else has to be implemented with an O(n)
procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?
Try to replace it with °
, and also to set the charset to utf-8, as Martin suggests.
°C
will get you something like this:
Everything is encoded by default!!! This is pretty huge.
Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.
You can make a section required which is nice.
Simple just run the following command.
sudo dnf install *package.rpm
Enter your password and you are done.
In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$");
for further information see the javadoc
You can get the name value from an input field using name element in jQuery by:
var firstname = jQuery("#form1 input[name=firstname]").val(); //Returns ABCD_x000D_
var lastname = jQuery("#form1 input[name=lastname]").val(); //Returns XYZ _x000D_
console.log(firstname);_x000D_
console.log(lastname);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name="form1" id="form1">_x000D_
<input type="text" name="firstname" value="ABCD"/>_x000D_
<input type="text" name="lastname" value="XYZ"/>_x000D_
</form>
_x000D_
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
You can use a constant (i.e. a static, final variable) as the parameter for an annotation. As a quick example, I use something like this fairly often:
import org.junit.Test;
import static org.junit.Assert.*;
public class MyTestClass
{
private static final int TEST_TIMEOUT = 60000; // one minute per test
@Test(timeout=TEST_TIMEOUT)
public void testJDK()
{
assertTrue("Something is very wrong", Boolean.TRUE);
}
}
Note that it's possible to pass the TEST_TIMEOUT
constant straight into the annotation.
Offhand, I don't recall ever having tried this with an array, so you may be running into some issues with slight differences in how arrays are represented as annotation parameters compared to Java variables? But as for the other part of your question, you could definitely use a constant String without any problems.
EDIT: I've just tried this with a String array, and didn't run into the problem you mentioned - however the compiler did tell me that the "attribute value must be constant" despite the array being defined as public static final String[]
. Perhaps it doesn't like the fact that arrays are mutable? Hmm...
just do this , you need to remove char other than "numeric" and "." form your string will do work for you
yourString = yourString.replace ( /[^\d.]/g, '' );
your final code will be
str1 = "test123.00".replace ( /[^\d.]/g, '' );
str2 = "yes50.00".replace ( /[^\d.]/g, '' );
total = parseInt(str1, 10) + parseInt(str2, 10);
alert(total);
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
Here is some code. without any error.
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // here is the most important part because if you dont replace you will get a DOM 18 exception.
window.location.href=image; // it will save locally
What im doing is, simple overriding join and run method of the Thread:
class RaisingThread(threading.Thread):
def run(self):
self._exc = None
try:
super().run()
except Exception as e:
self._exc = e
def join(self):
super().join()
if self._exc:
raise self._exc
Used as followed:
def foo():
time.sleep(2)
print('hi, from foo!')
raise Exception('exception from foo')
t = RaisingThread(target=foo)
t.start()
try:
t.join()
except Exception as e:
print(e)
Result:
hi, from foo!
exception from foo!
Animal = function () { throw "abstract class!" }
Animal.prototype.name = "This animal";
Animal.prototype.sound = "...";
Animal.prototype.say = function() {
console.log( this.name + " says: " + this.sound );
}
Cat = function () {
this.name = "Cat";
this.sound = "meow";
}
Dog = function() {
this.name = "Dog";
this.sound = "woof";
}
Cat.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
new Cat().say(); //Cat says: meow
new Dog().say(); //Dog says: woof
new Animal().say(); //Uncaught abstract class!
ravgs = [sum(data[i:i+5])/5. for i in range(len(data)-4)]
This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.
There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).
You can use the following command to know the number of databases:
CONFIG GET databases
1) "databases"
2) "16"
You can use the following command to list the databases for which some keys are defined:
INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.
For instance:
*2
$4
INFO
$8
keyspace
$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
You can find the description of the Redis protocol here: http://redis.io/topics/protocol
If You have already updated your SDK and You also using google-play-services then you need to take care of the dependency because there are some kind of conflics with :
Follow the below : compile 'com.google.android.gms:play-services:+' Replace by compile 'com.google.android.gms:play-services:6.5.87'
Note: Here '6.5.87' is the google-play-service version. I hope it will help..
It will be found in /usr/local/mysql
if you use the mysql binaries or dmg to install it on your system instead of using MAMP
On express 3 you can use directly res.json({foo:bar})
res.json({ msgId: msg.fileName })
See the documentation
Solution specific to Nexus 4 and Nexus 5 for OS X
Got no device listed in the "List of devices attached" when I ran: adb devices
Fix:
'Settings'
: { } Developer OptionsTry listing your device from ./adb devices and it should work.
Answer taken from: Any idea why adb does not recognize my nexus 4 on mac
The document suggests that it takes the @color/accent by default. But we can override it on code by using
fab.setBackgroundTintList(ColorStateList)
Also remember,
The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!
the best way: $('#myTextBox').val('new value').trim();
I use this function datetime_to_local_timezone()
, which seems overly convoluted but I found no simpler version of a function that converts a datetime
instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:
import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))
This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:
2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00
@RequestParam
annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:
request:
GET: http://someserver.org/path?name=John&surname=Smith
endpoint code:
public User getUser(@RequestParam(value = "name") String name,
@RequestParam(value = "surname") String surname){
...
}
So basically, while @RequestBody
maps entire user request (even for POST) to a String variable, @RequestParam
does so with one (or more - but it is more complicated) request param to your method argument.
String in string:
Find "etc" in " .. JD JD JD JD etc. and etc. JDJDJDJDJDJDJDJD and etc."
var strOrigin = " .. JD JD JD JD etc. and etc. JDJDJDJDJDJDJDJD and etc.";
var searchStr = "etc";
int count = (strOrigin.Length - strOrigin.Replace(searchStr, "").Length)/searchStr.Length.
Check performance before discarding this one as unsound/clumsy...
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
I don't get that part about the string stuff, but why don't you use the modulo operator (%
) to check if a number is dividable by another? If a number is dividable by another, the other is automatically a multiple of that number.
It goes like that:
int a = 10; int b = 5;
// is a a multiple of b
if ( a % b == 0 ) ....
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
For same error code i had quite different reason, I'm sharing here to help
I had web api action like below
public IHttpActionResult GetBooks (int id)
I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]
public IHttpActionResult GetBooks (int category, int author)
I also changed ajax options like below and at this point i start getting error 405 method not allowed
var options = {
url: '/api/books/GetBooks',
type: 'POST',
dataType: 'json',
cache: false,
traditional: true,
data: {
category: 1,
author: 15
}
}
When i created class for web api action parameters like below error was gone
public class BookParam
{
public int Category { get; set; }
public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)
For log4j 2 API , you can use
Logger logger = LogManager.getRootLogger();
Configurator.setAllLevels(logger.getName(), Level.getLevel(level));
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
see: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
so you need to add: cursor:pointer;
In your case use:
#more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
This will apply the curser to the element with the ID "more" (can be only used once). So in your HTML use
<input type="button" id="more" />
If you want to apply this to more than one button then you have more than one possibility:
using CLASS
.more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
and in your HTML use
<input type="button" class="more" value="first" />
<input type="button" class="more" value="second" />
or apply to a html context:
input[type=button] {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
}
and in your HTML use
<input type="button" value="first" />
<input type="button" value="second" />
No idea if this still applies to 8, but historically IE doesn't apply several styles to elements that don't "have layout."
CSS "classes" are not OOP "classes". The inheritance works the other way around.
A DOM element can have many classes, either directly or inherited or otherwise associated, which will all be applied in order, overriding earlier defined properties:
<div class="foo bar">
.foo {
color: blue;
width: 200px;
}
.bar {
color: red;
}
The div will be 200px wide and have the color red.
You override properties of DOM elements with different classes, not properties of CSS classes. CSS "classes" are rulesets, the same way ids or tags can be used as rulesets.
Note that the order in which the classes are applied depends on the precedence and specificity of the selector, which is a complex enough topic in itself.
You certainly want to hack the header to have a proper Ajax Request :
headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()
And to json.loads the POST on the server-side.
Edit : By the way, you have to urllib.urlencode(mydata_dict)
before sending them. If you don't, the POST won't be what the server expect
Resolved promise:
return $q.when( someValue ); // angularjs 1.2+
return $q.resolve( someValue ); // angularjs 1.4+, alias to `when` to match ES6
Rejected promise:
return $q.reject( someValue );
In Your example, apache.yml is tasklist, but not playbook
In depends on desired architecture, You can do one of:
Convert apache.yml to role. Then define tasks in roles/apache/tasks/mail.yml and variables in roles/apache/defaults/mail.yml (vars in defaults can be overriden when role applied)
Set vars in play.yml playbook
play.yml
---
- hosts: 127.0.0.1
connection: local
sudo: false
vars:
url: czxcxz
tasks:
- include: apache.yml
apache.yml
- name: Download apache
shell: wget {{url}}
I'm running an ASP.NET MVC 5 application on IIS 8.5. I tried all the variations posted here, and this is what my web.config
looks like:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I couldn't uninstall WebDav from my Server because I didn't have admin privileges. Also, sometimes I was getting the method not allowed
on .css and .js files. In the end, with the configuration above set up everything started working again.
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
i think you should use hidden better.
activityIndicator.hidden = YES
Here I like to use https://www.netresize.net/index.php?c=3a&id=11#buyopt. But it is paid version.
You also can get their source codes if you buy 1 Site License (Unlimited Developers).
How ever I am finding the nuget package solution.
As long as they are attributes like classes and ids you can remove them by javascript/jQuery class modifiers.
document.getElementById("MyElement").className = "";
There is no way to remove specific tag CSS other than overriding them (or using another element).
use app.set & app.get
Setting data
router.get(
"/facebook/callback",
passport.authenticate("facebook"),
(req, res) => {
req.app.set('user', res.req.user)
return res.redirect("/sign");
}
);
Getting data
router.get("/sign", (req, res) => {
console.log('sign', req.app.get('user'))
});
use aspectRatio property in style
Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.
docs: https://reactnative.dev/docs/layout-props#aspectratio
try like this:
import {Image, Dimensions} from 'react-native';
var width = Dimensions.get('window').width;
<Image
source={{
uri: '<IMAGE_URI>'
}}
style={{
width: width * .2, //its same to '20%' of device width
aspectRatio: 1, // <-- this
resizeMode: 'contain', //optional
}}
/>
Here is the code to check whether value is present or not.
If Trim(textbox1.text) <> "" Then
'Your code goes here
Else
'Nothing
End If
I think this will help.
Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.
'\u2060', // Word Joiner
'\u2061', // FUNCTION APPLICATION
'\u2062', // INVISIBLE TIMES
'\u2063', // INVISIBLE SEPARATOR
'\u2064', // INVISIBLE PLUS
'\u2066', // LEFT - TO - RIGHT ISOLATE
'\u2067', // RIGHT - TO - LEFT ISOLATE
'\u2068', // FIRST STRONG ISOLATE
'\u2069', // POP DIRECTIONAL ISOLATE
'\u206A', // INHIBIT SYMMETRIC SWAPPING
'\u206B', // ACTIVATE SYMMETRIC SWAPPING
'\u206C', // INHIBIT ARABIC FORM SHAPING
'\u206D', // ACTIVATE ARABIC FORM SHAPING
'\u206E', // NATIONAL DIGIT SHAPES
'\u206F', // NOMINAL DIGIT SHAPES
'\u200B', // Zero-Width Space
'\u200C', // Zero Width Non-Joiner
'\u200D', // Zero Width Joiner
'\u200E', // Left-To-Right Mark
'\u200F', // Right-To-Left Mark
'\u061C', // Arabic Letter Mark
'\uFEFF', // Byte Order Mark
'\u180E', // Mongolian Vowel Separator
'\u00AD' // soft-hyphen
Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.
Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.
You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/
In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.
The SciPy webpage used to provide build and installation instructions, but the instructions there now rely on OS binary distributions. To build SciPy (and NumPy) on operating systems without precompiled packages of the required libraries, you must build and then statically link to the Fortran libraries BLAS and LAPACK:
mkdir -p ~/src/
cd ~/src/
wget http://www.netlib.org/blas/blas.tgz
tar xzf blas.tgz
cd BLAS-*
## NOTE: The selected Fortran compiler must be consistent for BLAS, LAPACK, NumPy, and SciPy.
## For GNU compiler on 32-bit systems:
#g77 -O2 -fno-second-underscore -c *.f # with g77
#gfortran -O2 -std=legacy -fno-second-underscore -c *.f # with gfortran
## OR for GNU compiler on 64-bit systems:
#g77 -O3 -m64 -fno-second-underscore -fPIC -c *.f # with g77
gfortran -O3 -std=legacy -m64 -fno-second-underscore -fPIC -c *.f # with gfortran
## OR for Intel compiler:
#ifort -FI -w90 -w95 -cm -O3 -unroll -c *.f
# Continue below irrespective of compiler:
ar r libfblas.a *.o
ranlib libfblas.a
rm -rf *.o
export BLAS=~/src/BLAS-*/libfblas.a
Execute only one of the five g77/gfortran/ifort commands. I have commented out all, but the gfortran which I use. The subsequent LAPACK installation requires a Fortran 90 compiler, and since both installs should use the same Fortran compiler, g77 should not be used for BLAS.
Next, you'll need to install the LAPACK stuff. The SciPy webpage's instructions helped me here as well, but I had to modify them to suit my environment:
mkdir -p ~/src
cd ~/src/
wget http://www.netlib.org/lapack/lapack.tgz
tar xzf lapack.tgz
cd lapack-*/
cp INSTALL/make.inc.gfortran make.inc # On Linux with lapack-3.2.1 or newer
make lapacklib
make clean
export LAPACK=~/src/lapack-*/liblapack.a
Update on 3-Sep-2015:
Verified some comments today (thanks to all): Before running make lapacklib
edit the make.inc
file and add -fPIC
option to OPTS
and NOOPT
settings. If you are on a 64bit architecture or want to compile for one, also add -m64
. It is important that BLAS and LAPACK are compiled with these options set to the same values. If you forget the -fPIC
SciPy will actually give you an error about missing symbols and will recommend this switch. The specific section of make.inc
looks like this in my setup:
FORTRAN = gfortran
OPTS = -O2 -frecursive -fPIC -m64
DRVOPTS = $(OPTS)
NOOPT = -O0 -frecursive -fPIC -m64
LOADER = gfortran
On old machines (e.g. RedHat 5), gfortran might be installed in an older version (e.g. 4.1.2) and does not understand option -frecursive
. Simply remove it from the make.inc
file in such cases.
The lapack test target of the Makefile fails in my setup because it cannot find the blas libraries. If you are thorough you can temporarily move the blas library to the specified location to test the lapack. I'm a lazy person, so I trust the devs to have it working and verify only in SciPy.
awk '{out=$2; for(i=3;i<=NF;i++){out=out" "$i}; print out}'
My answer is based on the one of VeeArr, but I noticed it started with a white space before it would print the second column (and the rest). As I only have 1 reputation point, I can't comment on it, so here it goes as a new answer:
start with "out" as the second column and then add all the other columns (if they exist). This goes well as long as there is a second column.
A website might just be static content - a web application would have dynamic content. It is a very fuzzy line.
It looks like you are calling a non static member (a property or method, specifically setTextboxText
) from a static method (specifically SumData
). You will need to either:
Make the called member static also:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
Create an instance of Form1
within the calling method:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
Passing in an instance of Form1
would be an option also.
Make the calling method a non-static instance method (of Form1
):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
More info about this error can be found on MSDN.
Easy way to use for create dynamic header and cell in normal table :
<table width="100%" class="table">
<thead>
<tr>
<th ng-repeat="(header, value) in MyRecCollection[0]">{{header}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in MyRecCollection | filter:searchText">
<td ng-repeat="cell in row">{{cell}}</td>
</tr>
</tbody>
</table>
MyApp.controller('dataShow', function ($scope, $http) {
//$scope.gridheader = ['Name','City','Country']
$http.get('http://www.w3schools.com/website/Customers_MYSQL.php').success(function (data) {
$scope.MyRecCollection = data;
})
});
JSON Data :
[{
"Name": "Alfreds Futterkiste",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "Berglunds snabbköp",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}, {
"Name": "Ernst Handel",
"City": "Graz",
"Country": "Austria"
}, {
"Name": "FISSA Fabrica Inter. Salchichas S.A.",
"City": "Madrid",
"Country": "Spain"
}, {
"Name": "Galería del gastrónomo",
"City": "Barcelona",
"Country": "Spain"
}, {
"Name": "Island Trading",
"City": "Cowes",
"Country": "UK"
}, {
"Name": "Königlich Essen",
"City": "Brandenburg",
"Country": "Germany"
}, {
"Name": "Laughing Bacchus Wine Cellars",
"City": "Vancouver",
"Country": "Canada"
}, {
"Name": "Magazzini Alimentari Riuniti",
"City": "Bergamo",
"Country": "Italy"
}, {
"Name": "North/South",
"City": "London",
"Country": "UK"
}, {
"Name": "Paris spécialités",
"City": "Paris",
"Country": "France"
}, {
"Name": "Rattlesnake Canyon Grocery",
"City": "Albuquerque",
"Country": "USA"
}, {
"Name": "Simons bistro",
"City": "København",
"Country": "Denmark"
}, {
"Name": "The Big Cheese",
"City": "Portland",
"Country": "USA"
}, {
"Name": "Vaffeljernet",
"City": "Århus",
"Country": "Denmark"
}, {
"Name": "Wolski Zajazd",
"City": "Warszawa",
"Country": "Poland"
}]
Use:
echo %time% & dir & echo %time%
This is, from memory, equivalent to the semi-colon separator in bash
and other UNIXy shells.
There's also &&
(or ||
) which only executes the second command if the first succeeded (or failed), but the single ampersand &
is what you're looking for here.
That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.
You can get round this by turning on delayed expansion:
pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85
That's needed from the command line. If you're doing this inside a script, you can just use setlocal
:
@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal
An alternative way would be:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
Saw it here
as another option:
$ curl -i http://google.com
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 19 Jun 2010 04:15:10 GMT
Expires: Mon, 19 Jul 2010 04:15:10 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
But it doesn't go past the first one.