You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
I think best way is check if request is of type "OPTIONS" return 200 from middle ware. It worked for me.
express.use('*',(req,res,next) =>{
if (req.method == "OPTIONS") {
res.status(200);
res.send();
}else{
next();
}
});
They probably compile down to nearly the same machine code, so it is a matter of taste.
Personally, I would chose the one that is the clearest (i.e. very clear that it is supposed to be an infinite loop).
I would lean towards while(true){}
.
Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout
like below:
[Violation] 'setTimeout' handler took 43129ms
That number (43129ms) depends on how long you stop in your async function
If you want a one-liner solution (ignoring imports) that only requires O(max(n, m))
work for inputs of length n
and m
, not O(n * m)
work, you can do so with the itertools
module:
from itertools import filterfalse
main_list = list(filterfalse(set(list_1).__contains__, list_2))
This takes advantage of the functional functions taking a callback function on construction, allowing it to create the callback once and reuse it for every element without needing to store it somewhere (because filterfalse
stores it internally); list comprehensions and generator expressions can do this, but it's ugly.†
That gets the same results in a single line as:
main_list = [x for x in list_2 if x not in list_1]
with the speed of:
set_1 = set(list_1)
main_list = [x for x in list_2 if x not in set_1]
Of course, if the comparisons are intended to be positional, so:
list_1 = [1, 2, 3]
list_2 = [2, 3, 4]
should produce:
main_list = [2, 3, 4]
(because no value in list_2
has a match at the same index in list_1
), you should definitely go with Patrick's answer, which involves no temporary list
s or set
s (even with set
s being roughly O(1)
, they have a higher "constant" factor per check than simple equality checks) and involves O(min(n, m))
work, less than any other answer, and if your problem is position sensitive, is the only correct solution when matching elements appear at mismatched offsets.
†: The way to do the same thing with a list comprehension as a one-liner would be to abuse nested looping to create and cache value(s) in the "outermost" loop, e.g.:
main_list = [x for set_1 in (set(list_1),) for x in list_2 if x not in set_1]
which also gives a minor performance benefit on Python 3 (because now set_1
is locally scoped in the comprehension code, rather than looked up from nested scope for each check; on Python 2 that doesn't matter, because Python 2 doesn't use closures for list comprehensions; they operate in the same scope they're used in).
This error comes up when you try to clone a repository in a folder which still contains .git
folder (Hidden folder).
If the earlier answers doesn't work then you can proceed with my answer. Hope it will solve your issue.
Open terminal & change the directory to the destination folder (where you want to clone).
Now type: ls -a
You may see a folder named .git
.
You have to remove that folder by the following command: rm -rf .git
Now you are ready to clone your project.
Android Device monitor is no longer available in android studio.
If you are using android studio 3.0 and above.
mnt>sdcard
is the location for SD card on the emulator. Note: You can upload folder as well not just individual files.
Maybe you should try using Starwind V2V Converter, you can get it from here - http://www.starwindsoftware.com/converter. It also supports IMG disk format and performs sector-by sector conversion between IMG, VMDK or VHD into and from any of them without making any changes to source image. This tool is free :)
You can also get a query string value as:
$uri = $_SERVER["REQUEST_URI"]; //it will print full url
$uriArray = explode('/', $uri); //convert string into array with explode
$id = $uriArray[1]; //Print first array value
Because &
has a lesser priority than ==
.
Your code is equivalent to a[0] & (1 == 0)
, and unless a[0]
is a boolean this won't compile...
You need to:
(a[0] & 1) == 0
etc etc.
(yes, Java does hava a boolean &
operator -- a non shortcut logical and)
You should use Array.prototype.reduce to do this. I did do a little JS perf test to verify that this is more performant than doing a .filter
+ .map
.
$scope.appIds = $scope.applicationsHere.reduce(function(ids, obj){
if(obj.selected === true){
ids.push(obj.id);
}
return ids;
}, []);
Just for the sake of clarity, here's the sample .reduce
I used in the JSPerf test:
var things = [_x000D_
{id: 1, selected: true},_x000D_
{id: 2, selected: true},_x000D_
{id: 3, selected: true},_x000D_
{id: 4, selected: true},_x000D_
{id: 5, selected: false},_x000D_
{id: 6, selected: true},_x000D_
{id: 7, selected: false},_x000D_
{id: 8, selected: true},_x000D_
{id: 9, selected: false},_x000D_
{id: 10, selected: true},_x000D_
];_x000D_
_x000D_
_x000D_
var ids = things.reduce((ids, thing) => {_x000D_
if (thing.selected) {_x000D_
ids.push(thing.id);_x000D_
}_x000D_
return ids;_x000D_
}, []);_x000D_
_x000D_
console.log(ids)
_x000D_
EDIT 1
Note, As of 2/2018 Reduce + Push is fastest in Chrome and Edge, but slower than Filter + Map in Firefox
I did follow the answer from Bugagotti, And it does not work in my windows (Win7 64 bit, py27 and have mysql connector 6.1 installed) for mysql-python-1.2.5, so I made some even dirty changes inside mysql-python-1.2.5:
First, the site.cfg:
connector = C:\Program Files\MySQL\MySQL Connector C 6.1
Second, the _mysql.c :
#if defined(MS_WINDOWS)
#include <config-win.h>
#else
#include "my_config.h"
#endif
To:
#if 0 /*defined(MS_WINDOWS)*/
#include <config-win.h>
#else
#include "my_config.h"
#endif
And with these changes ,the config_win.h issue will gone, but there is still a link issue:
LINK : fatal error LNK1181: cannot open input file 'mysqlclient.lib'
For this, I changed the setup_windows.py:
library_dirs = [ os.path.join(connector, r'lib\vs9') ] ## the original value was r'lib\opt'
Then it worked finally.
The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:
var newDate = oldDate.Date + new TimeSpan(11, 30, 55);
I got this working on Android Studio 2.1. I have a module called "Native_Ads" which is shared across multiple projects.
First, I created a directory in my Native_ads module with the name 'aars' and then put the aar file in there.
Directory structure:
libs/
aars/ <-- newly created
src/
build.gradle
etc
Top level Gradle file:
allprojects {
repositories {
jcenter()
// For module with aar file in it
flatDir {
dirs project(':Native_Ads').file('aars')
}
}
}
App module's build.gradle file: - no changes
Settings.gradle file (to include the module):
include ':app'
include 'Native_Ads'
project(':Native_Ads').projectDir = new File(rootProject.projectDir, '../path/to/Native_Ads')
Gradle file for the Native_Ads module:
repositories {
jcenter()
flatDir {
dirs 'aars'
}
}
dependencies {
compile(name:'aar_file_name_without_aar_extension', ext:'aar')
}
That's it. Clean and build.
Trying to uninstall Python with
brew uninstall python
will not remove the natively installed Python but rather the version installed with brew
.
I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:
sudo vi /etc/apt/sources.list
and added the following lines:
deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main
If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:
sudo apt-get update
sudo apt-get install build-essential
Hopefully this will help someone who had the same problem that I did.
As described in other answers, Git is unable to represent empty directories in its staging area. (See the Git FAQ.) However, if, for your purposes, a directory is empty enough if it contains a .gitignore
file only, then you can create .gitignore
files in empty directories only via:
find . -type d -empty -exec touch {}/.gitignore \;
Based on solution You've already found How to apply CSS to iframe?:
var cssLink = document.createElement("link")
cssLink.href = "file://path/to/style.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['iframe'].document.body.appendChild(cssLink);
or more jqueryish (from Append a stylesheet to an iframe with jQuery):
var $head = $("iframe").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));
as for security issues: Disabling same-origin policy in Safari
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
r = requests.get('https://api.github.com', auth=('user', 'pass'))
r
is a response. It has a request attribute which has the information you need.
r.request.allow_redirects r.request.headers r.request.register_hook
r.request.auth r.request.hooks r.request.response
r.request.cert r.request.method r.request.send
r.request.config r.request.params r.request.sent
r.request.cookies r.request.path_url r.request.session
r.request.data r.request.prefetch r.request.timeout
r.request.deregister_hook r.request.proxies r.request.url
r.request.files r.request.redirect r.request.verify
r.request.headers
gives the headers:
{'Accept': '*/*',
'Accept-Encoding': 'identity, deflate, compress, gzip',
'Authorization': u'Basic dXNlcjpwYXNz',
'User-Agent': 'python-requests/0.12.1'}
Then r.request.data
has the body as a mapping. You can convert this with urllib.urlencode
if they prefer:
import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)
depending on the type of the response the .data
-attribute may be missing and a .body
-attribute be there instead.
Try forcing updates using the mvn cpu
option:
usage: mvn [options] [<goal(s)>] [<phase(s)>]
Options:
-cpu,--check-plugin-updates Force upToDate check for any
relevant registered plugins
Use the continue
keyword. Read here.
The continue statement skips the current iteration of a for, while , or do-while loop.
You can get the spark version by using the following command:
spark-submit --version
spark-shell --version
spark-sql --version
You can visit the below site to know the spark-version used in CDH 5.7.0
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
I suggest you also add separate checkboxes or a textfield for the special flags. That way it is clear that the user does not need to add any //
's. In the case of a replace, provide two textfields. This will make your life a lot easier.
Why? Because otherwise some users will add //
's while other will not. And some will make a syntax error. Then, after you stripped the //
's, you may end up with a syntactically valid regex that is nothing like what the user intended, leading to strange behaviour (from the user's perspective).
So it turns out that if I add the Handler Mappings on the Website and Application level, everything works beautifully. I was only adding them on the server level, thus IIS did not know to map the asp pages to the IsapiModule.
So to resolve this issue, go to the website you want to add your application to, then double click on Handler Mappings. Click "Add Script Map" and enter in the following information:
RequestPath: *.asp
Executable: C:\Windows\System32\inetsrv\asp.dll
Name: Classic ASP (this can be anything you want it to be
The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.
Also, I didn't understand when the accepted answer said "it defaults to node server.js
". I think the documentation clarifies the default behavior:
npm-start
Start a package
Synopsis
npm start [-- <args>]
Description
This runs an arbitrary command specified in the package's "
start
" property of its "scripts
" object. If no "start
" property is specified on the "scripts
" object, it will runnode server.js
.
In summary, running npm start
could do one of two things:
npm start {command_name}
: Run an arbitrary command (i.e. if such command is specified in the start
property of package.json's scripts
object)npm start
: Else if no start
property exists (or no command_name
is passed): Run node server.js
, (which may not be appropriate, for example the OP doesn't have server.js
; the OP runs node
app.js
)package.json
in the directory where you run npm start
, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
What worked for me in Android Studio 3.2.1
Was:
RUN -> Attach debugger to Android Process --> com.my app
Assuming this is what the HTML looks like
<div class="form-group required">
<label class="col-md-2 control-label">E-mail</label>
<div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>
To display an asterisk on the right of the label:
.form-group.required .control-label:after {
color: #d00;
content: "*";
position: absolute;
margin-left: 8px;
top:7px;
}
Or to the left of the label:
.form-group.required .control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -15px;
}
To make a nice big red asterisks you can add these lines:
font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;
Or if you are using Font Awesome add these lines (and change the content line):
font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";
In case of big projects, many files to change and also if the previous project version of PHP was 5.6 and the new one is 7.1, you can create a new file sql.php and include it in the header or somewhere you use it all the time and needs sql connection. For example:
//local
$sql_host = "localhost";
$sql_username = "root";
$sql_password = "";
$sql_database = "db";
$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
// /* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
// printf("Current character set: %s\n", $mysqli->character_set_name());
}
if (!function_exists('mysql_real_escape_string')) {
function mysql_real_escape_string($string){
global $mysqli;
if($string){
// $mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );
$newString = $mysqli->real_escape_string($string);
return $newString;
}
}
}
// $mysqli->close();
$conn = null;
if (!function_exists('mysql_query')) {
function mysql_query($query) {
global $mysqli;
// echo "DAAAAA";
if($query) {
$result = $mysqli->query($query);
return $result;
}
}
}
else {
$conn=mysql_connect($sql_host,$sql_username, $sql_password);
mysql_set_charset("utf8", $conn);
mysql_select_db($sql_database);
}
if (!function_exists('mysql_fetch_array')) {
function mysql_fetch_array($result){
if($result){
$row = $result->fetch_assoc();
return $row;
}
}
}
if (!function_exists('mysql_num_rows')) {
function mysql_num_rows($result){
if($result){
$row_cnt = $result->num_rows;;
return $row_cnt;
}
}
}
if (!function_exists('mysql_free_result')) {
function mysql_free_result($result){
if($result){
global $mysqli;
$result->free();
}
}
}
if (!function_exists('mysql_data_seek')) {
function mysql_data_seek($result, $offset){
if($result){
global $mysqli;
return $result->data_seek($offset);
}
}
}
if (!function_exists('mysql_close')) {
function mysql_close(){
global $mysqli;
return $mysqli->close();
}
}
if (!function_exists('mysql_insert_id')) {
function mysql_insert_id(){
global $mysqli;
$lastInsertId = $mysqli->insert_id;
return $lastInsertId;
}
}
if (!function_exists('mysql_error')) {
function mysql_error(){
global $mysqli;
$error = $mysqli->error;
return $error;
}
}
the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.
Either put it on one line or append on each line :o)
Sqlyog must be trimming white spaces on each line which explains why its working.
Example:
$qr2="INSERT INTO wp_bp_activity
(
user_id,
(this stuff)component,
(is) `type`,
(a) `action`,
(problem) content,
primary_link,
item_id,....
If you also get code signing fails with the error "resource fork, Finder information, or similar detritus not allowed."
Run script below in console to fix:
$ xattr -cr <path_to_app_bundle>
Apple documentation: https://developer.apple.com/library/archive/qa/qa1940/_index.html
json.dumps()
is used to decode JSON dataimport json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
json.loads()
is used to convert JSON data into Python data.import json
# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)
print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])
print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])
output:
arrayJson to list_data :
[1, 1.5, ['normal string', 1, 1.5]]
Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]
objectJson to dictionary :
{'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
| JSON | Python |
|:-------------:|:------:|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
Step 1: Go to directory where the classes are kept using command prompt (or Linux shell prompt)
Like for Project.
C:/workspace/MyProj/bin/classess/com/test/*.class
Go directory bin using command:
cd C:/workspace/MyProj/bin
Step 2: Use below command to generate jar file.
jar cvf helloworld.jar com\test\hello\Hello.class com\test\orld\HelloWorld.class
Using the above command the classes will be placed in a jar in a directory structure.
You need to return a view which has a friendly error message to the user
catch (Exception ex)
{
// to do :log error
return View("Error");
}
You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.
If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions
[HttpPost]
public ActionResult Create(CustomerVM model)
{
try
{
//save customer
return Json(new { status="success",message="customer created"});
}
catch(Exception ex)
{
//to do: log error
return Json(new { status="error",message="error creating customer"});
}
}
If you want to show the error in the form user submitted, You may use ModelState.AddModelError
method along with the Html helper methods like Html.ValidationSummary
etc to show the error to the user in the form he submitted.
Meanwhile, another reason : accidentally deleted the .config file caused the same error message appears:
"Service on local computer started and then stopped. some services stop automatically..."
Another mistake that can have the same effect can be the wrong theme in the preview. For some reason I had selected some other theme here. After choosing my AppTheme it worked fine again:
You can use the UpdateProgress control:
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
I'm late to the party, but this solution worked for me quite well. Based on this library, you can use a function lik this - setting the image, quality, max-width, and output format (jepg,png):
function compress(source_img_obj, quality, maxWidth, output_format){
var mime_type = "image/jpeg";
if(typeof output_format !== "undefined" && output_format=="png"){
mime_type = "image/png";
}
maxWidth = maxWidth || 1000;
var natW = source_img_obj.naturalWidth;
var natH = source_img_obj.naturalHeight;
var ratio = natH / natW;
if (natW > maxWidth) {
natW = maxWidth;
natH = ratio * maxWidth;
}
var cvs = document.createElement('canvas');
cvs.width = natW;
cvs.height = natH;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
var newImageData = cvs.toDataURL(mime_type, quality/100);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
return result_image_obj;
}
If you're using membership you can do: Membership.GetUser()
Your code is returning the Windows account which is assigned with ASP.NET.
Additional Info Edit: You will want to include System.Web.Security
using System.Web.Security
Git log but you need to prefix the path with --
Eg:
dan-mac:test dani$ git log file1.txt
fatal: ambiguous argument 'file1.txt': unknown revision or path not in the working tree.
dan-mac:test dani$ git log -- file1.txt
commit 0f7c4e1c36e0b39225d10b26f3dea40ad128b976
Author: Daniel Palacio <[email protected]>
Date: Tue Jul 26 23:32:20 2011 -0500
foo
I assume those XAML namespace declarations are in the parent tag of your control? You can't put comments inside of another tag. Other than that, the syntax you're using is correct.
<UserControl xmlns="...">
<!-- Here's a valid comment. Notice it's outside the <UserControl> tag's braces -->
[..snip..]
</UserControl>
JS:
<div onclick="location.href='url'">content</div>
jQuery:
$("div").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
Make sure to use cursor:pointer
for these DIVs
The value
attribute is used to determine the rendered label of a submit input.
<input type="submit" class="like" value="Like" />
Note that if the control is successful (this one won't be as it has no name
) this will also be the submitted value for it.
To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img>
here).
<button type="submit" class="like" name="foo" value="bar">Like</button>
Note that support for <button>
is dodgy in older versions of Internet Explorer.
You can use the following syntax:
#include <map>
std::map<char, char> my_map = {
{ 'A', '1' },
{ 'B', '2' },
{ 'C', '3' }
};
See http://angular-ui.github.io/bootstrap/#/collapse
function CollapseDemoCtrl($scope) {
$scope.isCollapsed = false;
}
<div ng-controller="CollapseDemoCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<hr>
<div collapse="isCollapsed">
<div class="well well-large">Some content</div>
</div>
</div>
First off, a PetStore
is not a farm.
Let's get past this though. You actually don't need access to the private members, you have everything you need in the public interface:
Animal_* getAnimal_(int i);
void addAnimal_(Animal_* newAnimal);
These are the methods you're given access to and these are the ones you should use.
I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ??
Simple, you call addAnimal
. It's public
and it also increments sizeF
.
Also, note that
PetStore()
{
idF=0;
};
is equivalent to
PetStore() : Farm()
{
idF=0;
};
i.e. the base constructor is called, base members are initialized.
For external link simply use an achor in place of Link:
<a rel="noopener noreferrer" href="http://url.com" target="_blank">Link Here</a>
Worth noting (from this issue) that if you're attaching events to document
, e.stopPropagation()
isn't going to help. As a workaround, you can use window.addEventListener()
instead of document.addEventListener
, then event.stopPropagation()
will stop event from propagating to the window.
I don't think this is possible. As far as I know, the only time a browser doesn't scroll to a changed document.location.hash
is if the hash doesn't exist within the page.
This article isn't directly related to your question, but it discusses typical browser behavior of changing document.location.hash
Create your own conversion function that applies the needed math, and invoke those instead. http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees
This is how it is done in jquery
$("#artifact_form").submit(function(){
return ["jpg", "jpeg", "bmp", "gif", "png"].includes(/[^.]+$/.exec($("#artifact_file_name").val())[0])
});
Apple simply recommends declaring an isX
getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:
@property (nonatomic, assign) BOOL working;
[self setWorking:YES]; // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;
Or
@property (nonatomic, assign, getter=isWorking) BOOL working;
[self setWorking:YES]; // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above
Why Quicksort is good?
Is Quicksort always better than Mergesort?
Not really.
Note: In java, Arrays.sort() function uses Quicksort for primitive data types and Mergesort for object data types. Because objects consume memory overhead, so added a little overhead for Mergesort may not be any issue for performance point of view.
Reference: Watch the QuickSort videos of Week 3, Princeton Algorithms Course at Coursera
Depending on which version of Vim I use, I'm able to use the +
register to access the clipboard.
"Mac OS X clipboard sharing" may have some ideas that work for you as well.
Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me
body {
overflow-y: hidden ! important;
overflow-x: hidden ! important;
background-color: #f8f8f8;
background-image: url('index.png');
/*background-size: cover;*/
background-size: contain;
background-repeat: no-repeat;
background-position: right;
}
Open Terminal and run:
cd ~
mv .itmstransporter/ .old_itmstransporter/
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"
?
I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.
I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.
Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.
Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.
I often need to execute an action on each pair in two collections. The Zip method is not useful in this case.
This extension method ForPair can be used:
public static void ForPair<TFirst, TSecond>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second,
Action<TFirst, TSecond> action)
{
using (var enumFirst = first.GetEnumerator())
using (var enumSecond = second.GetEnumerator())
{
while (enumFirst.MoveNext() && enumSecond.MoveNext())
{
action(enumFirst.Current, enumSecond.Current);
}
}
}
So for example, you could write:
var people = new List<Person> { person1, person2 };
var wages = new List<decimal> { 10, 20 };
people.ForPair(wages, (p, w) => p.Wage = w);
Note however that this method cannot be used to modify the collection itself. This for example will not work:
List<String> listA = new List<string> { "string", "string" };
List<String> listB = new List<string> { "string", "string" };
listA.ForPair(listA, (c1, c2) => c1 = c2); // Nothing will happen!
So in this case, the example in your own question is probably the best way.
There are several reasons this can happen. Some of these I found here, others I discovered on my own.
Id
, you need to add the [Key]
attribute to it.public
uint
, ulong
etc. are not allowed.modern shells already support arrays( and even associative arrays). So please do use them, and use less of eval.
var1="this is the real value"
array=("$var1")
# or array[0]="$var1"
then when you want to call it , echo ${array[0]}
I ran the below where <user>:<group>
matched the other <user>:<group>
for other files in the /usr/local/lib/python3.7/site-packages/
directory:
sudo chown -R <user>:<group> /usr/local/lib/python3.7/site-packages/pip*
brew postinstall python3
MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.
E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.
A general solution:
import random
def weighted_choice(choices, weights):
total = sum(weights)
treshold = random.uniform(0, total)
for k, weight in enumerate(weights):
total -= weight
if total < treshold:
return choices[k]
When using a wildcard, it had to be present on both sides of the refspec, so +refs/heads/*:refs/heads/master
will not work. But you can use +HEAD:refs/heads/master
:
git config remote.heroku.push +HEAD:refs/heads/master
Also, you can do this directly with git push:
git push heroku +HEAD:master
git push -f heroku HEAD:master
To translate your *nix style command script to windows/command batch style it would go like this:
SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"
mkdir on windows doens't have a -p parameter : from the MKDIR /? help:
MKDIR creates any intermediate directories in the path, if needed.
which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide
See this TechNet article: Runas command documentation
From a command prompt:
C:\> runas /user:<localmachinename>\administrator cmd
Or, if you're connected to a domain:
C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd
If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.
input.rightAligned {_x000D_
direction:ltr;_x000D_
overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
direction:rtl;_x000D_
text-align: left;_x000D_
unicode-bidi: plaintext;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
The not selector is currently well supported : Browser support
On Vista, this worked:
DOS: del c:\user\dad\.android\debug.keystore
ECLIPSE: In Project, Clean the project. Close Eclipse. Re-open Eclipse.
ECLIPSE: Start the Emulator. Remove the Application from the emulator.
You are good to go.
I was pretty worried when I say that error, but I fixed it from reading here and playing around for 10 minutes.
Create your own customized class AbcViewCell
subclass from UITableViewCell
(Make sure your class file name and nib file name are the same)
Create this extension class method.
extension UITableViewCell {
class func fromNib<T : UITableViewCell>() -> T {
return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)?[0] as! T
}
}
Use it.
let cell: AbcViewCell = UITableViewCell.fromNib()
sudo apt-get install python-dev # for python2.x installs
sudo apt-get install python3-dev # for python3.x installs
It will install any missing headers. It solved my issue
Based on my knowledge, if you put your image folder in your public folder, you can just do the following:
<div :style="{backgroundImage: `url(${project.imagePath})`}"></div>
If you put your images in the src/assets/
, you need to use require. Like this:
<div :style="{backgroundImage: 'url('+require('@/assets/'+project.image)+')'}">.
</div>
One important thing is that you cannot use an expression that contains the full URL like this project.image = '@/assets/image.png'
. You need to hardcode the '@assets/'
part. That was what I've found. I think the reason is that in Webpack, a context is created if your require contains expressions, so the exact module is not known on compile time. Instead, it will search for everything in the @/assets
folder. More info could be found here. Here is another doc explains how the Vue loader treats the link in single file components.
A pop-up is a child of the parent window, but it is not a child of the parent DOCUMENT. It is its own independent browser window and is not contained by the parent.
Use an absolutely-positioned DIV and a translucent overlay instead.
EDIT - example
You need jQuery for this:
<style>
html, body {
height:100%
}
#overlay {
position:absolute;
z-index:10;
width:100%;
height:100%;
top:0;
left:0;
background-color:#f00;
filter:alpha(opacity=10);
-moz-opacity:0.1;
opacity:0.1;
cursor:pointer;
}
.dialog {
position:absolute;
border:2px solid #3366CC;
width:250px;
height:120px;
background-color:#ffffff;
z-index:12;
}
</style>
<script type="text/javascript">
$(document).ready(function() { init() })
function init() {
$('#overlay').click(function() { closeDialog(); })
}
function openDialog(element) {
//this is the general dialog handler.
//pass the element name and this will copy
//the contents of the element to the dialog box
$('#overlay').css('height', $(document.body).height() + 'px')
$('#overlay').show()
$('#dialog').html($(element).html())
centerMe('#dialog')
$('#dialog').show();
}
function closeDialog() {
$('#overlay').hide();
$('#dialog').hide().html('');
}
function centerMe(element) {
//pass element name to be centered on screen
var pWidth = $(window).width();
var pTop = $(window).scrollTop()
var eWidth = $(element).width()
var height = $(element).height()
$(element).css('top', '130px')
//$(element).css('top',pTop+100+'px')
$(element).css('left', parseInt((pWidth / 2) - (eWidth / 2)) + 'px')
}
</script>
<a href="javascript:;//close me" onclick="openDialog($('#content'))">show dialog A</a>
<a href="javascript:;//close me" onclick="openDialog($('#contentB'))">show dialog B</a>
<div id="dialog" class="dialog" style="display:none"></div>
<div id="overlay" style="display:none"></div>
<div id="content" style="display:none">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisl felis, placerat in sollicitudin quis, hendrerit vitae diam. Nunc ornare iaculis urna.
</div>
<div id="contentB" style="display:none">
Moooo mooo moo moo moo!!!
</div>
I had the same problem while trying to install newer version of ruby 2.6.5 https://github.com/kelaberetiv/TagUI/issues/86 helps me to solve the problem. This if for macOS catalina Version 10.15.1
Basically, I did update and upgrade
homebrew and install openssl and install ruby.
brew update && brew upgrade
brew install openssl
Then create these 2 symlinks
ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/
ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/
then installed ruby 2.6.5
I do the following:
...WHERE
fieldname COLLATE DATABASE_DEFAULT = otherfieldname COLLATE DATABASE_DEFAULT
Works every time. :)
I needed to do this for an AWS ELB. After getting beaten up by the dialog many times, finally this is what worked for me:
openssl rsa -in server.key -text > private.pem
openssl x509 -inform PEM -in server.crt > public.pem
Thanks NCZ
Edit: As @floatingrock says
With AWS, don't forget to prepend the filename with file://
. So it'll look like:
aws iam upload-server-certificate --server-certificate-name blah --certificate-body file://path/to/server.crt --private-key file://path/to/private.key --path /cloudfront/static/
http://docs.aws.amazon.com/cli/latest/reference/iam/upload-server-certificate.html
Using onBackPressed()
method:
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
or use the finish()
method, I have something like
//Password Error, I call function
Quit();
protected void Quit() {
super.finish();
}
With super.finish() you close the super class's activity.
Try this:
your_command 2>stderr.log 1>stdout.log
The numerals 0
through 9
are file descriptors in bash.
0
stands for standard input, 1
stands for standard output, 2
stands for standard error. 3
through 9
are spare for any other temporary usage.
Any file descriptor can be redirected to a file or to another file descriptor using the operator >
. You can instead use the operator >>
to appends to a file instead of creating an empty one.
Usage:
file_descriptor > filename
file_descriptor > &file_descriptor
Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.
In Java 8 you have some many operators to use, for instance limit
/**
* Operator that limit the total number of items emitted through the pipeline
* Shall print
* [1]
* @throws InterruptedException
*/
@Test
public void limitStream() throws InterruptedException {
List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
.stream()
.limit(1)
.collect(toList());
System.out.println(list);
}
It is happening because you must have used another variable named "project" in your code. Something like
var project = {}
For you to make the code work, change as follows:
var project = {}
into var project1 = {}
Here is a simple letter-range implementation:
Code
def letter_range(start, stop="{", step=1):
"""Yield a range of lowercase letters."""
for ord_ in range(ord(start.lower()), ord(stop.lower()), step):
yield chr(ord_)
Demo
list(letter_range("a", "f"))
# ['a', 'b', 'c', 'd', 'e']
list(letter_range("a", "f", step=2))
# ['a', 'c', 'e']
Try this code
import re
re.sub(r'[^\x00-\x7F]+','','paste your string here').decode('utf-8','ignore').strip()
I had the same problem. The solutions was to use core.js instead of debug.core.js
This is because of a huge view state, In my case I got lucky since I was not using the viewstate. I just added enableviewstate="false"
on the form tag and view state went from 35k to 100 chars
Rebind your DatagridView to the source.
DataGridView dg1 = new DataGridView();
dg1.DataSource = src1;
// Update Data in src1
dg1.DataSource = null;
dg1.DataSource = src1;
$(document).ready(function() {
$(document)[0].oncontextmenu = function() { return false; }
$(document).mousedown(function(e) {
if( e.button == 2 ) {
alert('Sorry, this functionality is disabled!');
return false;
} else {
return true;
}
});
});
If you want to disable it only on image click the instead of $(document).mousedown
use $("#yourimage").mousedown
Here's my solution which I derived from other posts during my own search.
This allows you to send the pp and jj output to a file as needed.
require "pp"
require "json"
class File
def pp(*objs)
objs.each {|obj|
PP.pp(obj, self)
}
objs.size <= 1 ? objs.first : objs
end
def jj(*objs)
objs.each {|obj|
obj = JSON.parse(obj.to_json)
self.puts JSON.pretty_generate(obj)
}
objs.size <= 1 ? objs.first : objs
end
end
test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }
test_json_object = JSON.parse(test_object.to_json)
File.open("log/object_dump.txt", "w") do |file|
file.pp(test_object)
end
File.open("log/json_dump.txt", "w") do |file|
file.jj(test_json_object)
end
Ok, I think I got it.
The client is the docker
command installed into OS X.
The host is the Boot2Docker VM.
The daemon is a background service running inside Boot2Docker.
This variable tells the client how to connect to the daemon.
When starting Boot2Docker, the terminal window that pops up already has DOCKER_HOST
set, so that's why docker
commands work. However, to run Docker commands in other terminal windows, you need to set this variable in those windows.
Failing to set it gives a message like this:
$ docker run hello-world
2014/08/11 11:41:42 Post http:///var/run/docker.sock/v1.13/containers/create:
dial unix /var/run/docker.sock: no such file or directory
One way to fix that would be to simply do this:
$ export DOCKER_HOST=tcp://192.168.59.103:2375
But, as pointed out by others, it's better to do this:
$ $(boot2docker shellinit)
$ docker run hello-world
Hello from Docker. [...]
To spell out this possibly non-intuitive Bash command, running boot2docker shellinit
returns a set of Bash commands that set environment variables:
export DOCKER_HOST=tcp://192.168.59.103:2376
export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
export DOCKER_TLS_VERIFY=1
Hence running $(boot2docker shellinit)
generates those commands, and then runs them.
in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display e.g 0.02f will print 25.00 0.002f will print 25.000
I found this the quick and easy way:
Used: org.json.XML
class from java-json.jar
if (statusCode == 200 && inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = bufferedReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
IF OBJECT_ID('mytablename') IS NOT NULL
DateTime dCalcDate = DateTime.Now;
var startDate = new DateTime(Convert.ToInt32(Year), Convert.ToInt32(Month), 1);
var endDate = new DateTime(Convert.ToInt32(Year), Convert.ToInt32(Month), DateTime.DaysInMonth((Convert.ToInt32(Year)), Convert.ToInt32(Month)));
Variables can contain single quotes.
myvar=\'....$variable\'
repo forall -c $myvar
It is not recursion, it is overloading. The two add methods (the one in your snippet, and the one "provided" by ArrayList that you are extending) are not the same method, cause they are declared with different parameters.
this.setState({
items: this.state.items.map((item,index) => {
if (index === 1) {
item.name = 'newName';
}
return item;
})
});
Bootstrap 3 removed those color options for badges. However, we can add those styles manually. Here's my solution, and here is the JS Bin:
.badge {
padding: 1px 9px 2px;
font-size: 12.025px;
font-weight: bold;
white-space: nowrap;
color: #ffffff;
background-color: #999999;
-webkit-border-radius: 9px;
-moz-border-radius: 9px;
border-radius: 9px;
}
.badge:hover {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
.badge-error {
background-color: #b94a48;
}
.badge-error:hover {
background-color: #953b39;
}
.badge-warning {
background-color: #f89406;
}
.badge-warning:hover {
background-color: #c67605;
}
.badge-success {
background-color: #468847;
}
.badge-success:hover {
background-color: #356635;
}
.badge-info {
background-color: #3a87ad;
}
.badge-info:hover {
background-color: #2d6987;
}
.badge-inverse {
background-color: #333333;
}
.badge-inverse:hover {
background-color: #1a1a1a;
}
Ubuntu 11.10 doesn't have maven3 in repo.
Follow below step to install maven3 on ubuntu 11.10
sudo add-apt-repository ppa:natecarlson/maven3
sudo apt-get update && sudo apt-get install maven3
Open terminal: mvn3 -v
if you want mvn as a binary then execute below script:
sudo ln -s /usr/bin/mvn3 /usr/bin/mvn
I hope this will help you.
Thanks, Rajam
// Regex for special symbols
var regex_symbols= /[-!$%^&*()_+|~=`{}\[\]:\/;<>?,.@#]/;
Go to the directory
cd /usr/local
Remove it with super user privileges
sudo rm -rf go
In my case, its Password was longer than 100 characters. Setting it to a smaller character password worked.
Actually I am wondering is there a reference somewhere to that.
If you want to filter out only your app's activities currently running/paused, you can use this command:
adb shell dumpsys activity activities | grep 'Hist #' | grep 'YOUR_PACKAGE_NAME'
For example:
adb shell dumpsys activity activities | grep 'Hist #' | grep 'com.supercell.clashroyale'
The output will be something like:
* Hist #2: ActivityRecord{26ba44b u10 com.supercell.clashroyale/StartActivity t27770}
* Hist #1: ActivityRecord{2f3a0236 u10 com.supercell.clashroyale/SomeActivity t27770}
* Hist #0: ActivityRecord{20bbb4ae u10 com.supercell.clashroyale/OtherActivity t27770}
Do notice that the output shows the actual stack of activities i.e. the topmost activity is the one that is currently being displayed.
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.
Function myDateFormat(myDate)
d = TwoDigits(Day(myDate))
m = TwoDigits(Month(myDate))
y = Year(myDate)
myDateFormat= m & "-" & d & "-" & y
End Function
Function TwoDigits(num)
If(Len(num)=1) Then
TwoDigits="0"&num
Else
TwoDigits=num
End If
End Function
edit: added function to format day and month as 0n
if value is less than 10
.
I would suggest using numpy's sort, as it is anyway what pandas is doing in background:
import numpy as np
np.sort(df.A.unique())
But doing all in pandas is valid as well.
You need to do it like this,
void Yourfunction(List<DateTime> dates )
{
}
There is a very simple solution using dense_rank()
dense_rank() over (partition by [Mth] order by [UserAccountKey])
+ dense_rank() over (partition by [Mth] order by [UserAccountKey] desc)
- 1
This will give you exactly what you were asking for: The number of distinct UserAccountKeys within each month.
<%--
Commented out HTML/CODE/Markup. Anything with
this block will not be parsed/handled by ASP.NET.
<asp:Calendar runat="server"></asp:Calendar>
<%# Eval(“SomeProperty”) %>
--%>
For Android Studio / intellij users:
static void InsertSettings(IEnumerable<Entry> settings) {
using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
using (SqlCommand oCommand = oConnection.CreateCommand()) {
oCommand.Transaction = oTransaction;
oCommand.CommandType = CommandType.Text;
oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
try {
foreach (var oSetting in settings) {
oCommand.Parameters[0].Value = oSetting.Key;
oCommand.Parameters[1].Value = oSetting.Value;
if (oCommand.ExecuteNonQuery() != 1) {
//'handled as needed,
//' but this snippet will throw an exception to force a rollback
throw new InvalidProgramException();
}
}
oTransaction.Commit();
} catch (Exception) {
oTransaction.Rollback();
throw;
}
}
}
}
}
Edit: Although this question has been marked as a duplicate, it has still been getting attention. The answer provided by @JaKXz is correct and should be the accepted answer.
You'll need to check for the existence of the view. Then do a CREATE VIEW
or ALTER VIEW
depending on the result.
IF OBJECT_ID('dbo.data_VVVV') IS NULL
BEGIN
CREATE VIEW dbo.data_VVVV
AS
SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
ALTER VIEW dbo.data_VVVV
AS
SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
BEGIN
END
I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
OrderId = o.id,
OrderDate = o.orderDate,
OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
});
data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));
If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.
An example looks like this:
String urlString = "http://wherever.com/someAction?param1=value1¶m2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
Try this
new DropdownButton<String>(
items: <String>['A', 'B', 'C', 'D'].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (_) {},
)
This is an extension method for the ASP.Net MVC action link helper method that allows it to use the controller's authorize attributes to decide if the link should be enabled, disabled or hidden from the current user's view. I saves you from having to enclose your restricted actions in "if" clauses that check for user membership in all the views. Thanks to Maarten Balliauw for the idea and the code bits that showed me the way :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using System.Web.Routing;
using System.Web.Mvc;
using System.Collections;
using System.Reflection;
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
/// <summary>
/// Shows or hides an action link based on the user's membership status
/// and the controller's authorize attributes
/// </summary>
/// <param name="linkText">The link text.</param>
/// <param name="action">The controller action name.</param>
/// <param name="controller">The controller name.</param>
/// <returns></returns>
public static string SecurityTrimmedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false, null);
}
/// <summary>
/// Enables, disables or hides an action link based on the user's membership status
/// and the controller's authorize attributes
/// </summary>
/// <param name="linkText">The link text.</param>
/// <param name="action">The action name.</param>
/// <param name="controller">The controller name.</param>
/// <param name="showDisabled">if set to <c>true</c> [show link as disabled -
/// using a span tag instead of an anchor tag ].</param>
/// <param name="disabledAttributeText">Use this to add attributes to the disabled
/// span tag.</param>
/// <returns></returns>
public static string SecurityTrimmedActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller,
bool showDisabled,
string disabledAttributeText)
{
if (IsAccessibleToUser(action, controller, HttpContext.Current ))
{
return htmlHelper.ActionLink(linkText, action, controller);
}
else
{
return showDisabled ?
String.Format(
"<span{1}>{0}</span>",
linkText,
disabledAttributeText==null?"":" "+disabledAttributeText
) : "";
}
}
private static IController GetControllerInstance(string controllerName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type controllerType = GetControllerType(controllerName);
return (IController)Activator.CreateInstance(controllerType);
}
private static ArrayList GetControllerAttributes(string controllerName, HttpContext context)
{
if (context.Cache[controllerName + "_ControllerAttributes"] == null)
{
var controller = GetControllerInstance(controllerName);
context.Cache.Add(
controllerName + "_ControllerAttributes",
new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true)),
null,
Caching.Cache.NoAbsoluteExpiration,
Caching.Cache.NoSlidingExpiration,
Caching.CacheItemPriority.Default,
null);
}
return (ArrayList)context.Cache[controllerName + "_ControllerAttributes"];
}
private static ArrayList GetMethodAttributes(string controllerName, string actionName, HttpContext context)
{
if (context.Cache[controllerName + "_" + actionName + "_ActionAttributes"] == null)
{
ArrayList actionAttrs = new ArrayList();
var controller = GetControllerInstance(controllerName);
MethodInfo[] methods = controller.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);
if ((attributes.Length == 0 && method.Name == actionName)
||
(attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionName))
{
actionAttrs.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));
}
}
context.Cache.Add(
controllerName + "_" + actionName + "_ActionAttributes",
actionAttrs,
null,
Caching.Cache.NoAbsoluteExpiration,
Caching.Cache.NoSlidingExpiration,
Caching.CacheItemPriority.Default,
null);
}
return (ArrayList)context.Cache[controllerName + "_" + actionName+ "_ActionAttributes"];
}
public static bool IsAccessibleToUser(string actionToAuthorize, string controllerToAuthorize, HttpContext context)
{
IPrincipal principal = context.User;
//cache the attribute list for both controller class and it's methods
ArrayList controllerAttributes = GetControllerAttributes(controllerToAuthorize, context);
ArrayList actionAttributes = GetMethodAttributes(controllerToAuthorize, actionToAuthorize, context);
if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)
return true;
string roles = "";
string users = "";
if (controllerAttributes.Count > 0)
{
AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (actionAttributes.Count > 0)
{
AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;
roles += attribute.Roles;
users += attribute.Users;
}
if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)
return true;
string[] roleArray = roles.Split(',');
string[] usersArray = users.Split(',');
foreach (string role in roleArray)
{
if (role == "*" || principal.IsInRole(role))
return true;
}
foreach (string user in usersArray)
{
if (user == "*" && (principal.Identity.Name == user))
return true;
}
return false;
}
private static Type GetControllerType(string controllerName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.GetTypes())
{
if (
type.BaseType!=null
&& type.BaseType.Name == "Controller"
&& (type.Name.ToUpper() == (controllerName.ToUpper() + "Controller".ToUpper())))
{
return type;
}
}
return null;
}
}
}
Using a ConstraintLayout
, I've found something like
<Button
android:id="@+id/left_button"
android:layout_width="80dp"
android:layout_height="48dp"
android:text="<"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@+id/left_button"
app:layout_constraintRight_toLeftOf="@+id/right_button"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/right_button"
android:layout_width="80dp"
android:layout_height="48dp"
android:text=">"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
works. The key is setting the right, left, top, and bottom edge constraints appropriately, then setting the width and height to 0dp
and letting it figure out it's own size.
This is a quick efficient one:
bool isPrimeNumber(int n) {
int divider = 2;
while (n % divider != 0) {
divider++;
}
if (n == divider) {
return true;
}
else {
return false;
}
}
It will start finding a divisible number of n, starting by 2. As soon as it finds one, if that number is equal to n then it's prime, otherwise it's not.
an easy way with out much redundancy.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Fileout As Object
Set Fileout = fso.CreateTextFile("C:\your_path\vba.txt", True, True)
Fileout.Write "your string goes here"
Fileout.Close
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
Select s.stock_code,s.stock_desc,s.stock_desc_ar,
mc.category_name,s.sel_price,
case when s.allow_discount=0 then 'Non Promotional Item' else 'Prmotional
item' end 'Promotion'
From tbl_stock s inner join tbl_stock_category c on s.stock_id=c.stock_id
inner join tbl_category mc on c.category_id=mc.category_id
where mc.category_id=2 and s.isSerialBased=0
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
I would say to err on the high side. Since you'll probably be using varchar, any extra space you allow won't actually use up any extra space unless somebody needs it. I would say for names (first or last), go at least 50 chars, and for email address, make it at least 128. There are some really long email addresses out there.
Another thing I like to do is go to Lipsum.com and ask it to generate some text. That way you can get a good idea of just what 100 bytes looks like.
The sklearn.metrics.accuracy_score(y_true, y_pred)
method defines y_pred as
:
y_pred : 1d array-like, or label indicator array / sparse matrix. Predicted labels, as returned by a classifier.
Which means y_pred
has to be an array of 1's or 0's (predicated labels). They should not be probabilities.
The predicated labels (1's and 0's) and/or predicted probabilites can be generated using the LinearRegression()
model's methods predict()
and predict_proba()
respectively.
1. Generate predicted labels:
LR = linear_model.LinearRegression()
y_preds=LR.predict(X_test)
print(y_preds)
output:
[1 1 0 1]
y_preds
can now be used for the accuracy_score()
method: accuracy_score(y_true, y_pred)
2. Generate probabilities for labels:
Some metrics such as 'precision_recall_curve(y_true, probas_pred)' require probabilities, which can be generated as follows:
LR = linear_model.LinearRegression()
y_preds=LR.predict_proba(X_test)
print(y_preds)
output:
[0.87812372 0.77490434 0.30319547 0.84999743]
With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.
let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});
Please note that data values should be string, ie; { params: {limit: "2"}}
Use HttpParams, HttpClient from @angular/common/http
import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});
Also, try stringifying your nested object using JSON.stringify()
.
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
first, you have to create a handler.
var specialElementHandlers = {
'#editor': function(element, renderer){
return true;
}
};
then write this code in click event:
doc.fromHTML($('body').get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
var pdfOutput = doc.output();
console.log(">>>"+pdfOutput );
assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.
A portable approach that works equally well on Linux or Windows (where there is no /dev/null):
echo | gcc -dM -E -
For c++ you may use (replace c++11
with whatever version you use):
echo | gcc -x c++ -std=c++11 -dM -E -
It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters
). If you want to know what defines are added when you include a header file you can use -dD
option which is similar to -dM but does not include predefined macros:
echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -
Note, however, that empty input still produces lots of defines with -dD
option.
On your DBA account, give USERB the right to create a procedure using grant grant create any procedure to USERB
The procedure will look
CREATE OR REPLACE PROCEDURE USERB.USERB_PROCEDURE
--Must add the line below
AUTHID CURRENT_USER AS
BEGIN
--DO SOMETHING HERE
END
END
GRANT EXECUTE ON USERB.USERB_PROCEDURE TO USERA
I know this is a very old question but I am hoping I could chip it a bit.
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
Set up a constructor in your entity and set the default value there.
Issue Background:
I was getting following error when i try to run mvn clean install in my project and through Netbeans IDE clean and build option. This issue is due to certificate not available when we download through NET beans IDE/through command prompt, but able to download the files through the browser.
Error:
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.java.project:product:jar:1.0.32 from/to repo-local (https://url/local-repo): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Resolution:
1. Download the certificate of the Url in question:
2. Now install the key store to fix the issue.
C:\Program Files\Java\jdk1.8.0_141\jre\bin>keytool -importcert -file "C:/user/sheldon/desktop/product.cer" -alias product -keystore "C:/Program Files/Java/jdk1.8.0_141/jre/lib/security/cacerts".
Sample command line commands/output:
keytool -importcert -file "C:/Users/sheldon/Desktop/product.cer" -alias product -keystore "C:/Program iles/Java/jdk1.8.0_141/jre/lib/security/cacerts"
Enter keystore password:
Trust this certificate? [no]: yes
Certificate was added to keystore
The Main Reason for the denying permission is that we don’t have permission for drawing over another apps,We have to provide the permission for the Drawing over other apps that can be done by the following code
Request code for Permission
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
add this in your MainActivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
askPermission();
}
private void askPermission() {
Intent intent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
Add this also
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE){
if(!Settings.canDrawOverlays(this)){
askPermission();
}
}
}
To get parameters from URL string, I used following function.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var email = getUrlParameter('email');
If there are many URL strings, then you can use loop to get parameter 'email' from all those URL strings and store them in array.
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
Solution for LAMP users:
apt-get install php5-json
service apache2 restart
umh.. like that?
$newstring = substr($dynamicstring, -7);
We faced this issue, In order to fix this, solution is dead simple is below.
Basically this error tells that your current build got failed due to reasons like Code issue or dependency issue.
If you take advantage of width: 100vw;
and height: 100vh;
, the object with these styles applied will stretch to the full width and height of the device.
Also note, there are times padding and margins can get added to your view, by browsers and the like. I added a *
global no padding and margins so you can see the difference. Keep this in mind.
*{_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
This happens because in r6 it shows an error when you try to extend private styles.
Refer to this link
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-
app.get('/', function(req, res){
console.log(req.query.name);
res.send('Response send to client::'+req.query.name);
});
Many of us develop in Eclipse via a Maven project. If so,
you can include Tomcat dependencies in Maven via the tomcat-servlet-api
and tomcat-jsp-api
jars. One exists for each version of Tomcat. Usually adding these with scope provided
to your POM is sufficient. This will keep your build more portable.
If you upgrade Tomcat in the future, you simply update the version of these jars as well.
People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">
Python allows you to use a string as an iterator:
for character in 'string':
print(character)
I'm guessing it's your job to figure out how to turn that into a while loop.
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
Another approach
=CONCATENATE("Age as of ", TEXT(TODAY(),"dd-mmm-yyyy"))
This will return Age as of 06-Aug-2013
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
In my case, my Android app uses Volley to make a POST call with an empty body to an API application hosted on Microsoft Azure.
The error was:
JSONException: Value <p>iisnode of type java.lang.String cannot be converted to JSONObject
This is a snippet on how I was constructing the Volley JSON request:
final JSONObject emptyJsonObject = new JSONObject();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, emptyJsonObject, listener, errorListener);
I solved my problem by creating the JSONObject
with an empty JSON object as follows:
final JSONObject emptyJsonObject = new JSONObject("{}");
My solution is along the lines to this older answer.
First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.
Create the menu layouts as per your need and number.
Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.
Please check the below code for the reference and for more info checkout my project from github
<android.support.constraint.ConstraintLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.fabmenu.MainActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/baseFloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:clickable="true"
android:onClick="@{FabHandler::onBaseFabClick}"
android:tint="@android:color/white"
app:fabSize="normal"
app:layout_constraintBottom_toBottomOf="@+id/activity_main"
app:layout_constraintRight_toRightOf="@+id/activity_main"
app:srcCompat="@drawable/ic_add_black_24dp" />
<LinearLayout
android:id="@+id/shareLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/createLayout"
app:layout_constraintLeft_toLeftOf="@+id/createLayout"
app:layout_constraintRight_toRightOf="@+id/activity_main">
<TextView
android:id="@+id/shareLabelTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="@drawable/shape_fab_label"
android:elevation="2dp"
android:fontFamily="sans-serif"
android:padding="5dip"
android:text="Share"
android:textColor="@android:color/white"
android:typeface="normal" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/shareFab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="@{FabHandler::onShareFabClick}"
android:tint="@android:color/white"
app:fabSize="mini"
app:srcCompat="@drawable/ic_share_black_24dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/createLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
app:layout_constraintRight_toRightOf="@+id/activity_main">
<TextView
android:id="@+id/createLabelTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="@drawable/shape_fab_label"
android:elevation="2dp"
android:fontFamily="sans-serif"
android:padding="5dip"
android:text="Create"
android:textColor="@android:color/white"
android:typeface="normal" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/createFab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="@{FabHandler::onCreateFabClick}"
android:tint="@android:color/white"
app:fabSize="mini"
app:srcCompat="@drawable/ic_create_black_24dp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
These are the animations-
Opening animation of FAB Menu:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="300"
android:fromXScale="0"
android:fromYScale="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="1"
android:toYScale="1" />
<alpha
android:duration="300"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
Closing animation of FAB Menu:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
android:duration="300"
android:fromXScale="1"
android:fromYScale="1"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="0.0"
android:toYScale="0.0" />
<alpha
android:duration="300"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
</set>
Then in my Activity I've simply used the animations above to show and hide the FAB menu :
Show Fab Menu:
private void expandFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabOpenAnimation);
binding.shareLayout.startAnimation(fabOpenAnimation);
binding.createFab.setClickable(true);
binding.shareFab.setClickable(true);
isFabMenuOpen = true;
}
Close Fab Menu:
private void collapseFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabCloseAnimation);
binding.shareLayout.startAnimation(fabCloseAnimation);
binding.createFab.setClickable(false);
binding.shareFab.setClickable(false);
isFabMenuOpen = false;
}
Here is the the Activity class -
package com.app.fabmenu;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import com.app.fabmenu.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setFabHandler(new FabHandler());
getAnimations();
}
private void getAnimations() {
fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);
fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);
}
private void expandFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabOpenAnimation);
binding.shareLayout.startAnimation(fabOpenAnimation);
binding.createFab.setClickable(true);
binding.shareFab.setClickable(true);
isFabMenuOpen = true;
}
private void collapseFabMenu() {
ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
binding.createLayout.startAnimation(fabCloseAnimation);
binding.shareLayout.startAnimation(fabCloseAnimation);
binding.createFab.setClickable(false);
binding.shareFab.setClickable(false);
isFabMenuOpen = false;
}
public class FabHandler {
public void onBaseFabClick(View view) {
if (isFabMenuOpen)
collapseFabMenu();
else
expandFabMenu();
}
public void onCreateFabClick(View view) {
Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();
}
public void onShareFabClick(View view) {
Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
if (isFabMenuOpen)
collapseFabMenu();
else
super.onBackPressed();
}
}
Here are the screenshots
Why not...
bool isEmpty = !list.Any();
if(isEmpty)
{
// error message
}
else
{
// show grid
}
The GridView
has also an EmptyDataTemplate
which is shown if the datasource is empty. This is an approach in ASP.NET:
<emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataErrorImg"
imageurl="~/images/NoDataError.jpg" runat="server"/>
No Data Found!
</emptydatatemplate>
Alternatively, if you're working in .NET v4.5 or above, try using System.Web.MimeMapping.GetMimeMapping(yourFileName) to get MIME types. It is much better than hard-coding strings.
An alternative to extend LayoutManager can be just set the size of the view manually.
Number of items per row height (if all the items have the same height and the separator is included on the row)
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mListView.getLayoutParams();
params.height = mAdapter.getItemCount() * getResources().getDimensionPixelSize(R.dimen.row_height);
mListView.setLayoutParams(params);
Is still a workaround, but for basic cases it works.
DECLARE @Number int = 1;
SELECT RIGHT('0'+ CONVERT(VARCHAR, @Number), 2)
--OR
SELECT RIGHT(CONVERT(VARCHAR, 100 + @Number), 2)
GO
Dictionaries and Hashtables are not serializable with XmlSerializer
. Therefore you cannot use them directly. A workaround would be to use the XmlIgnore
attribute to hide those properties from the serializer and expose them via a list of serializable key-value pairs.
PS: constructing an XmlSerializer
is very expensive, so always cache it if there is a chance of being able to re-use it.
There is a great moment
method called fromNow()
that will return the time from a specific time in nice human readable form, like this:
moment('2019-04-30T07:30:53.000Z').fromNow() // an hour ago || a day ago || 10 days ago
Or if you want that between two specific dates you can use:
var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b); // "a day ago"
Taken from the Docs:
Given that there are so many edge cases for each country (eg. London addresses may use a slightly different format to the rest of the UK) I don't think that there is an ultimate regex other than maybe:
[0-9a-zA-Z]+
Best of going with a fairly broad pattern (well not quite as broad as the above), or treat each country/region with a specific pattern of its own!
UPDATE: However, it may be possible to dynamically construct a regex based upon lots of smaller, region specific rules - not sure about performance though!
Lots of country specific patterns can be found on the RegExLib site.
If you are that particular to pass elements to viewmodel You can use
CommandParameter="{Binding ElementName=ManualParcelScanScreen}"
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
More oin regards to question part 4 How do you e-mail that error to an email address? The error_log function has email destination too. http://php.net/manual/en/function.error-log.php
Agha, here I found an example that shows a usage. Send errors message via email using error_log()
error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);
Yes there is a difference.
The Runtime.exec(String)
method takes a single command string that it splits into a command and a sequence of arguments.
The ProcessBuilder
constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)
So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.
No, it is not considered good practice. On the contrary, it is generally considered a bad idea.
http://www.gotw.ca/publications/mill22.htm goes into a lot more detail about why, but the problem is partly that the compiler is unable to enforce this, so it has to be checked at runtime, which is usually undesirable. And it is not well supported in any case. (MSVC ignores exception specifications, except throw(), which it interprets as a guarantee that no exception will be thrown.
The proper way to do this in VB is to use on of the VB constants for newlines. The main three are
VB by default doesn't allow for any character escape codes in strings which is different than languages like C# and C++ which do. One of the reasons for doing this is ease of use when dealing with file paths.
If you want an all-purpose local development stack for any operating system where you can choose from different PHP, MySQL and Web server versions and are also not afraid of using Docker, you could go for the devilbox.
The devilbox is a modern and highly customisable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts and DNS records are created automatically. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is pre-setup with mass virtual hosting.
Getting it up and running is pretty straight-forward:
# Get the devilbox
$ git clone https://github.com/cytopia/devilbox
$ cd devilbox
# Create docker-compose environment file
$ cp env-example .env
# Edit your configuration
$ vim .env
# Start all containers
$ docker-compose up
Links:
$('form[name="frmSave"]')
is correct. You mentioned you thought this would get all children with the name frmsave
inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');
$('form[name="frmSave"]')
literally means find all forms with the name frmSave
, because there is no combinator involved.
My solution is basically a modification of @Termininja's answer, however I have enhanced it a bit and it appears to be more than 5 times faster than the accepted answer.
public static void CopyEntireDirectory(string path, string newPath)
{
Parallel.ForEach(Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories)
,(fileName) =>
{
string output = Regex.Replace(fileName, "^" + Regex.Escape(path), newPath);
if (File.Exists(fileName))
{
Directory.CreateDirectory(Path.GetDirectoryName(output));
File.Copy(fileName, output, true);
}
else
Directory.CreateDirectory(output);
});
}
EDIT: Modifying @Ahmed Sabry to full parallel foreach does produce a better result, however the code uses recursive function and its not ideal in some situation.
public static void CopyEntireDirectory(DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)
{
if (!source.Exists) return;
if (!target.Exists) target.Create();
Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>
CopyEntireDirectory(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));
Parallel.ForEach(source.GetFiles(), sourceFile =>
sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles));
}
First of all, anyone can create 2 keys. One to encrypt data, and another to decrypt data. The former can be a private key, and the latter a public key, AND VICERZA.
Second of all, in simplest terms, a Certificate Authority (CA) offers the service of creating a certificate for you. How? They use certain values (the CA's issuer name, your server's public key, company name, domain, etc.) and they use their SUPER DUPER ULTRA SECURE SECRET private key and encrypt this data. The result of this encrypted data is a SIGNATURE.
So now the CA gives you back a certificate. The certificate is basically a file containing the values previously mentioned (CA's issuer name, company name, domain, your server's public key, etc.), INCLUDING the signature (i.e. an encrypted version of the latter values).
Now, with all that being said, here is a REALLY IMPORTANT part to remember: your device/OS (Windows, Android, etc.) pretty much keeps a list of all major/trusted CA's and their PUBLIC KEYS (if you're thinking that these public keys are used to decrypt the signatures inside the certificates, YOU ARE CORRECT!).
Ok, if you read the above, this sequential example will be a breeze now:
Why? Think about it, only this public key can decrypt the signature in such a way that the contents look like they did before the private key encrypted them.
This is one of the main reasons (if not the main reason) why the above standard was created.
Let's say hacker-Jane intercepts internet-user-Bob's request, and replies with her own certificate. However, hacker-Jane is still careful enough to state in the certificate that the issuer was Example-CA. Lastly, hacker-Jane remembers that she has to include a signature on the certificate. But what key does Jane use to sign (i.e. create an encrypted value of the certificate main contents) the certificate?????
So even if hacker-Jane signed the certificate with her own key, you see what's gonna happen next. The browser is gonna say: "ok, this certificate is issued by Example-CA, let's decrypt the signature with Example-CA's public key". After decryption, the browser notices that the certificate contents don't match at all. Hence, the browser gives a very clear warning to the user, and it says it doesn't trust the connection.
As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent XRegExp and its Unicode plug-in.
I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.
I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).
con = file("pathtotargetfile", "r")
readsizeof<-2 # read size for one step to caculate number of lines in file
nooflines<-0 # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0) # calculate number of lines. Also a better solution for big file
nooflines<-nooflines+linesread
con = file("pathtotargetfile", "r") # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0) # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
print(is.vector(tmp))
print(tmp)
}
close(con)
To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:
$ echo kill | nc -w 2 localhost 5554
(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)
I've started to think that using the 'iframe' for Ajax style upload might be a much better choice for my situation until HTML5 comes full circle and I don't have to support legacy browsers in my app!
og:title
is one of the open graph meta tags. og:...
properties define objects in a social graph. They are used for example by Facebook.
og:title
stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.
Here's a method I wrote that takes a slightly different approach. Rather than specifying the characters to remove, I tell my method which characters I want to keep -- it will remove all other characters.
In the OP's example, he only wants to keep alphabetical characters and spaces. Here's what a call to my method would look like (C# demo):
var str = "My name @is ,Wan.;'; Wan";
// "My name is Wan Wan"
var result = RemoveExcept(str, alphas: true, spaces: true);
Here's my method:
/// <summary>
/// Returns a copy of the original string containing only the set of whitelisted characters.
/// </summary>
/// <param name="value">The string that will be copied and scrubbed.</param>
/// <param name="alphas">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="numerics">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="dashes">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="underlines">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="spaces">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="periods">If true, all decimal characters (".") will be preserved; otherwise, they will be removed.</param>
public static string RemoveExcept(string value, bool alphas = false, bool numerics = false, bool dashes = false, bool underlines = false, bool spaces = false, bool periods = false) {
if (string.IsNullOrWhiteSpace(value)) return value;
if (new[] { alphas, numerics, dashes, underlines, spaces, periods }.All(x => x == false)) return value;
var whitelistChars = new HashSet<char>(string.Concat(
alphas ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : "",
numerics ? "0123456789" : "",
dashes ? "-" : "",
underlines ? "_" : "",
periods ? "." : "",
spaces ? " " : ""
).ToCharArray());
var scrubbedValue = value.Aggregate(new StringBuilder(), (sb, @char) => {
if (whitelistChars.Contains(@char)) sb.Append(@char);
return sb;
}).ToString();
return scrubbedValue;
}
This is the easy way to do this
var value = 5 + "" + 6;
Is that commit in the other branch? Git checkout <commitid>
will just switch over to the other branch if the commit has happened in the other branch. You will want to merge the changes to your first branch if you want the code there.
string = "hello world";
strrev = ""
list = [];
def splitstring(string):
j = 0;
for i in range(0,len(string)):
if(string[i] == " "):
list.append(string[j:i]);
j = i+1;
elif (i+1 == len(string)):
list.append(string[j:i+1]);
splitstring(string);
for i in list:
for j in range(len(i)-1,-1,-1):
strrev += i[j];
if (i != list[-1]):
strrev+= " ";
print(list);
print(":%s:" %(strrev));
SearchView
can be added as actionView
in menu using
app:useActionClass = "android.support.v7.widget.SearchView" .
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
android:id="@+id/searchBar"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
/>
</menu>
SearchView.OnQueryTextListener
has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.
YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.searchBar);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setQueryHint("Search People");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
This is how you can implement abstract methods of the listener.
@Override
public boolean onQueryTextSubmit(String query) {
// This method can be used when a query is submitted eg. creating search history using SQLite DB
Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView
.
public void filter(String queryText)
{
list.clear();
if(queryText.isEmpty())
{
list.addAll(copyList);
}
else
{
for(String name: copyList)
{
if(name.toLowerCase().contains(queryText.toLowerCase()))
{
list.add(name);
}
}
}
notifyDataSetChanged();
}
Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App
Thread holds behaviour which is not intended to be accessed;
however if you sub-class Thread have to consider more Thread is implemented.
public class ThreadMain {
public int getId() {
return 12345678;
}
public String getName() {
return "Hello World";
}
public String getState() {
return "testing";
}
public void example() {
new Thread() {
@Override
public void run() {
System.out.println("id: "+getId()+", name: "+getName()+", state: "+getState());
}
}.start();
}
public static void main(String[] args) {
new ThreadMain().example();
}
}
If you run this you might expect
id: 12345678, name: Hello World, state: testing
however, you are not calling the methods you think you are because you are using the method in Thread
not ThreadMain
and instead you see something like
id: 11, name: Thread-0, state: RUNNABLE
POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.
I'm assuming you've got a nice fat USB HD and a good connection to the net. You can use apt-mirror to essentially create your own debian mirror.
Have you noticed that in the code you posted, condition2
is never set to False
? This way, your loop body is never executed.
Also, note that in Python, not condition
is preferred to condition == False
; likewise, condition
is preferred to condition == True
.
Yes, you can.
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
YMMV.
It works because only Safari Mobile implements -webkit-touch-callout
: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout
Please note that @supports
does not work in IE. IE will skip both of the above @support
blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not
because of this.
What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.
Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling
but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".
Most likely, the userdata()
function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.
I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.
So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...
Maybe the code might be cleaner, but it works for me pretty well.
<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>
<script>
var map;
function initialize() {
// Get all map canvas with ".maps" and store them to a variable.
var maps = document.getElementsByClassName("maps");
var ids, gps, mapId = '';
// Loop: Explore all elements with ".maps" and create a new Google Map object for them
for(var i=0; i<maps.length; i++) {
// Get ID of single div
mapId = document.getElementById(maps[i].id);
// Get LatLng stored in data attribute.
// !!! Make sure there is no space in data-attribute !!!
// !!! and the values are separated with comma !!!
gps = mapId.getAttribute('data-gps');
// Convert LatLng to an array
gps = gps.split(",");
// Create new Google Map object for single canvas
map = new google.maps.Map(mapId, {
zoom: 15,
// Use our LatLng array bellow
center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
mapTypeId: 'roadmap',
mapTypeControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
}
});
// Create new Google Marker object for new map
var marker = new google.maps.Marker({
// Use our LatLng array bellow
position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
map: map
});
}
}
</script>
You can access elements of parent window from within an iframe by using window.parent
like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top
like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
__dirname
Gives you the current node application's rooth directory.
In your case, you'd use
__dirname + '/Desktop/MyApp/newversion/partials/navigation.jade';
See this answer:
For readability, I prefer this:
if (inputString.length() > maxLength) {
inputString = inputString.substring(0, maxLength);
}
over the accepted answer.
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.
There are three answers here, depending on the version of React you're (forced to) work(ing) with, and whether you want to use hooks.
It's important to understand how React works, so you can do things properly (protip: it's is super worth running through the React tutorial exercise on the React website. It's well written, and covers all the basics in a way that actually explains how to do things). "Properly" here means that you're writing an application interface that happens to be rendered in a browser; all the interface work happens in React, not in "what you're used to if you're writing a web page" (this is why React apps are "apps", not "web pages").
React applications are rendered based off of two things:
What you're expressly not doing when you use React is generating HTML elements and then using those: when you tell React to use an <input>
, for instance, you are not creating an HTML input element, you are telling React to create a React input object that happens to render as an HTML input element, and whose event handling looks at, but is not controlled by, the HTML element's input events.
When using React, what you're doing is generating application UI elements that present the user with (often manipulable) data, with user interaction changing the Component's state, which may cause a rerender of part of your application interface to reflect the new state. In this model, the state is always the final authority, not "whatever UI library is used to render it", which on the web is the browser's DOM. The DOM is almost an afterthought in this programming model: it's just the particular UI framework that React happens to be using.
So in the case of an input element, the logic is:
render
call after the update, but only if the state update changed the state.All of that happens in a matter of milliseconds, if not less, so it looks like you typed into the input element in the same way you're used to from "just using an input element on a page", but that's absolutely not what happened.
So, with that said, on to how to get values from elements in React:
To do things properly, your component has a state value, which is shown via an input field, and we can update it by making that UI element send change events back into the component:
var Component = React.createClass({
getInitialState: function() {
return {
inputValue: ''
};
},
render: function() {
return (
//...
<input value={this.state.inputValue} onChange={this.updateInputValue}/>
//...
);
},
updateInputValue: function(evt) {
this.setState({
inputValue: evt.target.value
});
}
});
So we tell React to use the updateInputValue
function to handle the user interaction, use setState
to schedule the state update, and the fact that render
taps into this.state.inputValue
means that when it rerenders after updating the state, the user will see the update text based on what they typed.
addendum based on comments
Given that UI inputs represent state values (consider what happens if a user closes their tab midway, and the tab is restored. Should all those values they filled in be restored? If so, that's state). That might make you feel like a large form needs tens or even a hundred input forms, but React is about modeling your UI in a maintainable way: you do not have 100 independent input fields, you have groups of related inputs, so you capture each group in a component and then build up your "master" form as a collection of groups.
MyForm:
render:
<PersonalData/>
<AppPreferences/>
<ThirdParty/>
...
This is also much easier to maintain than a giant single form component. Split up groups into Components with state maintenance, where each component is only responsible for tracking a few input fields at a time.
You may also feel like it's "a hassle" to write out all that code, but that's a false saving: developers-who-are-not-you, including future you, actually benefit greatly from seeing all those inputs hooked up explicitly, because it makes code paths much easier to trace. However, you can always optimize. For instance, you can write a state linker
MyComponent = React.createClass({
getInitialState() {
return {
firstName: this.props.firstName || "",
lastName: this.props.lastName || ""
...: ...
...
}
},
componentWillMount() {
Object.keys(this.state).forEach(n => {
let fn = n + 'Changed';
this[fn] = evt => {
let update = {};
update[n] = evt.target.value;
this.setState(update);
});
});
},
render: function() {
return Object.keys(this.state).map(n => {
<input
key={n}
type="text"
value={this.state[n]}
onChange={this[n + 'Changed']}/>
});
}
});
Of course, there are improved versions of this, so hit up https://npmjs.com and search for a React state linking solution that you like best. Open Source is mostly about finding what others have already done, and using that instead of writing everything yourself from scratch.
As of React 16 (and soft-starting with 15.5) the createClass
call is no longer supported, and class syntax needs to be used. This changes two things: the obvious class syntax, but also the this
context binding that createClass
can do "for free", so to ensure things still work make sure you're using "fat arrow" notation for this
context preserving anonymous functions in onWhatever
handlers, such as the onChange
we use in the code here:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
};
}
render() {
return (
//...
<input value={this.state.inputValue} onChange={evt => this.updateInputValue(evt)}/>
//...
);
},
updateInputValue(evt) {
this.setState({
inputValue: evt.target.value
});
}
});
You may also have seen people use bind
in their constructor for all their event handling functions, like this:
constructor(props) {
super(props);
this.handler = this.handler.bind(this);
...
}
render() {
return (
...
<element onclick={this.handler}/>
...
);
}
Don't do that.
Almost any time you're using bind
, the proverbial "you're doing it wrong" applies. Your class already defines the object prototype, and so already defines the instance context. Don't put bind
of top of that; use normal event forwarding instead of duplicating all your function calls in the constructor, because that duplication increases your bug surface, and makes it much harder to trace errors because the problem might be in your constructor instead of where you call your code. As well as placing a burden of maintenance on others that you (have or choose) to work with.
Yes, I know the react docs say it's fine. It's not, don't do it.
As of React 16.8 the function component (i.e. literally just a function that takes some props
as argument can be used as if it's an instance of a component class, without ever writing a class) can also be given state, through the use of hooks.
If you don't need full class code, and a single instance function will do, then you can now use the useState
hook to get yourself a single state variable, and its update function, which works roughly the same as the above examples, except without the setState
function call:
import { useState } from 'react';
function myFunctionalComponentFunction() {
const [input, setInput] = useState(''); // '' is the initial state value
return (
<div>
<label>Please specify:</label>
<input value={input} onInput={e => setInput(e.target.value)}/>
</div>
);
}
Previously the unofficial distinction between classes and function components was "function components don't have state", so we can't hide behind that one anymore: the difference between function components and classes components can be found spread over several pages in the very well-written react documentation (no shortcut one liner explanation to conveniently misinterpret for you!) which you should read so that you know what you're doing and can thus know whether you picked the best (whatever that means for you) solution to program yourself out of a problem you're having.
There is a slight effect, since you're doing the same check twice, at least in your example:
IF EXISTS(SELECT 1 FROM Contacs WHERE [Type] = 1)
Has to query, see if there are any, if true then:
UPDATE Contacs SET [Deleted] = 1 WHERE [Type] = 1
Has to query, see which ones...same check twice for no reason. Now if the condition you're looking for is indexed it ought to be quick, but for large tables you could see some delay just because you're running the select.
Set your css to this
img {
max-width:100%,
max-height100%
}