In addition to Petr's answer, if you want to bind to a specific interface instead of all the interfaces you can use -b
or --bind
flag.
python -m http.server 8000 --bind 127.0.0.1
The above snippet should do the trick. 8000 is the port number. 80 is used as the standard port for HTTP communications.
If you have PHP installed you could use the builtin server.
php -S 0:8080
http://www.manning.com/hethmon/ -- "Illustrated Guide to HTTP by Paul S. Hethmon" from Manning is a very good book to learn HTTP protocol and will be very useful to someone implementing it /extending it.
RevNoah had the best answer with the suggestion of using Express's cookie parser. But, that answer is now 3 years old and is out of date.
Using Express, you can read a cookie as follows
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.get('/myapi', function(req, resp) {
console.log(req.cookies['Your-Cookie-Name-Here']);
})
And update your package.json
with the following, substituting the appropriate relatively latest versions.
"dependencies": {
"express": "4.12.3",
"cookie-parser": "1.4.0"
},
More operations like setting and parsing cookies are described here and here
When you're running npm install
in the project's root, it installs all of the npm dependencies into the project's node_modules
directory.
If you take a look at the project's node_modules
directory, you should see a directory called http-server
, which holds the http-server
package, and a .bin
folder, which holds the executable binaries from the installed dependencies. The .bin
directory should have the http-server
binary (or a link to it).
So in your case, you should be able to start the http-server
by running the following from your project's root directory (instead of npm start
):
./node_modules/.bin/http-server -a localhost -p 8000 -c-1
This should have the same effect as running npm start
.
If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin
folder to your $PATH
environment variable:
export PATH=./node_modules/.bin:$PATH
This will put this folder on your path, and you should be able to simply run
http-server -a localhost -p 8000 -c-1
checkout Simple. its a pretty simple embeddable server with built in support for quite a variety of operations. I particularly love its threading model..
Amazing!
No one of the previous answers (which all are correct) was suited to my situation: I don't use the async
parameter in jQuery.ajax()
and I don't include a script tag as part of the content that was being returned like:
<div>
SOME CONTENT HERE
</div>
<script src="/scripts/script.js"></script>
My situation is that I am calling two AJAX requests consecutively with the aim to update two divs at the same time:
function f1() {
$.ajax(...); // XMLHTTP request to url_1 and append result to div_1
}
function f2() {
$.ajax(...); // XMLHTTP request to url_2 and append result to div_2
}
function anchor_f1(){
$('a.anchor1').click(function(){
f1();
})
}
function anchor_f2(){
$('a.anchor2').click(function(){
f2();
});
}
// the listener of anchor 3 the source of problem
function anchor_problem(){
$('a.anchor3').click(function(){
f1();
f2();
});
}
anchor_f1();
anchor_f2();
anchor_problem();
When I click on a.anchor3
, it raises the warning flag.I resolved the issue by replacing f2 invoking by click()
function:
function anchor_problem(){
$('a.anchor_problem').click(function(){
f1();
$('a.anchor_f2').click();
});
}
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".
It sounds like you're after something that has some concept of items. I'd thus recommend seeing if it is Enumerable
. That also guarantees the existence of #count
.
For example,
[1,2,3].is_a? Enumerable
[1,2,3].count
note that, while size
, length
and count
all work for arrays, count
is the right meaning here - (for example, 'abc'.length
and 'abc'.size
both work, but 'abc'.count
doesn't work like that).
Caution: a string is_a? Enumerable, so perhaps this isn't what you want... depends on your concept of an array like object.
Your .htaccess
is slightly off. Look at mine:
RewriteEngine On
RewriteBase /codeigniter
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
RewriteRule ^(.*)$ /codeigniter/index.php?/$1 [L]
Notice "codeigniter" in two places.
after that, in your config:
base_url = "http://localhost/codeigniter"
index = ""
Change codeigniter to "ci" whereever appropriate
A stateful app is one that stores information about what has happened or changed since it started running. Any public info about what "mode" it is in, or how many records is has processed, or whatever, makes it stateful.
Stateless apps don't expose any of that information. They give the same response to the same request, function or method call, every time. HTTP is stateless in its raw form - if you do a GET to a particular URL, you get (theoretically) the same response every time. The exception of course is when we start adding statefulness on top, e.g. with ASP.NET web apps :) But if you think of a static website with only HTML files and images, you'll know what I mean.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
I was also getting "Request return with error:parsererror." in the javascript console. In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
function in_arrayi($needle, $haystack) {
return in_array(strtolower($needle), array_map('strtolower', $haystack));
}
Source: php.net in_array manual page.
Lot of people including myself face lot of issues in making this work due to missing some information like, forgetting to convert to Base64, initialization vectors, character set, etc. So I thought of making a fully functional code.
Hope this will be useful to you all: To compile you need additional Apache Commons Codec jar, which is available here: http://commons.apache.org/proper/commons-codec/download_codec.cgi
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encryptor {
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ Base64.encodeBase64String(encrypted));
return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key = "Bar12345Bar12345"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
System.out.println(decrypt(key, initVector,
encrypt(key, initVector, "Hello World")));
}
}
Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$response = $client->request('POST', 'http://www.example.com/files/post', [
'multipart' => [
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'csv_header',
'contents' => 'First Name, Last Name, Username',
'filename' => 'csv_header.csv'
]
]
]);
// PUT
$client->put('http://www.example.com/user/4', [
'body' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
'timeout' => 5
]);
// DELETE
$client->delete('http://www.example.com/user');
Usefull for long server operations.
$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
According to documentation, you can set headers :
// Set various headers on a request
$client->request('GET', '/get', [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
]
]);
If you want more details information, you can use debug
option like this :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
// If you want more informations during request
'debug' => true
]);
Documentation is more explicits about new possibilities.
Git add .
Git status //Check file that being modified
// git reset HEAD --- replace to which file you want to ignore
git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!
git commit -m ''
git push
According to the documentation of the PropertyFile
task, you can append the generated properties to an existing file. You could have a properties file with just the comment line, and have the Ant task append the generated properties.
Here is another way how you can format using 'f-string' format:
print(
f"{'Trades:':<15}{cnt:>10}",
f"\n{'Wins:':<15}{wins:>10}",
f"\n{'Losses:':<15}{losses:>10}",
f"\n{'Breakeven:':<15}{evens:>10}",
f"\n{'Win/Loss Ratio:':<15}{win_r:>10}",
f"\n{'Mean Win:':<15}{mean_w:>10}",
f"\n{'Mean Loss:':<15}{mean_l:>10}",
f"\n{'Mean:':<15}{mean_trd:>10}",
f"\n{'Std Dev:':<15}{sd:>10}",
f"\n{'Max Loss:':<15}{max_l:>10}",
f"\n{'Max Win:':<15}{max_w:>10}",
f"\n{'Sharpe Ratio:':<15}{sharpe_r:>10}",
)
This will provide the following output:
Trades: 2304
Wins: 1232
Losses: 1035
Breakeven: 37
Win/Loss Ratio: 1.19
Mean Win: 0.381
Mean Loss: -0.395
Mean: 0.026
Std Dev: 0.56
Max Loss: -3.406
Max Win: 4.09
Sharpe Ratio: 0.7395
What you are doing here is you are saying that the first column is 15 chars long and it's left justified and second column (values) is 10 chars long and it's right justified.
intent.getAction().equals(SMS_RECEIVED)
I have tried it out successfully.
Here's one that works for both Mac and Linux:
netstat -aln | awk '$6 == "LISTEN" && $4 ~ "[\\.\:]445$"'
In linux you can run
HOST_IP=`hostname -I | awk '{print $1}'`
In macOS your host machine is not the Docker host. Docker will install it's host OS in VirtualBox.
HOST_IP=`docker run busybox ping -c 1 docker.for.mac.localhost | awk 'FNR==2 {print $4}' | sed s'/.$//'`
I had a similar problem and solved it this way.
My working directory is a general script folder and serveral particular script folder in same root, i need to call particular script folder (which call general script with the parameter of the particular problem). So working directory is like this
\Nico\Scripts\Script1.ps1
\Script2.ps1
\Problem1\Solution1.ps1
\ParameterForSolution1.config
\Problem2\Solution2.ps1
\ParameterForSolution2.config
Solutions1 and Solutions2 call the PS1 in Scripts folder loading the parameter stored in ParameterForSolution. So in powershell ISE i run this command
.\Nico\Problem1\Solution1.PS1
And the code inside Solution1.PS1 is:
# This is the path where my script is running
$path = split-path -parent $MyInvocation.MyCommand.Definition
# Change to root dir
cd "$path\..\.."
$script = ".\Script\Script1.PS1"
$parametro = "Problem1\ParameterForSolution1.config"
# Another set of parameter Script1.PS1 can receive for debuggin porpuose
$parametro +=' -verbose'
Invoke-Expression "$script $parametro"
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
No.
You get charged for:
So... if you stop the EC2 instance you will only have to pay for the storage of the image on S3 (assuming you store an image ofcourse) and any IP addresses you've reserved.
You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).
Instant.now() // Get current moment in UTC, then…
.get( ChronoField.MILLI_OF_SECOND ) // interrogate a `TemporalField`.
2017-04-25T03:01:14.113Z ?
113
See this code run live at IdeOne.com.
The modern way is with the java.time classes.
Capture the current moment in UTC.
Instant.now()
Use the Instant.get
method to interrogate for the value of a TemporalField
. In our case, the TemporalField
we want is ChronoField.MILLI_OF_SECOND
.
int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ; // Get current moment in UTC, then interrogate a `TemporalField`.
Or do the math yourself.
More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant
but there are so many anomalies with time zones, I hesitate to make that assumption.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;
Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.
long nanosFractionOfSecond = zdt.getNano();
If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.
long millis = ( nanosFractionOfSecond / 1_000_000L ) ; // Truncate nanoseconds to milliseconds, by a factor of one million.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/
They call it a multi-root workspace, and with that you can do debugging easily because:
"With multi-root workspaces, Visual Studio Code searches across all folders for launch.json debug configuration files and displays them with the folder name as a suffix."
Say you have a server and a client folder inside your application folder. If you want to debug them together, without a workspace you have to start two Visual Studio Code instances, one for server, one for client and you need to switch back and forth.
But right now (1.24) you can't add a single file to a workspace, only folders, which is a little bit inconvenient.
In my case, I was missing the setting.gradle
file.
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
If you are building the code yourself, then this issue could be overcome by giving "-target 1.5" to the java compiler (or by setting the corresponding option in your IDE or your build config).
if you have an iframe using Google map embedded API like this :
<iframe width="320" height="400" frameborder="0" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>
you can add this css style: pointer-event:none; ES.
<iframe width="320" height="400" frameborder="0" style="pointer-event:none;" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>
In my opinion FirstOrDefault
is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault()
is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details. IMO most of the times SingleOrDefault()
is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.
You can using the exists
if (pricePublicList.Exists(x => x.Size == 200))
{
//code
}
XMLHttpRequest, i.e. AJAX, without the XML.
The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:
var client = new XMLHttpRequest(); client.open('GET', '/foo.txt'); client.onreadystatechange = function() { alert(client.responseText); } client.send();
Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.
One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.
This code gets the maximum value from the maxlength
attribute of the textarea
and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try
;WITH ue(id)
AS
(
SELECT MAX(id)
FROM table
GROUP BY email
)
SELECT * FROM table t
INNER JOIN ue ON ue.id = t.id
@Entity(name = "someThing")
=> this name will be used to identify the domain ..this name will only be identified by hql
queries ..ie ..name of the domain object
@Table(name = "someThing")
=> this name will be used to which table referred by domain object..ie ..name of the table
The most simple way to get user input would be to use Scanner. Here's an example of how it's supposed to be used:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();
The line of code import java.util.Scanner;
tells the program that the programmer will be using user inputs in their code. Like it says, it imports the scanner utility. Scanner sc=new Scanner(System.in);
tells the program to start the user inputs. After you do that, you must make a string or integer without a value, then put those in the line a=sc.nextInt();
or a=sc.nextLine();
. This gives the variables the value of the user inputs. Then you can use it in your code. Hope this helps.
Set JAVA_HOME
in environment variable.
set JAVA_HOME
to only JDK1.6.0_23
or whatever jdk folder
you have. dont include bin
folder in path.
In your regex you need to escape the dot "\."
or use it inside a character class "[.]"
, as it is a meta-character in regex, which matches any character.
Also, you need \w+
instead of \w
to match one or more word characters.
Now, if you want the test.this
content, then split
is not what you need. split
will split your string around the test.this
. For example:
>>> re.split(r"\b\w+\.\w+@", s)
['blah blah blah ', 'gmail.com blah blah']
You can use re.findall
:
>>> re.findall(r'\w+[.]\w+(?=@)', s) # look ahead
['test.this']
>>> re.findall(r'(\w+[.]\w+)@', s) # capture group
['test.this']
check if its not a issue with umask
if (!function_exists('mkdir_r')) {
/**
* create directory recursively
* @param $dirName
* @param int $rights
* @param string $dir_separator
* @return bool
*/
function mkdir_r($dirName, $rights = 0744, $dir_separator = DIRECTORY_SEPARATOR) {
$dirs = explode($dir_separator, $dirName);
$dir = '';
$created = false;
foreach ($dirs as $part) {
$dir .= $part . $dir_separator;
if (!is_dir($dir) && strlen($dir) > 0) {
$created = mkdir($dir, $rights);
}
}
return $created;
}
}
if (!function_exists('ensure_dir')) {
/**
* ensure directory exist if not create
* @param $dir_path
* @param int $mode
* @param bool $use_mask
* @param int $mask
* @return bool
*/
function ensure_dir($dir_path, $mode = 0744, $use_mask = true, $mask = 0002) {
// set mask
$old_mask = $use_mask && $mask != null
? umask($mask)
: null;
try {
return is_dir($dir_path) || mkdir_r($dir_path, $mode);
} finally {
if ($use_mask && $old_mask != null) {
// restore original
umask($old_mask);
}
}
}
}
Include required imports and you can make ur decision in handleError method Error status will give the error code
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model';
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
catchError(this.handleError)
);
}
There's a few useful functions for dealing with errno
s. (Just to make it clear, these are built-in to libc
-- I'm just providing sample implementations because some people find reading code clearer than reading English.)
#include <string.h>
char *strerror(int errnum);
/* you can think of it as being implemented like this: */
static char strerror_buf[1024];
const char *sys_errlist[] = {
[EPERM] = "Operation not permitted",
[ENOENT] = "No such file or directory",
[ESRCH] = "No such process",
[EINTR] = "Interrupted system call",
[EIO] = "I/O error",
[ENXIO] = "No such device or address",
[E2BIG] = "Argument list too long",
/* etc. */
};
int sys_nerr = sizeof(sys_errlist) / sizeof(char *);
char *strerror(int errnum) {
if (0 <= errnum && errnum < sys_nerr && sys_errlist[errnum])
strcpy(strerror_buf, sys_errlist[errnum]);
else
sprintf(strerror_buf, "Unknown error %d", errnum);
return strerror_buf;
}
strerror
returns a string describing the error number you've passed to it. Caution, this is not thread- or interrupt-safe; it is free to rewrite the string and return the same pointer on the next invocation. Use strerror_r
if you need to worry about that.
#include <stdio.h>
void perror(const char *s);
/* you can think of it as being implemented like this: */
void perror(const char *s) {
fprintf(stderr, "%s: %s\n", s, strerror(errno));
}
perror
prints out the message you give it, plus a string describing the current errno
, to standard error.
There are many ways of doing it, I'm listing a few here:
Use SizedBox
if you want to set some specific space
Row(
children: <Widget>[
Text("1"),
SizedBox(width: 50), // give it width
Text("2"),
],
)
Use Spacer
if you want both to be as far apart as possible.
Row(
children: <Widget>[
Text("1"),
Spacer(), // use Spacer
Text("2"),
],
)
Use mainAxisAlignment
according to your needs:
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, // use whichever suits your need
children: <Widget>[
Text("1"),
Text("2"),
],
)
Use Wrap
instead of Row
and give some spacing
Wrap(
spacing: 100, // set spacing here
children: <Widget>[
Text("1"),
Text("2"),
],
)
Other solutions are great but they didn't take care of the fact that watermark shouldn't get selected on selection from the mouse. This fiddle takes care or that: https://jsfiddle.net/MiKr13/d1r4o0jg/9/
This will be better option for pdf or static html.
CSS:
#watermark {
opacity: 0.2;
font-size: 52px;
color: 'black';
background: '#ccc';
position: absolute;
cursor: default;
user-select: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
right: 5px;
bottom: 5px;
}
Updating my Java SDK to the latest version 1.7.0_79
and updating the SDK Location
under Project Structure
solved the problem for me.
.schema in sqlite console when you have you're inside the table it looks something like this for me ...
sqlite>.schema
CREATE TABLE players(
id integer primary key,
Name varchar(255),
Number INT,
Team varchar(255)
You mean you want to add a new row and only put data in a certain column? Try the following:
var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);
As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value
instead of whatever data type you imagine it would be.
As you mentioned in OP, you need to overlay Text
on ImageView
programmatically way. You can get ImageView
drawable and write on it with the help of putting it on Canvas
and Paint
.
private BitmapDrawable writeTextOnDrawable(int drawableId, String text)
{
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(11);
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
canvas.drawText(text, xPos, yPos, paint);
return new BitmapDrawable(getResources(), bm);
}
How do I round this down to, say, 1.543 when I print
totalWorkTimeInHours
?
To round totalWorkTimeInHours
to 3 digits for printing, use the String
constructor which takes a format
string:
print(String(format: "%.3f", totalWorkTimeInHours))
OK, I have found the problem.
I use some reporting plugins. In the documentation of the failsafe-maven-plugin
I found, that the <encoding>
configuration - of course - uses ${project.reporting.outputEncoding}
by default.
So I added the property as a child element of the project
element and everything is fine now:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
See also http://maven.apache.org/general.html#encoding-warning
So far as my observation goes, any answer posted here can have unexpected side effects.
In ES2015-compatible enviroment, you can avoid any side effects by using WeakMap.
const id = (() => {
let currentId = 0;
const map = new WeakMap();
return (object) => {
if (!map.has(object)) {
map.set(object, ++currentId);
}
return map.get(object);
};
})();
id({}); //=> 1
The alignment-baseline
property is what you're looking for it can take the following values
auto | baseline | before-edge | text-before-edge |
middle | central | after-edge | text-after-edge |
ideographic | alphabetic | hanging | mathematical |
inherit
Description from w3c
This property specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes. It defaults to the baseline with the same name as the computed value of the alignment-baseline property. That is, the position of "ideographic" alignment-point in the block-progression-direction is the position of the "ideographic" baseline in the baseline-table of the object being aligned.
Unfortunately, although this is the "correct" way of achieving what you're after it would appear Firefox have not implemented a lot of the presentation attributes for the SVG Text Module ('SVG in Firefox' MDN Documentation)
maybe you benefit from converting it to JSON string
String jsonString = new com.google.gson.Gson().toJson(myObject);
in my case, I wanted to add an object to the response headers but you cant add objects to the headers,
so to solve this I convert my object to JSON string and in the client side I will return that string to JSON again
addition of <mvc:annotation-driven/>
worked for me.
Add it before line <context:component-scan ............/>
This should get you started:
R> qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))
See also this question: How can I manipulate the strip text of facet plots in ggplot2?
Ensure the device is running.
Execute the following in terminal:
open ~/Library/Developer/CoreSimulator/Devices/$(xcrun simctl list | grep Booted | grep -Eo '[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*-[a-zA-Z0-9]*')/data/Media/DCIM
Further regex ref @ https://regex101.com/r/tY951n/3
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
A major practical difference is its use:
in security scenario
where we always needed a new session, we should use request.getSession(true)
.
request.getSession(false): will return null if no session found.
while using Google App Engine, i had this problem. For some reason i did following since then Google App Engine was never starting.
$ echo '' > /tmp/appengine.apprtc.root/*.db
To fix it i required to do manually:
$ sqlite3 datastore.db
sqlite> begin immediate;
<press CTRL+Z>
$ cp datastore.db logs.db
And then run the Google App Engine with flag:
$ dev_appserver.py --clear_datastore --clear_search_index
after that it finally worked.
While a bit more cryptic than join
, you can also multiply the array by a string.
@arr * " "
You need to put your main code on the OnStart
method.
This other SO answer of mine might help.
You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.
EDIT:
Please see also the documentation available here for the OnStart
method at the MSDN where one can read this:
Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.
Since the encoding that turns "the Family" into "t?? T???ly" is effectively random and not following any algorithm that can be explained by the information of the Unicode codepoints involved, there's no general way to solve this algorithmically.
You will need to build the mapping of Unicode characters into latin characters which they resemble. You could probably do this with some smart machine learning on the actual glyphs representing the Unicode codepoints. But I think the effort for this would be greater than manually building that mapping. Especially if you have a good amount of examples from which you can build your mapping.
To clarify: a few of the substitutions can actually be solved via the Unicode data (as the other answers demonstrate), but some letters simply have no reasonable association with the latin characters which they resemble.
Examples:
Was someone able to have a timepicker working with Bootstrap 3.4?
Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()
You can also use:
map.setView(new L.LatLng(40.737, -73.923), 8);
It just depends on what behavior you want. map.panTo()
will pan to the location with zoom/pan animation, while map.setView()
immediately set the new view to the desired location/zoom level.
The following is my configuration:
cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})
add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )
Unfortunately there is no cross platform macro which defines 32 / 64 bit across the major compilers. I've found the most effective way to do this is the following.
First I pick my own representation. I prefer ENVIRONMENT64 / ENVIRONMENT32. Then I find out what all of the major compilers use for determining if it's a 64 bit environment or not and use that to set my variables.
// Check windows
#if _WIN32 || _WIN64
#if _WIN64
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
// Check GCC
#if __GNUC__
#if __x86_64__ || __ppc64__
#define ENVIRONMENT64
#else
#define ENVIRONMENT32
#endif
#endif
Another easier route is to simply set these variables from the compiler command line.
Use the utf8 module from npm to encode/decode the string.
Installation:
npm install utf8
In a browser:
<script src="utf8.js"></script>
In Node.js:
const utf8 = require('utf8');
API:
Encode:
utf8.encode(string)
Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. (If you need to be able to encode non-scalar values as well, use WTF-8 instead.)
// U+00A9 COPYRIGHT SIGN; see http://codepoints.net/U+00A9
utf8.encode('\xA9');
// ? '\xC2\xA9'
// U+10001 LINEAR B SYLLABLE B038 E; see http://codepoints.net/U+10001
utf8.encode('\uD800\uDC01');
// ? '\xF0\x90\x80\x81'
Decode:
utf8.decode(byteString)
Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. It throws an error when malformed UTF-8 is detected. (If you need to be able to decode encoded non-scalar values as well, use WTF-8 instead.)
utf8.decode('\xC2\xA9');
// ? '\xA9'
utf8.decode('\xF0\x90\x80\x81');
// ? '\uD800\uDC01'
// ? U+10001 LINEAR B SYLLABLE B038 E
Here you can find a nice tutorial of how you can create and consume a SOAP service through WSDL. Long story short you need to call wsimport tool from command line (you can find it in your jdk) with parameters like -s (source for .java files) -d (destination for .class files) and the wsdl link.
$ wsimport -s "C:\workspace\soap\src\main\java\com\test\soap\ws" -d "C:\workspace\soap\target\classes\com\test\soap\ws" http://localhost:8855/soap/test?wsdl
After the stubs are created, you can call the webservices very easy something like:
TestHarnessService harnessService = new TestHarnessService();
ITestApi testApi = harnessService.getBasicHttpBindingITestApi();
testApi.resetLogMemoryTarget();
MYSQL PROCEDURE steps:
DELIMITER //
create PROCEDURE, you can refer syntax
NOTE: Don't forget to end statement with ' ; '
create procedure ProG() begin SELECT * FROM hs_hr_employee_leave_quota; end;//
delimiter ;
call ProG();
@Maxim
try this...
pom.xml
<groupId>org.opensource</groupId>
<artifactId>base</artifactId>
<version>1.0.0.SNAPSHOT</version>
..............
<properties>
<my.version>4.0.8.8</my.version>
</properties>
<build>
<finalName>my-base-project</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<goals>
<goal>install-file</goal>
</goals>
<phase>install</phase>
<configuration>
<file>${project.build.finalName}.${project.packaging}</file>
<generatePom>false</generatePom>
<pomFile>pom.xml</pomFile>
<version>${my.version}</version>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Commnad mvn clean install
Output
[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ base ---
[INFO] Building jar: D:\dev\project\base\target\my-base-project.jar
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ base ---
[INFO] Installing D:\dev\project\base\target\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\1.0.0.SNAPSHOT\base-1.0.0.SNAPSHOT.pom
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default) @ base ---
[INFO] Installing D:\dev\project\base\my-base-project.jar to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.jar
[INFO] Installing D:\dev\project\base\pom.xml to H:\dev\.m2\repository\org\opensource\base\4.0.8.8\base-4.0.8.8.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
This works for me:
printf "%b" "\e[1;34mThis is a blue text.\e[0m"
From printf(1)
:
%b ARGUMENT as a string with '\' escapes interpreted, except that octal escapes are of the form \0 or \0NNN
See this answer; in Chrome and Safari you can use the following style to disable the default dragging:
-webkit-user-drag: auto | element | none;
You could try user-select for Firefox and IE(10+):
-moz-user-select: none | text | all | element
-ms-user-select: none | text | all | element
I don't think "Ruby has X and Python doesn't, while Python has Y and Ruby doesn't" is the most useful way to look at it. They're quite similar languages, with many shared abilities.
To a large degree, the difference is what the language makes elegant and readable. To use an example you brought up, both do theoretically have lambdas, but Python programmers tend to avoid them, and constructs made using them do not look anywhere near as readable or idiomatic as in Ruby. So in Python, a good programmer will want to take a different route to solving the problem than he would in Ruby, just because it actually is the better way to do it.
Just small change need in test.ts
file inside src folder:
const context = require.context('./', true, /test-example\.spec\.ts$/);
Here, test-example
is the exact file name which we need to run
In the same way, if you need to test the service file only you can replace the filename like "/test-example.service"
For quick overview comparisons, I really like this website, that has many comparison pages, eg AWS DynamoDB vs MongoDB; http://db-engines.com/en/system/Amazon+DynamoDB%3BMongoDB
Use a UI library, like jquery or yui, that provides an alternative to the native SELECT element, typically as part of the implementation of a combo box.
you can use $nbsp; for a single space, if you like just using single allows you single space instead of using creating own class
<div id="bulkOptionContainer" class="col-xs-4">
<select class="form-control" name="" id="">
<option value="">Select Options</option>
<option value="">Published</option>
<option value="">Draft</option>
<option value="">Delete</option>
</select>
</div>
<div class="col-xs-4">
<input type="submit" name="submit" class="btn btn-success " value="Apply">
<a class="btn btn-primary" href="add_posts.php">Add post</a>
</div>
</form>
You should check logs If you see like below "stacktrace": ["java.lang.IllegalStateException: Received message from unsupported version: [6.4.3] minimal compatible version is: [6.8.0]"
You can check this link https://discuss.elastic.co/t/java-client-or-spring-boot-for-elasticsearch-7-3-1/199778 You have to explicit declare es version.
Oneliner:
array = [] << 1 << 2 << 3 #this is for fixnums.
or
a = %w| 1 2 3 4 5 |
or
a = [*'1'..'3']
or
a = Array.new(3, '1')
or
a = Array[*'1'..'3']
private int CountWords(string text, string word) {
int count = (text.Length - text.Replace(word, "").Length) / word.Length;
return count;
}
Because the original solution, was the fastest for chars, I suppose it will also be for strings. So here is my contribution.
For the context: I was looking for words like 'failed' and 'succeeded' in a log file.
Gr, Ben
If you are using it in a script, use stat
.
$ date | tee /tmp/foo
Wed Mar 13 05:36:31 UTC 2019
$ stat -c %s /tmp/foo
29
$ ls -l /tmp/foo
-rw-r--r-- 1 bruno wheel 29 Mar 13 05:36 /tmp/foo
That will give you size in bytes. See man stat
for more output format options.
The OSX/BSD equivalent is:
$ date | tee /tmp/foo
Wed Mar 13 00:54:16 EDT 2019
$ stat -f %z /tmp/foo
29
$ ls -l /tmp/foo
-rw-r--r-- 1 bruno wheel 29 Mar 13 00:54 /tmp/foo
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
For the GUI itself:
PyQT is pretty much the reference.
Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.
Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.
Update (using renderer):
Note that the original Renderer service has now been deprecated in favor of Renderer2
as on Renderer2 official doc.
Furthermore, as pointed out by @GünterZöchbauer:
Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.
You can achieve this by using elementRef
as well as by ViewChild
. however it's not recommendable to use elementRef
due to:
as pointed out by official ng2 documentation.
elementRef
(Direct Access):export class MyComponent {
constructor (private _elementRef : ElementRef) {
this._elementRef.nativeElement.querySelector('textarea').focus();
}
}
ViewChild
(better approach):<textarea #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}"
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var
export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
renderer
:export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
constructor(private renderer: Renderer2){
}
ngAfterViewInit() {
//using selectRootElement instead of depreaced invokeElementMethod
this.renderer.selectRootElement(this.input["nativeElement"]).focus();
}
}
Please try below:
myDropDown.SelectedIndex =
myDropDown.Items.IndexOf(myDropDown.Items.FindByValue("myValue"))
Use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
You can even improve your form processing by stripping all tags with strip_tags()
and remove all white spaces with trim()
:
function processText($text) {
$text = strip_tags($text);
$text = trim($text);
$text = htmlspecialchars($text);
return $text;
}
echo processText($_POST['contact_list']);
Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.
There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API
It includes an answer to your question here: Updates & creation should return a resource representation
It says:
To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.
Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.
toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.
var fval = 4;
console.log(fval.toFixed(2)); // prints 4.00
It may be easier. Try to think like this:
:
// 'www.dev.yyy.com'
// 'xxx.foo.pl'
var url = "xxx.foo.pl";
switch (url.match(/\..*.\./)[0]){
case ".dev.yyy." :
console.log("xxx.dev.yyy.com");break;
case ".some.":
console.log("xxx.foo.pl");break;
} //end switch
Version 3.6+: Use a formatted string literal, f-string for short
print(f"{i}. {key} appears {wordBank[key]} times.")
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (It's either a case of Great mind thinking alike or they read my answer :)
End Update
If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.
@Html.EditorFor(modelItem => item.YourProperty,
new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px" } })
then in your template (not required for simple types in MVC 5.1)
@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])
The following worked for me, I'm not sure what part did the trick:
julian:project$ sudo service docker status
julian:varys$ sudo service docker status
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2020-07-15 01:21:16 UTC; 24min ago
Docs: https://docs.docker.com
Main PID: 6762 (dockerd)
Tasks: 25
CGroup: /system.slice/docker.service
+-6762 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
julian:project$ export DOCKER_HOST=unix:///run/containerd/containerd.sock
julian:project$ sudo groupadd docker
groupadd: group 'docker' already exists
julian:project$ sudo gpasswd -a $USER docker
Adding user ubuntu to group docker
julian:project$ newgrp docker
julian:project$ ls -ln /var/run/ | grep docker
drwx------ 5 0 0 120 Jul 15 01:10 docker
-rw-r--r-- 1 0 0 4 Jul 15 01:10 docker.pid
srw-rw---- 1 0 999 0 Jul 15 01:10 docker.sock
julian:project$ sudo rm /var/run/docker.sock
julian:project$ sudo rm /var/run/docker.pid
julian:project$ sudo service docker restart
Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.
public interface ICalculator
{
void Add(int a, int b);
}
public class Calculator : ICalculator
{
public void Add(int a, int b)
{
return a + b;
}
}
You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).
IoCLlibrary.Register<ICalculator>.Return<Calculator>();
So now when you want an instance of an ICalculator you just...
Calculator calc = IoCLibrary.Resolve<ICalculator>();
IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.
Now let's say you have a class that relies on an ICalculator to be present you could have..
public class BankingSystem
{
public BankingSystem(ICalculator calc)
{
_calc = calc;
}
private ICalculator _calc;
}
And you can setup the library to inject a object into the constructor when it's created.
So DI or Dependency Injection means to inject any object another might require.
Where does the variable results come from?
This block:
foreach (People p in ppl.results) {
list.Add(results.name);
list.Add(results.email);
list2d.Add(list);
}
Should probably read more like:
foreach (People p in ppl.results) {
var list = new List<string>();
list.Add(p.name);
list.Add(p.email);
list2d.Add(list);
}
Here you go:
.glowing-border {
border: 2px solid #dadada;
border-radius: 7px;
}
.glowing-border:focus {
outline: none;
border-color: #9ecaed;
box-shadow: 0 0 10px #9ecaed;
}
Live demo: http://jsfiddle.net/simevidas/CXUpm/1/show/
(to view the code for the demo, remove "show/" from the URL)
label { _x000D_
display:block;_x000D_
margin:20px;_x000D_
width:420px;_x000D_
overflow:auto;_x000D_
font-family:sans-serif;_x000D_
font-size:20px;_x000D_
color:#444;_x000D_
text-shadow:0 0 2px #ddd;_x000D_
padding:20px 10px 10px 0;_x000D_
}_x000D_
_x000D_
input {_x000D_
float:right;_x000D_
width:200px;_x000D_
border:2px solid #dadada;_x000D_
border-radius:7px;_x000D_
font-size:20px;_x000D_
padding:5px;_x000D_
margin-top:-10px; _x000D_
}_x000D_
_x000D_
input:focus { _x000D_
outline:none;_x000D_
border-color:#9ecaed;_x000D_
box-shadow:0 0 10px #9ecaed;_x000D_
}
_x000D_
<label> Aktuelles Passwort: <input type="password"> </label>_x000D_
<label> Neues Passwort: <input type="password"> </label>
_x000D_
If I understood well, you want to remove a specific character only if it is at the beginning or at the end of the string (ex: ||fo||oo||||
should become foo||oo
). You can create an ad hoc function as follows:
function trimChar(string, charToRemove) {
while(string.charAt(0)==charToRemove) {
string = string.substring(1);
}
while(string.charAt(string.length-1)==charToRemove) {
string = string.substring(0,string.length-1);
}
return string;
}
I tested this function with the code below:
var str = "|f|oo||";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "Trimmed: '" + trimChar(str, "|") + "'" );
I faced same problem and tried above solutions but none of them worked for me. Then I tried following steps and the problem was solved:
*.jar
file as external jar.You might be interested in visiting this blog post concerning all the possible ways to assign an attribute or update record (updated to Rails 4) update_attribute, update, update_column, update_columns etc.
http://www.davidverhasselt.com/set-attributes-in-activerecord/. For example it differs in aspects such as running validations, touching object's updated_at or triggering callbacks.
As an answer to the OP's question update_attribute
does not by pass callbacks.
To make it lighter and faster I suggest to use direct filling of a string.
template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I)<<1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len,'0');
for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
rc[i] = digits[(w>>j) & 0x0f];
return rc;
}
Use strncpy
e.g.
strncpy(dest, src + beginIndex, endIndex - beginIndex);
This assumes you've
dest
is large enough.endIndex
is greater than beginIndex
beginIndex
is less than strlen(src)
endIndex
is less than strlen(src)
In python re, you can span from numberic to upper case alpha. So..
import re
test = "01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK"
re.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars
## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']
re.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars
## ['01234ABCDEF', '01234', 'ABCDEF']
re.compile(r'[0-F]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-f]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
That makes the simplest Python UUID regex:
re_uuid = re.compile("[0-F]{8}-([0-F]{4}-){3}[0-F]{12}", re.I)
I'll leave it as an exercise to the reader to use timeit to compare the performance of these.
Enjoy. Keep it Pythonic™!
NOTE: Those spans will also match :;<=>?@'
so, if you suspect that could give you false positives, don't take the shortcut. (Thank you Oliver Aubert for pointing that out in the comments.)
One way to achieve similar effect would be through CSS:
<td>Cell content.
<div class="popup">
This is the popup.
<br>
Another line of popup.
</div>
</td>
And then use the following in CSS:
td div.popup { display: none; }
td:hover div.popup { display: block; position: absolute; }
You will want to add some borders and background to make the popup look decent, but this should sketch the idea. It has some drawbacks though, for example the popup is not positioned relative to mouse but relative to the containing cell.
You can try this-
$('#selectID').append($('<option>',
{
value: value_variable,
text : text_variable
}));
Like this-
for (i = 0; i < 10; i++)_x000D_
{ _x000D_
$('#mySelect').append($('<option>',_x000D_
{_x000D_
value: i,_x000D_
text : "Option "+i _x000D_
}));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<select id='mySelect'></select>
_x000D_
Or try this-
$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );
Like this-
for (i = 0; i < 10; i++)_x000D_
{ _x000D_
$('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<select id='mySelect'></select>
_x000D_
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use theStop
statement instead. You can then resume execution while preserving the value of those variables.Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
You have to use latest version with SSMS
You can check latest builds via this page https://sqlserverbuilds.blogspot.com/
If your just interested in sharing complex data types between javascript and python, check out jsonpickle. It wraps the standard Python JSON libraries, but has some smarts in serializing and deserializing Python classes and other data types.
Quite a few Google App Engine projects have used this library. Joose and FirePython both incorporate jsonpickle.
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;
Here's the whole code snippet needed:
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
To produce key events without Windows Forms Context, We can use the following method,
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
sample code is given below:
const int VK_UP = 0x26; //up key
const int VK_DOWN = 0x28; //down key
const int VK_LEFT = 0x25;
const int VK_RIGHT = 0x27;
const uint KEYEVENTF_KEYUP = 0x0002;
const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
int press()
{
//Press the key
keybd_event((byte)VK_UP, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
return 0;
}
List of Virtual Keys are defined here.
To get the complete picture, please use the below link, http://tksinghal.blogspot.in/2011/04/how-to-press-and-hold-keyboard-key.html
sc delete sericeName
Just make sure the service is stopped before doing this. I have seen this work most times. There are times where I have seen windows get stuck on something and it insists on a reboot.
Inheritance or generalization is an example of high coupling (i.e. high interdependence). What I meant by this is that in inheritance often the parent class defines base functionalities that is used by its child class and change in methods of parent class directly impact its child classes. Hence we can say that there is a greater degree of interdependence between classes.
Realization or using interface is an example of high cohesion (i.e. low interdependence). What this means is that an interface put forward a contract for any class that implements it but each class has the right to implement methods declared in interface in its own way and changes in method declared in one class doesn't affect any other class.
www.somesite.com/Transaction_List.jsp?accountID=5
For this URL
there is a method call request.getParameter
in java , if you want a number here cast into int
, similarly for string value cast into string
. so for your requirement , just copy past below line in page,
int accountId =(int)request.getParameter("accountID");
you can now call this value useing accountId
in whole page.
here accountId
is name of parameter you can also get more than one parameters using this, but this not work. It will only work with GET
method if you hit POST
request then their will be an error.
Hope this is helpful.
$month=01;
$year=2015;
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo $num;
display 31 last day of date
here is how to give permission for one user not public,
Direct Query:
Use MyDatabase
Grant execute on [dbo].[My-procedures-name] to [IIS APPPOOL\my-iis-pool]
Go
If you are using the IN
operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS
, the SQL engine will stop the scanning process as soon as it found a match.
This appears to be a bug in the way jQuery ships. You can fix it manually with some dom manipulation on the Dialog Open
event:
$("#selector").dialog({
open: function() {
$(this).closest(".ui-dialog")
.find(".ui-dialog-titlebar-close")
.removeClass("ui-dialog-titlebar-close")
.html("<span class='ui-button-icon-primary ui-icon ui-icon-closethick'></span>");
}
});
Try setting host=127.0.0.1 on your db settings file, it worked for me! :)
Hope it helps!
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
<a href="page.html" onclick="return false" style="cursor:default;">page link</a>
The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead:
Sheets("Zeros").UsedRange.ClearContents
Alternately, you can delete the sheet and re-add it:
Application.DisplayAlerts = False
Sheets("Zeros").Delete
Application.DisplayAlerts = True
Dim sheet As Worksheet
Set sheet = Sheets.Add
sheet.Name = "Zeros"
To solve, you need to import Private Certificate (PFX).
If you don't have PFX, use OpenSSL to generate it:
Open command line and run:
openssl pkcs12 -export -in public_certificate.cer -inkey server.key -out private_certificate.pfx
Than, install private_certificate.pfx (right click -> Install Certificate).
Now, your certificate does not disappear anymore and you can bind Website over SSL.
A great resource: https://blog.lextudio.com/the-whole-story-of-server-certificate-disappears-in-iis-7-7-5-8-8-5-10-0-after-installing-it-why-b66e802baa38
While the OP is the original author of the database, and likely created a simple data model, I had experienced a similar behavior on a more complicated system. In my scenario the main .mdb file was on a network share location with read/write access by the user. The .mdb file referenced tables in another .mdb file in a different network location - where the user did not have proper access.
For others viewing this post to solve similar problems, verify the linked tables path and access.
To verify linked tables...(assuming Access 2010)
REGEXP_COUNT wasn't added until Oracle 11i. Here's an Oracle 10g solution, adopted from Art's solution.
SELECT trim(regexp_substr('Err1, Err2, Err3', '[^,]+', 1, LEVEL)) str_2_tab
FROM dual
CONNECT BY LEVEL <=
LENGTH('Err1, Err2, Err3')
- LENGTH(REPLACE('Err1, Err2, Err3', ',', ''))
+ 1;
I've found this snippet as an alternative solution. It's a more graceful removal of libraries than remaking the virtualenv:
pip freeze | xargs pip uninstall -y
In case you have packages installed via VCS, you need to exclude those lines and remove the packages manually (elevated from the comments below):
pip freeze | grep -v "^-e" | xargs pip uninstall -y
Easy way to shutdown mySQL server for Windows7 :
My Computer > Manage > Services and Application > Services > select "MySQL 56"(the name depends upon the version of MySQL installed.) three options are present at left top corner. Stop the Service pause the Service Restart the Service
choose Stop the service > to stop the server
Again to start you can come to the same location or we can chose tools options on mySQL GUI Server > Startup/Shutdown > Choose to Startup or Shutdown
PS: some times it is not possible to stop the server from the GUI even though the options are provided. so is the reason the above alternative method is provided.
share the ans. to improve. thanks
Declare this in your CSS and you should be good:
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
This solution can be implemented without using additional wrappers.
This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.
These attributes must be included in the textview
tag in order to allow scrolling.
Everything else is optional.
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:ellipsize="marquee"
This may be helpful if you have more than one python versions installed and dont know how to tell your ide's to use a specific version.
anaconda
. Latest version can be found hereanaconda-navigator
in terminalcreate
and then choose your python version in that. install
in that. Hope it helps!!
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
For cases like this, the effect is the same: You end up passing the address of the first character in a string of characters.
The declarations are obviously not the same though.
The following sets aside memory for a string and also a character pointer, and then initializes the pointer to point to the first character in the string.
char *p = "hello";
While the following sets aside memory just for the string. So it can actually use less memory.
char p[10] = "hello";
This button post to the current page while at the same time opens OtherPage.aspx
in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />
In Server 2008 the startup folder for individual users is here:
C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
For All Users it's here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
Hope that helps
My ECMAScript proposal for String.prototype.toKebabCase
.
String.prototype.toKebabCase = function () {
return this.valueOf().replace(/-/g, ' ').split('')
.reduce((str, char) => char.toUpperCase() === char ?
`${str} ${char}` :
`${str}${char}`, ''
).replace(/ * /g, ' ').trim().replace(/ /g, '-').toLowerCase();
}
Another approach starting from 0
and returning a String
public static String getCharForNumber(int i) {
return i < 0 || i > 25 ? "?" : String.valueOf((char) ('A' + i));
}
Parasoft is a tool which can do this. I've done this very thing using this tool in my past work place. You can generate a request in Parasoft SOATest and get a response in Parasoft Virtualize. It does cost though. However Parasoft Virtualize now has a free community edition from which you can generate response messages from a WSDL. You can download from parasoft community edition
You can read data direct from some file and plot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from sys import argv
x,y,z = np.loadtxt('your_file', unpack=True)
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('teste.pdf')
plt.show()
If necessary you can pass vmin and vmax to define the colorbar range, e.g.
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1, vmin=0, vmax=2000)
I was wondering how to do some interactive plots, in this case with artificial data
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import Image
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
def plot(i):
fig = plt.figure()
ax = plt.axes(projection='3d')
theta = 2 * np.pi * np.random.random(1000)
r = i * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
fig.tight_layout()
interactive_plot = interactive(plot, i=(2, 10))
interactive_plot
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pType_in_your_current_password_here password ''
Using zsh
:
a=(*(/N)); echo ${#a}
The N
is a nullglob, /
makes it match directories, #
counts. It will neatly cope with spaces in directory names as well as returning 0
if there are no directories.
Ah, this is one of my favorite subjects. There are essentially two ways you can load a resource through the classpath:
Class.getResourceAsStream(resource)
and
ClassLoader.getResourceAsStream(resource)
(there are other ways which involve getting a URL for the resource in a similar fashion, then opening a connection to it, but these are the two direct ways).
The first method actually delegates to the second, after mangling the resource name. There are essentially two kinds of resource names: absolute (e.g. "/path/to/resource/resource") and relative (e.g. "resource"). Absolute paths start with "/".
Here's an example which should illustrate. Consider a class com.example.A. Consider two resources, one located at /com/example/nested, the other at /top, in the classpath. The following program shows nine possible ways to access the two resources:
package com.example; public class A { public static void main(String args[]) { // Class.getResourceAsStream Object resource = A.class.getResourceAsStream("nested"); System.out.println("1: A.class nested=" + resource); resource = A.class.getResourceAsStream("/com/example/nested"); System.out.println("2: A.class /com/example/nested=" + resource); resource = A.class.getResourceAsStream("top"); System.out.println("3: A.class top=" + resource); resource = A.class.getResourceAsStream("/top"); System.out.println("4: A.class /top=" + resource); // ClassLoader.getResourceAsStream ClassLoader cl = A.class.getClassLoader(); resource = cl.getResourceAsStream("nested"); System.out.println("5: cl nested=" + resource); resource = cl.getResourceAsStream("/com/example/nested"); System.out.println("6: cl /com/example/nested=" + resource); resource = cl.getResourceAsStream("com/example/nested"); System.out.println("7: cl com/example/nested=" + resource); resource = cl.getResourceAsStream("top"); System.out.println("8: cl top=" + resource); resource = cl.getResourceAsStream("/top"); System.out.println("9: cl /top=" + resource); } }
The output from the program is:
1: A.class nested=java.io.BufferedInputStream@19821f 2: A.class /com/example/nested=java.io.BufferedInputStream@addbf1 3: A.class top=null 4: A.class /top=java.io.BufferedInputStream@42e816 5: cl nested=null 6: cl /com/example/nested=null 7: cl com/example/nested=java.io.BufferedInputStream@9304b1 8: cl top=java.io.BufferedInputStream@190d11 9: cl /top=null
Mostly things do what you'd expect. Case-3 fails because class relative resolving is with respect to the Class, so "top" means "/com/example/top", but "/top" means what it says.
Case-5 fails because classloader relative resolving is with respect to the classloader. But, unexpectedly Case-6 also fails: one might expect "/com/example/nested" to resolve properly. To access a nested resource through the classloader you need to use Case-7, i.e. the nested path is relative to the root of the classloader. Likewise Case-9 fails, but Case-8 passes.
Remember: for java.lang.Class, getResourceAsStream() does delegate to the classloader:
public InputStream getResourceAsStream(String name) { name = resolveName(name); ClassLoader cl = getClassLoader0(); if (cl==null) { // A system class. return ClassLoader.getSystemResourceAsStream(name); } return cl.getResourceAsStream(name); }
so it is the behavior of resolveName() that is important.
Finally, since it is the behavior of the classloader that loaded the class that essentially controls getResourceAsStream(), and the classloader is often a custom loader, then the resource-loading rules may be even more complex. e.g. for Web-Applications, load from WEB-INF/classes or WEB-INF/lib in the context of the web application, but not from other web-applications which are isolated. Also, well-behaved classloaders delegate to parents, so that duplicateed resources in the classpath may not be accessible using this mechanism.
Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial
keyword.
form = CustomForm(initial={'Email': GetEmailString()})
See the Django Form docs for more explanation.
If you are trying to change a value after the form was submitted, you can use something like:
if form.is_valid():
form.cleaned_data['Email'] = GetEmailString()
Check the referenced docs above for more on using cleaned_data
It is enough to use color property alongside with -webkit-text-fill-color this way:
input {_x000D_
color: red; /* color of caret */_x000D_
-webkit-text-fill-color: black; /* color of text */_x000D_
}
_x000D_
<input type="text"/>
_x000D_
Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.
The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN
So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.
Except for a few very rare cases (possibly a many-to-many relationship table, or a table you temporarily use for bulk-loading huge amounts of data), I would go with the saying:
If it doesn't have a primary key, it's not a table!
Marc
nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.
btoa
middlestep (no lib)In question title you write about string conversion, but in question you talk about binary data (picture) so here is function which make proper conversion starting from PNG picture binary data (details and reversal conversion here )
function bytesArrToBase64(arr) {
const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // base64 alphabet
const bin = n => n.toString(2).padStart(8,0); // convert num to 8-bit binary string
const l = arr.length
let result = '';
for(let i=0; i<=(l-1)/3; i++) {
let c1 = i*3+1>=l; // case when "=" is on end
let c2 = i*3+2>=l; // case when "=" is on end
let chunk = bin(arr[3*i]) + bin(c1? 0:arr[3*i+1]) + bin(c2? 0:arr[3*i+2]);
let r = chunk.match(/.{1,6}/g).map((x,j)=> j==3&&c2 ? '=' :(j==2&&c1 ? '=':abc[+('0b'+x)]));
result += r.join('');
}
return result;
}
// TEST
const pic = [ // PNG binary data
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff, 0x61, 0x00, 0x00, 0x00,
0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00,
0x01, 0x59, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f,
0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3c, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65,
0x74, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x3d, 0x22,
0x61, 0x64, 0x6f, 0x62, 0x65, 0x3a, 0x6e, 0x73, 0x3a, 0x6d, 0x65, 0x74,
0x61, 0x2f, 0x22, 0x20, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x74, 0x6b, 0x3d,
0x22, 0x58, 0x4d, 0x50, 0x20, 0x43, 0x6f, 0x72, 0x65, 0x20, 0x35, 0x2e,
0x34, 0x2e, 0x30, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64,
0x66, 0x3a, 0x52, 0x44, 0x46, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a,
0x72, 0x64, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f,
0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31,
0x39, 0x39, 0x39, 0x2f, 0x30, 0x32, 0x2f, 0x32, 0x32, 0x2d, 0x72, 0x64,
0x66, 0x2d, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x2d, 0x6e, 0x73, 0x23,
0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x72, 0x64,
0x66, 0x3a, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x72, 0x64, 0x66, 0x3a, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x3d,
0x22, 0x22, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x74, 0x69, 0x66,
0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6e, 0x73,
0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74,
0x69, 0x66, 0x66, 0x2f, 0x31, 0x2e, 0x30, 0x2f, 0x22, 0x3e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x66,
0x66, 0x3a, 0x4f, 0x72, 0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x3e, 0x31, 0x3c, 0x2f, 0x74, 0x69, 0x66, 0x66, 0x3a, 0x4f, 0x72,
0x69, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x44,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x0a,
0x20, 0x20, 0x20, 0x3c, 0x2f, 0x72, 0x64, 0x66, 0x3a, 0x52, 0x44, 0x46,
0x3e, 0x0a, 0x3c, 0x2f, 0x78, 0x3a, 0x78, 0x6d, 0x70, 0x6d, 0x65, 0x74,
0x61, 0x3e, 0x0a, 0x4c, 0xc2, 0x27, 0x59, 0x00, 0x00, 0x00, 0xf9, 0x49,
0x44, 0x41, 0x54, 0x38, 0x11, 0x95, 0x93, 0x3d, 0x0a, 0x02, 0x41, 0x0c,
0x85, 0xb3, 0xb2, 0x85, 0xb7, 0x10, 0x6c, 0x04, 0x1b, 0x0b, 0x4b, 0x6f,
0xe2, 0x76, 0x1e, 0xc1, 0xc2, 0x56, 0x6c, 0x2d, 0xbc, 0x85, 0xde, 0xc4,
0xd2, 0x56, 0xb0, 0x11, 0xbc, 0x85, 0x85, 0xa0, 0xfb, 0x46, 0xbf, 0xd9,
0x30, 0x33, 0x88, 0x06, 0x76, 0x93, 0x79, 0x93, 0xf7, 0x92, 0xf9, 0xab,
0xcc, 0xec, 0xd9, 0x7e, 0x7f, 0xd9, 0x63, 0x33, 0x8e, 0xf9, 0x75, 0x8c,
0x92, 0xe0, 0x34, 0xe8, 0x27, 0x88, 0xd9, 0xf4, 0x76, 0xcf, 0xb0, 0xaa,
0x45, 0xb2, 0x0e, 0x4a, 0xe4, 0x94, 0x39, 0x59, 0x0c, 0x03, 0x54, 0x14,
0x58, 0xce, 0xbb, 0xea, 0xdb, 0xd1, 0x3b, 0x71, 0x75, 0xb9, 0x9a, 0xe2,
0x7a, 0x7d, 0x36, 0x3f, 0xdf, 0x4b, 0x95, 0x35, 0x09, 0x09, 0xef, 0x73,
0xfc, 0xfa, 0x85, 0x67, 0x02, 0x3e, 0x59, 0x55, 0x31, 0x89, 0x31, 0x56,
0x8c, 0x78, 0xb6, 0x04, 0xda, 0x23, 0x01, 0x01, 0xc8, 0x8c, 0xe5, 0x77,
0x87, 0xbb, 0x65, 0x02, 0x24, 0xa4, 0xad, 0x82, 0xcb, 0x4b, 0x4c, 0x64,
0x59, 0x14, 0xa0, 0x72, 0x40, 0x3f, 0xbf, 0xe6, 0x68, 0xb6, 0x9f, 0x75,
0x08, 0x63, 0xc8, 0x9a, 0x09, 0x02, 0x25, 0x32, 0x34, 0x48, 0x7e, 0xcc,
0x7d, 0x10, 0xaf, 0xa6, 0xd5, 0xd2, 0x1a, 0x3d, 0x89, 0x38, 0xf5, 0xf1,
0x14, 0xb4, 0x69, 0x6a, 0x4d, 0x15, 0xf5, 0xc9, 0xf0, 0x5c, 0x1a, 0x61,
0x8a, 0x75, 0xd1, 0xe8, 0x3a, 0x2c, 0x41, 0x5d, 0x70, 0x41, 0x20, 0x29,
0xf9, 0x9b, 0xb1, 0x37, 0xc5, 0x4d, 0xfc, 0x45, 0x84, 0x7d, 0x08, 0x8f,
0x89, 0x76, 0x54, 0xf1, 0x1b, 0x19, 0x92, 0xef, 0x2c, 0xbe, 0x46, 0x8e,
0xa6, 0x49, 0x5e, 0x61, 0x89, 0xe4, 0x05, 0x5e, 0x4e, 0xa4, 0x5c, 0x10,
0x6e, 0x9f, 0xfc, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44,
0xae, 0x42, 0x60, 0x82
];
let b64pic = bytesArrToBase64(pic);
myPic.src = "data:image/png;base64,"+b64pic;
msg.innerHTML = "Base64 encoded pic data:<br>" + b64pic;
_x000D_
img { zoom: 10; image-rendering: pixelated; }
#msg { word-break: break-all; }
_x000D_
<img id="myPic">
<code id="msg"></code>
_x000D_
@SETLOCAL ENABLEDELAYEDEXPANSION
@REM Use WMIC to retrieve date and time
@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
IF NOT "%%~F"=="" (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
set YEAR=!SortDate:~0,4!
set MON=!SortDate:~4,2!
set DAY=!SortDate:~6,2!
@REM Add 1000000 so as to force a prepended 0 if hours less than 10
SET /A SortTime = 1000000 + 10000 * %%B + 100 * %%C + %%E
set HOUR=!SortTime:~1,2!
set MIN=!SortTime:~3,2!
set SEC=!SortTime:~5,2!
)
)
@echo on
@echo DATE=%DATE%, TIME=%TIME%
@echo HOUR=!HOUR! MIN=!MIN! SEC=!SEC!
@echo YR=!YEAR! MON=!MON! DAY=!DAY!
@echo DATECODE= '!YEAR!!MON!!DAY!!HOUR!!MIN!'
Output:
DATE=2015-05-20, TIME= 1:30:38.59
HOUR=01 MIN=30 SEC=38
YR=2015 MON=05 DAY=20
DATECODE= '201505200130'
You can also use OrderedDict:
In [183]: from collections import OrderedDict
In [184]: data = OrderedDict()
In [185]: data['one thing'] = [1,2,3,4]
In [186]: data['second thing'] = [0.1,0.2,1,2]
In [187]: data['other thing'] = ['a','e','i','o']
In [188]: frame = pd.DataFrame(data)
In [189]: frame
Out[189]:
one thing second thing other thing
0 1 0.1 a
1 2 0.2 e
2 3 1.0 i
3 4 2.0 o
.img-responsive
is the right way to make images responsive with bootstrap 3
You can add some height rule for the picture you want to make responsive, because with responsibility, width changes along the height, fix it and there you are.
You can change input box styles as well as text styles inside input
box:
Here you can use any color e.g. white
, #DDD
, rgba(102, 163, 177, 0.45)
.
But transparent
won't work here.
/* Change the white to any color */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active
{
-webkit-box-shadow: 0 0 0 30px white inset !important;
}
Additionally, you can use this to change the text color:
/*Change text in autofill textbox*/
input:-webkit-autofill
{
-webkit-text-fill-color: yellow !important;
}
Advice: Don't use an excessive blur radius in the hundreds or thousands. This has no benefit and might put processor load on weaker mobile devices. (Also true for actual, outside shadows). For a normal input box of 20px height, 30px ‘blur radius’ will perfectly cover it.
I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen
vs FullScreen
. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.
function fullScreenTgl() {
let doc=document,elm=doc.documentElement;
if (elm.requestFullscreen ) { (!doc.fullscreenElement ? elm.requestFullscreen() : doc.exitFullscreen() ) }
else if (elm.mozRequestFullScreen ) { (!doc.mozFullScreen ? elm.mozRequestFullScreen() : doc.mozCancelFullScreen() ) }
else if (elm.msRequestFullscreen ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen() : doc.msExitFullscreen() ) }
else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
else { console.log("Fullscreen support not detected."); }
}
I would also recommend to use Notepad++ with json-view extension. You get the extension here: https://sourceforge.net/projects/nppjsonviewer/ Install and restart Notepad++. Then open json-file in Notepad and go to "extensions -> Json-Viewer - > Format JSON. Then you habe the hierarchical view of json.
You can also use one of the online-viewers (http://jsonviewer.stack.hu/ , https://jsoneditoronline.org/) which look nice, but I wouldn't recommend this if your data are sensitive in terms of privacy.
As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent
is processed SecurityContextHolder
is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder
) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:
AuthenticationSuccessEvent
AuthenticationSuccessHandler
implementation.AuthenticationSuccessHandler
has one important advantage over first way: SecurityContextHolder
will be already populated. So just move your stateService.rowCount()
call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...)
method and the problem will go away.
assertAlert ought to do the trick. I see in the docs that alerts generated in a page's OnLoad event handler cannot be scripted this way (and have experienced it myself, alas, due to the ASP.NET page lifecycle). Could that be what you're running into?
i. Please check the InnerException
property of the TypeInitializationException
ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly
Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/
This will add 10 pixels to the left of the paragraph element
p {
margin-left: 10px;
}
or if you just want some padding within your paragraph element
p {
padding-left: 10px;
}
`
require_once('functions.php');
$errors = FALSE;
$errorMessage = "";
if(mysqli_connect_error()){
$errors = TRUE;
$errorMessage .= "There was a connection error <br/>";
errorDisplay($errorMessage);
die($errors);
} else if($errors != "TRUE"){
$errors .= FALSE;
}
if(isset(mysqli_real_escape_string($_POST['search']))){
$search = mysqli_real_escape_string($_POST['search']);
search(search);
}
?>
<?php
//This is functions.php
function search($searchQuery){
echo "<div class="col-md-10 col-md-offset-1">";
$searchTerm
$query = query("SELECT * FROM `index` WHERE `keywords` LIKE '".$searchTerm."' ");
while($row = mysqli_fetch_array($query)){
$results = <<< DELIMITER
<div class="result col-md-12">
<a href="index.php?search={$row['id']}"> {$row['Title']} </a>
<p class="searchDesc">{$row['description']}</p>
</div>
DELIMITER;
echo $results;
}
echo "</div>";
}
function errorDisplay($msg){
if(!isset($_SESSION['errors'])){
$_SESSION['errors'] = $msg;
showError($msg);
} else if() {
$_SESSION['errors'] .= $msg . "<br>";
showError($msg);
}
}
function showError($msg) {
return $msg;
unset($_SESSION['errors']);
}
?>`
Perhaps That Helps?
I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:
const ROUTER_INSTANCE = new VueRouter({
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
// ... other routes ...
// and finally the default route, when none of the above matches:
{ path: "*", component: PageNotFound }
]
})
In the above PageNotFound
component definition, you can specify the actual redirect, that will take you out of the app entirely:
Vue.component("page-not-found", {
template: "",
created: function() {
// Redirect outside the app using plain old javascript
window.location.href = "/my-new-404-page.html";
}
}
You may do it either on created
hook as shown above, or mounted
hook also.
Please note:
I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli
as it requires server side handling.
Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">
. This will fail for your /404-page.html
unless your server treats it as a special case and serves the static page.
Let me know if it works!
Update for Vue 3 onward:
You'll need to replace the '*'
path property with '/:pathMatch(.*)*'
if you're using Vue 3 as the old catch-all path of '*'
is no longer supported. The route would then look something like this:
{ path: '/:pathMatch(.*)*', component: PathNotFound },
See the docs for more info on this update.
Probably my question should have been more specific. I actually know a base class for the string so solved it by:
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
The Activator.CreateInstance class has various methods to achieve the same thing in different ways. I could have cast it to an object but the above is of the most use to my situation.
Jefferson is right, you have to do it backwards.
Here's the c# equivalent:
for (var i == list.Items.Count - 1; i >= 0; i--)
{
list.Items.RemoveAt(i);
}
Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:
TableA:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataA11 |
| 1 | DataA12 |
| 1 | DataA13 |
| 2 | DataA21 |
| 3 | DataA31 |
+----+---------+
TableB:
+----+---------+
| Id | Data |
+----+---------+
| 1 | DataB11 |
| 2 | DataB21 |
| 2 | DataB22 |
| 2 | DataB23 |
| 4 | DataB41 |
+----+---------+
Inner Join on column Id
will return columns from both the tables and only the matching records:
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
'----'---------'----'---------'
Left Join (or Left Outer join) on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table):
.----.---------.----.---------.
| Id | Data | Id | Data |
:----+---------+----+---------:
| 1 | DataA11 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA12 | 1 | DataB11 |
:----+---------+----+---------:
| 1 | DataA13 | 1 | DataB11 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB21 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB22 |
:----+---------+----+---------:
| 2 | DataA21 | 2 | DataB23 |
:----+---------+----+---------:
| 3 | DataA31 | | |
'----'---------'----'---------'
Right Join (or Right Outer join) on column Id
will return columns from both the tables and matching records with records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
+----+---------+----+---------¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Full Outer Join on column Id
will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):
+-----------------------------+
¦ Id ¦ Data ¦ Id ¦ Data ¦
¦----+---------+----+---------¦
¦ - ¦ ¦ ¦ ¦
¦ 1 ¦ DataA11 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA12 ¦ 1 ¦ DataB11 ¦
¦ 1 ¦ DataA13 ¦ 1 ¦ DataB11 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB21 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB22 ¦
¦ 2 ¦ DataA21 ¦ 2 ¦ DataB23 ¦
¦ 3 ¦ DataA31 ¦ ¦ ¦
¦ ¦ ¦ 4 ¦ DataB41 ¦
+-----------------------------+
Left Semi Join on column Id
will return columns only from left table and matching records only from left table:
+--------------+
¦ Id ¦ Data ¦
+----+---------¦
¦ 1 ¦ DataA11 ¦
¦ 1 ¦ DataA12 ¦
¦ 1 ¦ DataA13 ¦
¦ 2 ¦ DataA21 ¦
+--------------+
Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.
If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.
For example, in a query you link two tables in a select statement with a join:
SELECT a, b from table1 LEFT JOIN table2 USING (common_field);
By code:
btn_edit.IsEnabled = true;
By XAML:
<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />
I am a VIMer. I can do some rare Hex edits with:
:%!xxd
to switch into hex mode
:%!xxd -r
to exit from hex mode
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
Note: I had this problem while Generating Database Sql from Model. It had created all the tables fine but wouldn't export the changes. What you need to notice is that this error is generated when you try to export the sql using the DDL Generation Template as SSDLtoSQL10. It is expecting MySQL connection here so make sure you select from the drop down DDL Generation Template SSDLtoMySQL on the Model properties. Spent a whole day on this !
If you select a cell in an already selected range, it will not work. But, Selecting a range outside the original selection will clear the original selection.
'* The original selection *' ActiveSheet.range("A1:K10").Select
'* New Selections *' Activesheet.Range("L1").Select
'* Then *' Activesheet.Range("A1").Select
You need to iterate over your ResultSet calling next()
.
This is an example from java2s.com:
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
Column 3 is the TABLE_NAME
(see documentation of DatabaseMetaData::getTables
).
Try this:
with open(file_dmp_path, 'rb') as file:
fsize = bsize = os.path.getsize(file_dmp_path)
word_len = len(SEARCH_WORD)
while True:
p = file.read(bsize).find(SEARCH_WORD)
if p > -1:
pos_dec = file.tell() - (bsize - p)
file.seek(pos_dec + word_len)
bsize = fsize - file.tell()
if file.tell() < fsize:
seek = file.tell() - word_len + 1
file.seek(seek)
else:
break
I had the same issue.
Look at your git ignore and check if .env is not ignored.
It was my problem and resolved to my case.
SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
$("#tabs").tabs({
load: function(event, ui){
var anchor = ui.tab.find(".ui-tabs-anchor");
var url = anchor.attr('href');
}
});
In the url variable you will get the current tab's HREF / URL
Since Python 3.3, you can use the class ExitStack
from the contextlib
module to safely
open an arbitrary number of files.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
If you are interested in the details, here is a generic example in order to explain how ExitStack
operates:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(len(stack._exit_callbacks)) # number of callbacks called on exit
nums = [stack.enter_context(x) for x in xs]
print(len(stack._exit_callbacks))
print(len(stack._exit_callbacks))
print(nums)
Output:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
If you are on a detached head (i.e. you've checked out a release) and have an output from git status such as
HEAD detached at v1.7.3.1
And you want the release version, we use the following command...
git status --branch | head -n1 | tr -d 'A-Za-z: '
This returns 1.7.3.1, which we replace in our parameters.yml (Symfony) with
# RevNum=`svn status -u | grep revision | tr -d 'A-Za-z: '` # the old SVN version
RevNum=`git status --branch | head -n1 | tr -d 'A-Za-z: '` # Git (obvs)
sed -i "/^ app_version:/c\ app_version:$RevNum" app/config/parameters.yml
Hope this helps :) Obviously if you have non-numerics in your branch name, you'll need to alter the arguments to the tr command.
You can also use a text editor:
If it has to be "nested", this would be one way, to get your job done:
SELECT o.name AS country, o.headofstate
FROM country o
WHERE o.headofstate like 'A%'
AND (
SELECT i.population
FROM city i
WHERE i.id = o.capital
) > 100000
A JOIN
would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?
I don't see how. The PID doesn't make it onto the wire (generally speaking), plus Wireshark allows you to look at what's on the wire - potentially all machines which are communicating over the wire. Process IDs aren't unique across different machines, anyway.
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error. and then enjoy it :)
Check your antivirus and firewall settings.
From one day to the other, git did not work anymore. With what is described above, I found that Kaspersky puts a self-signed Anti-virus personal root certificate in the middle. I did not manage to let Git accept that certificate following the instructions above. I gave up on that. What works for me is to disable the feature to Scan encrypted connections.
After this, git works again with sslVerify enabled.
Note. This is still not satisfying for me, because I would like to have that feature of my Anti-Virus active. In the advanced settings, Kaspersky shows a list of websites that will not work with that feature. Github is not listed as one of them. I will check it at the Kaspersky forum. There seem to be some topics, e.g. https://forum.kaspersky.com/index.php?/topic/395220-kis-interfering-with-git/&tab=comments#comment-2801211
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application
, available for the life of the entire applicationsession
, available for the life of the sessionrequest
, only available for the life of the requestpage
(JSP only), available for the current JSP page only this worked nicely for me:
from csv import DictReader
f = requests.get('https://somedomain.com/file').content.decode('utf-8')
reader = DictReader(f.split('\n'))
csv_dict_list = list(reader)
The below options works for me:
-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.rmi.port=9010
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname={host name}
and remember to open 9010 port in the server
sudo ufw allow 9010/udp
sudo ufw allow 9010/tcp
sudo ufw reload
This can be done with reduce using method references reduce(Integer::sum)
:
Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
.stream()
.reduce(Integer::sum)
.get();
Or without Optional
:
Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
.stream()
.reduce(0, Integer::sum);
The overall dimensions of a range are in its Width
and Height
properties.
Dim r As Range
Set r = ActiveSheet.Range("A4:H12")
Debug.Print r.Width
Debug.Print r.Height
Call Path.GetFullPath
; it will throw exceptions if the path is invalid.
To disallow relative paths (such as Word
), call Path.IsPathRooted
.
Below the code will print 0 if it is Palindrome else it will print -1
Optimized Code
word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output: 0
word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output: -1
when searching the string the value that is returned is the value of the location that the string starts at.
So when you do word.find(word[::-1])
it finds nepalapen
at location 0
and [::-1]
reverses nepalapen
and it still is nepalapen
at location 0
so 0
is returned.
Now when we search for nepalapend
and then reverse nepalapend
to dnepalapen
it renders a FALSE
statement nepalapend
was reversed to dnepalapen
causing the search to fail to find nepalapend
resulting in a value of -1
which indicates string not found.
Another method print true if palindrome else print false
word = "nepalapen"
print(word[::-1]==word[::1])
output: TRUE
seaborn has a wrapper function scatterplot
that does it more efficiently.
sns.scatterplot(data = df, x = 'one', y = 'two', data = 'key1'])
I looked at most the solutions posted, but came across a different one that I prefer. It's simple, doesn't use threads, and works for what I want it to.
http://weblogs.asp.net/kennykerr/archive/2004/11/26/where-is-form-s-loaded-event.aspx
I added to the solution in the article and moved the code into a base class that all my forms inherit from. Now I just call one function: ShowWaitForm() during the frm_load() event of any form that needs a wait dialogue box while the form is loading. Here's the code:
public class MyFormBase : System.Windows.Forms.Form
{
private MyWaitForm _waitForm;
protected void ShowWaitForm(string message)
{
// don't display more than one wait form at a time
if (_waitForm != null && !_waitForm.IsDisposed)
{
return;
}
_waitForm = new MyWaitForm();
_waitForm.SetMessage(message); // "Loading data. Please wait..."
_waitForm.TopMost = true;
_waitForm.StartPosition = FormStartPosition.CenterScreen;
_waitForm.Show();
_waitForm.Refresh();
// force the wait window to display for at least 700ms so it doesn't just flash on the screen
System.Threading.Thread.Sleep(700);
Application.Idle += OnLoaded;
}
private void OnLoaded(object sender, EventArgs e)
{
Application.Idle -= OnLoaded;
_waitForm.Close();
}
}
MyWaitForm is the name of a form you create to look like a wait dialogue. I added a SetMessage() function to customize the text on the wait form.
Building on @Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:
myApp.run(function($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function() {
$templateCache.removeAll();
});
});
A performance comparison:
import itertools
import timeit
big_list = [[0]*1000 for i in range(1000)]
timeit.repeat(lambda: list(itertools.chain.from_iterable(big_list)), number=100)
timeit.repeat(lambda: list(itertools.chain(*big_list)), number=100)
timeit.repeat(lambda: (lambda b: map(b.extend, big_list))([]), number=100)
timeit.repeat(lambda: [el for list_ in big_list for el in list_], number=100)
[100*x for x in timeit.repeat(lambda: sum(big_list, []), number=1)]
Producing:
>>> import itertools
>>> import timeit
>>> big_list = [[0]*1000 for i in range(1000)]
>>> timeit.repeat(lambda: list(itertools.chain.from_iterable(big_list)), number=100)
[3.016212113769325, 3.0148865239060227, 3.0126415732791028]
>>> timeit.repeat(lambda: list(itertools.chain(*big_list)), number=100)
[3.019953987082083, 3.528754223385439, 3.02181439266457]
>>> timeit.repeat(lambda: (lambda b: map(b.extend, big_list))([]), number=100)
[1.812084445152557, 1.7702404451095965, 1.7722977998725362]
>>> timeit.repeat(lambda: [el for list_ in big_list for el in list_], number=100)
[5.409658160700605, 5.477502077679354, 5.444318360412744]
>>> [100*x for x in timeit.repeat(lambda: sum(big_list, []), number=1)]
[399.27587954973444, 400.9240571138051, 403.7521153804846]
This is with Python 2.7.1 on Windows XP 32-bit, but @temoto in the comments above got from_iterable
to be faster than map+extend
, so it's quite platform and input dependent.
Stay away from sum(big_list, [])
I haven't tested your code, just tried to help you understand how it operates in comment;
WITH
cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
AS
(
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
SELECT EmployeeID, FirstName, LastName, ManagerID, 1
FROM Employees
WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
r.EmpLevel + 1
FROM Employees e
INNER JOIN cteReports r
ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
)
SELECT
FirstName + ' ' + LastName AS FullName,
EmpLevel,
(SELECT FirstName + ' ' + LastName FROM Employees
WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID
The simplest example of a recursive CTE
I can think of to illustrate its operation is;
;WITH Numbers AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM Numbers
WHERE n+1 <= 10
)
SELECT n
FROM Numbers
Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.
A1:
In this case, N
is not a variable. N
is an alias. It is the equivalent of SELECT 1 AS N
. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE
in T-SQL
. I've included the analog of a simple CTE
in Excel
to try and illustrate in a more familiar way what is happening.
-- Outside
;WITH CTE (MyColName) AS
(
SELECT 1
)
-- Inside
;WITH CTE AS
(
SELECT 1 AS MyColName
-- Or
SELECT MyColName = 1
-- Etc...
)
Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager
A2:
Does this code answer your question?
--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS
(
SELECT 1, 'Keith', NULL UNION ALL
SELECT 2, 'Josh', 1 UNION ALL
SELECT 3, 'Robin', 1 UNION ALL
SELECT 4, 'Raja', 2 UNION ALL
SELECT 5, 'Tridip', NULL UNION ALL
SELECT 6, 'Arijit', 5 UNION ALL
SELECT 7, 'Amit', 5 UNION ALL
SELECT 8, 'Dev', 6
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
-- Anchor
SELECT ID
,Name
,MgrID
,nLevel = 1
,Family = ROW_NUMBER() OVER (ORDER BY Name)
FROM Employee
WHERE MgrID IS NULL
UNION ALL
-- Recursive query
SELECT E.ID
,E.Name
,E.MgrID
,H.nLevel+1
,Family
FROM Employee E
JOIN Hierarchy H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel
SELECT ID,space(nLevel+
(CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
)+Name
FROM Hierarchy
ORDER BY Family, nLevel
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
No. But there are other options out there like Overlib, and jQuery that allow you this freedom.
Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your <head>).
Just try this code:
start "" "C:\Users\DiPesh\Desktop\vbscript\welcome.vbs"
and save as .bat, it works for me
You shouldn't care. You should use int
most of the time. It will help the porting of your program to a wider architecture in the future (currently int
is an alias to System.Int32
but that could change). Only when the bit width of the variable matters (for instance: to control the layout in memory of a struct
) you should use int32
and others (with the associated "using System;
").
Change
application:climate-change
to
application: climate-change
The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)
To avoid problems of side effects after changing env
, especially using multiple nodes, it is better to set a temporary context.
One safe way to alter the environment is:
withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
sh '$MYTOOL_HOME/bin/start'
}
This approach does not poison the env after the command execution.
Use the vectorised str
method replace
:
In [30]:
df['range'] = df['range'].str.replace(',','-')
df
Out[30]:
range
0 (2-30)
1 (50-290)
EDIT
So if we look at what you tried and why it didn't work:
df['range'].replace(',','-',inplace=True)
from the docs we see this desc:
str or regex: str: string exactly matching to_replace will be replaced with value
So because the str values do not match, no replacement occurs, compare with the following:
In [43]:
df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)
df['range']
Out[43]:
0 (2,30)
1 -
Name: range, dtype: object
here we get an exact match on the second row and the replacement occurs.
In similar case I used: white-space: nowrap;
Based on previous answers this has worked for me with Python 3.7
from urllib.request import Request, urlopen
req = Request('Url_Link', headers={'User-Agent': 'XYZ/3.0'})
webpage = urlopen(req, timeout=10).read()
print(webpage)