Need to support old browser and have a object hierarchy
body.head.eyes[0] //body, head, eyes may be null
may use this,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
other = s or "some default value"
Ok, it must be clarified how the or
operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.
Note that the or
operator does not return only True
or False
. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.
In this case, the expression x or y
returns x
if it is True
or evaluates to true when converted to boolean. Otherwise, it returns y
. For most cases, this will serve for the very same purpose of C?'s null-coalescing operator, but keep in mind:
42 or "something" # returns 42
0 or "something" # returns "something"
None or "something" # returns "something"
False or "something" # returns "something"
"" or "something" # returns "something"
If you use your variable s
to hold something that is either a reference to the instance of a class or None
(as long as your class does not define members __nonzero__()
and __len__()
), it is secure to use the same semantics as the null-coalescing operator.
In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None
specifically (an error object, for example).
In some languages this behavior is referred to as the Elvis operator.
For the beginners:
Null coalescing operator (??)
Everything is true except null
values and undefined (variable/array index/object attributes)
ex:
$array = [];
$object = new stdClass();
var_export (false ?? 'second'); # false
var_export (true ?? 'second'); # true
var_export (null ?? 'second'); # 'second'
var_export ('' ?? 'second'); # ""
var_export ('some text' ?? 'second'); # "some text"
var_export (0 ?? 'second'); # 0
var_export ($undefinedVarible ?? 'second'); # "second"
var_export ($array['undefined_index'] ?? 'second'); # "second"
var_export ($object->undefinedAttribute ?? 'second'); # "second"
this is basically check the variable(array index, object attribute.. etc) is exist and not null
. similar to isset
function
Ternary operator shorthand (?:)
every false things (false
,null
,0
,empty string) are come as false, but if it's a undefined it also come as false but Notice
will throw
ex
$array = [];
$object = new stdClass();
var_export (false ?: 'second'); # "second"
var_export (true ?: 'second'); # true
var_export (null ?: 'second'); # "second"
var_export ('' ?: 'second'); # "second"
var_export ('some text' ?? 'second'); # "some text"
var_export (0 ?: 'second'); # "second"
var_export ($undefinedVarible ?: 'second'); # "second" Notice: Undefined variable: ..
var_export ($array['undefined_index'] ?: 'second'); # "second" Notice: Undefined index: ..
var_export ($object->undefinedAttribute ?: 'second'); # "Notice: Undefined index: ..
Hope this helps
It's short hand for the ternary operator.
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
Or for those who don't do ternary:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}
Add this into your httpd.conf file
Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore
To come full circle and include all versions of Visual Studio, @Myster originally stated that;
Pre Visual Studio 2015 the paths to applicationhost.config were:
%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config
Visual Studio 2015/2017 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\applicationhost.config
Visual Studio 2019 path can be found at: (credit: @Talon)
$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config
But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)
So, if you make a change in the applicationhost.config you also have to make sure your changes match here:
$(solutionDir)\ProjectName.sln
The two important settings should look like:
Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
and
VWDPort = "Port#"
What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.
Try placing your text-decoration: none;
on your a:hover css.
As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"
for example :
<mat-table #table [dataSource]="dataSource" matSortDisableClear>
<ng-container matColumnDef="productId">
<mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
<mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
</ng-container>
<ng-container matColumnDef="productName">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
<mat-cell *matCellDef="let product">
<button (click)="view(product)">
<mat-icon>visibility</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
here matColumnDef
is
productId
, productName
and action
now we apply width by matColumnDef
styling
.mat-column-productId {
flex: 0 0 10%;
}
.mat-column-productName {
flex: 0 0 50%;
}
and remaining width is equally allocated to other columns
For more info Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11
Curiously, you’ll notice that the connection attempts to change the http protocol to https to protect against mistakes in your code where you may have accidentally misconfigured the URL. In some cases, this might actually work, but it’s also confusing.
This Shipping an App With App Transport Security covers some good debugging tips
ATS Failure
Most ATS failures will present as CFErrors with a code in the -9800 series. These are defined in the Security/SecureTransport.h header
2015-08-23 06:34:42.700 SelfSignedServerATSTest[3792:683731] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
CFNETWORK_DIAGNOSTICS
Set the environment variable CFNETWORK_DIAGNOSTICS to 1 in order to get more information on the console about the failure
nscurl
The tool will run through several different combinations of ATS exceptions, trying a secure connection to the given host under each ATS configuration and reporting the result.
nscurl --ats-diagnostics https://example.com
I'm afraid I don't think there's a shortcut to do this - if only someone would write a linq wrapper for VB6!
You could write a function that does it by looping through the array and checking each entry - I don't think you'll get cleaner than that.
There's an example article that provides some details here: http://www.vb6.us/tutorials/searching-arrays-visual-basic-6
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print('Executed After', original_function.__name__, '\n')
return result
return wrapper_function
@decorator_function
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))
display_info('Mr Bean', 66)
display_info('MC Jordan', 57)
output:
Executed Before display_info
display_info ran with arguments (Mr Bean, 66)
Executed After display_info
Executed Before display_info
display_info ran with arguments (MC Jordan, 57)
Executed After display_info
So now let's go ahead and get our decorator function to accept arguments.
For example let's say that I wanted a customizable prefix to all of these print statements within the wrapper.
Now this would be a good candidate for an argument to the decorator.
The argument that we pass in will be that prefix. Now in order to do, this we're just going to add another outer layer to our decorator, so I'm going to call this a function a prefix decorator.
def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function
@prefix_decorator('LOG:')
def display_info(name, age):
print('display_info ran with arguments ({}, {})'.format(name, age))
display_info('Mr Bean', 66)
display_info('MC Jordan', 57)
output:
LOG: Executed Before display_info
display_info ran with arguments (Mr Bean, 66)
LOG: Executed After display_info
LOG: Executed Before display_info
display_info ran with arguments (MC Jordan, 57)
LOG: Executed After display_info
LOG:
prefix before our print statements in our wrapper function and you can change this any time that you want.My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?
<select name="owner">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>
Sounds like an lxml advertisement in here. ;) ElementTree is included in the std library. Under 2.6 and below its xpath is pretty weak, but in 2.7+ much improved:
import xml.etree.ElementTree as ET
root = ET.parse(filename)
result = ''
for elem in root.findall('.//child/grandchild'):
# How to make decisions based on attributes even in 2.6:
if elem.attrib.get('name') == 'foo':
result = elem.text
break
Open the terminal Ctrl+`
Under output ESLint
dropdown, you find useful debugging data (Errors, warnings, info).
For example, missing .eslintrc-.json
throw this error:
Error: ENOENT: no such file or directory, realpath
Next, check if the plugin enabled:
Last, Since v 2.0.4 - eslint.validate
in normal cases not necessary anymore (old legacy setting):
eslint.probe
= an array for language identifiers for which the ESLint extension should be activated and should try to validate the file. If validation fails for probed languages the extension says silent. Defaults to [javascript
,javascriptreact
,typescript
,typescriptreact
,html
,vue
,markdown
].
My issue was related to the ESLint plugin "currently block" status bar on New/First instalation (v2.1.14).
no modal dialog is shown when the ESLint extension tries to load an ESLint library for the first time and an approval is necessary. Instead the ESLint status bar item changes to ESLint status icon indicating that the execution is currently block.
Click on the status-bar
(Right-Bottom corner):
Opens this popup:
Approve ==> Allows Everywhere
-or- by commands:
ctrl + Shift + p -- ESLint: Manage Library Execution
Read more here under "Release Notes":
https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint
To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:
$ rm -rf .git
Or to delete .gitignore and .gitmodules if any (via @aragaer):
$ rm -rf .git*
Then from the same ex-repository folder, to see if hidden folder .git is still there:
$ ls -lah
If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).
To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:
defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder
Source: http://lifehacker.com/188892/show-hidden-files-in-finder.
maybe you can try using
SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'
You're trying to remove index.php from your site URL's, correct?
Try setting your $config['uri_protocol']
to REQUEST_URI
instead of AUTO
.
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
try this:
[self dismissViewControllerAnimated:true completion:nil];
this worked for me..
<Location />
Allow from all
Order Deny,Allow
</Location>
I have included this code in my /etc/apache2/apache2.conf
For what it's worth here are the step by step instructions for doing this in an Android device. Should be the same for iOS:
You should then be able to see the SSL files in Charles. If you want to intercept and change the values you can use the "Map Local" tool which is really awesome:
You can't be sure that the user account that your service is running under even has permissions to stop and restart the service.
I've created a couple of map tutorials that will cover what you need
Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.
Take a look at these 2 tutorials and the Github project containing the sample app.
It contains some tips to make your code cleaner and more efficient:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.map((myArr, index) => {
console.log(`your index is -> ${index} AND value is ${myArr}`);
})
_x000D_
> output will be
index is -> 0 AND value is 1
index is -> 1 AND value is 2
index is -> 2 AND value is 3
index is -> 3 AND value is 4
index is -> 4 AND value is 5
index is -> 5 AND value is 6
index is -> 6 AND value is 7
index is -> 7 AND value is 8
index is -> 8 AND value is 9
Consider 2 dataFrames:
>>> aDF.show()
+---+----+
| id|datA|
+---+----+
| 1| a1|
| 2| a2|
| 3| a3|
+---+----+
and
>>> bDF.show()
+---+----+
| id|datB|
+---+----+
| 2| b2|
| 3| b3|
| 4| b4|
+---+----+
To accomplish what you are looking for, there are 2 ways:
1. Different joining condition. Instead of saying aDF.id == bDF.id
aDF.join(bDF, aDF.id == bDF.id, "outer")
Write this:
aDF.join(bDF, "id", "outer").show()
+---+----+----+
| id|datA|datB|
+---+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
| 4|null| b4|
+---+----+----+
This will automatically get rid of the extra the dropping process.
2. Use Aliasing: You will lose data related to B Specific Id's in this.
>>> from pyspark.sql.functions import col
>>> aDF.alias("a").join(bDF.alias("b"), aDF.id == bDF.id, "outer").drop(col("b.id")).show()
+----+----+----+
| id|datA|datB|
+----+----+----+
| 1| a1|null|
| 3| a3| b3|
| 2| a2| b2|
|null|null| b4|
+----+----+----+
I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:
#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file
This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/
and placing a wildcard in place of the_original_line
.
I prefer the Boost Timer library for its simplicity, but if you don't want to use third-parrty libraries, using clock() seems reasonable.
The logit (/'lo?d??t/ LOH-jit) function is the inverse of the sigmoidal "logistic" function or logistic transform used in mathematics, especially in statistics. When the function's variable represents a probability p, the logit function gives the log-odds, or the logarithm of the odds p/(1 - p).
See here: https://en.wikipedia.org/wiki/Logit
You could use jquery ui's switchClass
, Heres an example:
$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );
Or see this jsfiddle.
I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;
<script>
var video = document.getElementById("myVideoPlayer");
function stopVideo(){
video.pause();
video.currentTime = 0;
}
</script>
Now you can use stopVideo() method to stop HTML5 video. Like,
$("#stop").on('click', function(){
stopVideo();
});
In [34]: a=np.arange(-10,10)
In [35]: a
Out[35]:
array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9])
In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)
In [37]: np.where(a>5)[0][0]
Out[37]: 16
Your function is failing because the groupby dataframe you end up with has a hierarchical index and two columns (Letter and N) so when you do .hist()
it's trying to make a histogram of both columns hence the str error.
This is the default behavior of pandas plotting functions (one plot per column) so if you reshape your data frame so that each letter is a column you will get exactly what you want.
df.reset_index().pivot('index','Letter','N').hist()
The reset_index()
is just to shove the current index into a column called index
. Then pivot
will take your data frame, collect all of the values N
for each Letter
and make them a column. The resulting data frame as 400 rows (fills missing values with NaN
) and three columns (A, B, C
). hist()
will then produce one histogram per column and you get format the plots as needed.
You can use Excel's Index
function:
=INDEX(Age, 5)
$("body").on("click", "#tableid tr", function () {
debugger
alert($(this).text());
});
$("body").on("click", "#tableid td", function () {
debugger
alert($(this).text());
});
less than 2 seconds per user usually - ie users that see slower responses than this think the system is slow.
Now you tell me how many users you have connected.
You can use the following array methods to obtain a column from a 2D array:
const array_column = (array, column) => array.map(e => e[column]);
const array_column = (array, column) => array.reduce((a, c) => {
a.push(c[column]);
return a;
}, []);
const array_column = (array, column) => {
const result = [];
array.forEach(e => {
result.push(e[column]);
});
return result;
};
If your 2D array is a square (the same number of columns for each row), you can use the following method:
const array_column = (array, column) => array.flat().filter((e, i) => i % array.length === column);
Convert would be the normal answer, but the format is not a recognised format for the converter, mm/dd/yyyy could be converted using convert(datetime,yourdatestring,101) but you do not have that format so it fails.
The problem is the format being non-standard, you will have to manipulate it to a standard the convert can understand from those available.
Hacked together, if you can guarentee the format
declare @date char(8)
set @date = '12312009'
select convert(datetime, substring(@date,5,4) + substring(@date,1,2) + substring(@date,3,2),112)
For creating a hashing table from scratch, all the values has to set to "None" and modified once a requirement arises. Hashable objects refers to the modifiable datatypes(Dictionary,lists etc). Sets on the other hand cannot be reinitialized once assigned, so sets are non hashable. Whereas, The variant of set() -- frozenset() -- is hashable.
use like this
<script type=text/javascript>
function validate(){
if (document.getElementById('remember').checked){
alert("checked") ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
</script>
<input id="remember" name="remember" type="checkbox" onclick="validate()" />
I don't believe you can alter an existing column to be an identity column using tsql. However, you can do it through the Enterprise Manager design view.
Alternatively you could create a new row as the identity column, drop the old column, then rename your new column.
ALTER TABLE FooTable
ADD BarColumn INT IDENTITY(1, 1)
NOT NULL
PRIMARY KEY CLUSTERED
You can do this:
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
OR Something like
var dateObj = new Date();
var month = dateObj.getUTCMonth();
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = month + "/" + day + "/" + year;
alert(newdate);
Use pandas!
def isMonthEnd(date):
return date + pd.offsets.MonthEnd(0) == date
isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False
Put this at the top of the other files where you want to access the class:
using CLIck10.App_Code;
OR access the class from other files like this:
CLIck10.App_Code.Glob
Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on.
Update: I recently found that if I add an App_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.
The by far the simplest approach is:
yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)
If Jenkins run in a the Jenkins Docker container you can use this command line in Bash:
java -jar /var/jenkins_home/war/WEB-INF/jenkins-cli.jar -s http://localhost:8080/ list-plugins --username admin --password `/bin/cat /var/jenkins_home/secrets/initialAdminPassword`
ActiveSupport::OrderedHash is another option if you don't want to use ruby 1.9.2 or roll your own workarounds.
Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.
If not just try tgp.linkurl.htm or html, ie default.html
, www/home/siteurl/web/
, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/
, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess
or default.html
. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.
Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).
You can use type-converter. To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
@Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.
https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js
If you have 2 routes that perform the same action you can do the following to keep it DRY.
var express = require("express"),
app = express.createServer();
function fooRoute(req, res, next) {
res.end("Foo Route\n");
}
app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);
app.listen(3000);
I missed to add
@Controller("userBo") into UserBoImpl class.
The solution for this is adding this controller into Impl class.
Following worked just fine for me in Junit 5
https://junit.org/junit5/docs/current/user-guide/#running-tests-build-maven
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</build>
<!-- ... -->
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<!-- ... -->
</dependencies>
<!-- ... -->
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
I tried the same on Intellij Ideav11.
It was not picking up the settings after checking the process using grep. In case it does not, give the mem settings for JAVA_OPTS in catalina.sh instead.
We can use following code
textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
Where
"Text"
– the property of textbox model
– the model object enter code here "Name"
– the value of model which to bind the textbox.I will explain the method i usally prefer:
First of all you need to take into consideration that for this method you will sacrifice memory with the aim of gaining computation speed. Second you need to have a the right to edit the table structure.
1) Add a field (i usually call it "digest") where you store all the data from the table.
The field will look like:
"n-n1-n2-n3-n4-n5-n6-n7-n8-n9" etc.. where n is a single word
I achieve this using a regular expression thar replaces " " with "-". This field is the result of all the table data "digested" in one sigle string.
2) Use the LIKE statement %keyword% on the digest field:
SELECT * FROM table WHERE digest LIKE %keyword%
you can even build a qUery with a little loop so you can search for multiple keywords at the same time looking like:
SELECT * FROM table WHERE
digest LIKE %keyword1% AND
digest LIKE %keyword2% AND
digest LIKE %keyword3% ...
I propose a script for removing randomly picked up items off a list until it is empty:
Maintain a set
and remove randomly picked up element (with choice
) until list is empty.
s=set(range(1,6))
import random
while len(s)>0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
You can still use angular.isDefined()
You just need to set
$rootScope.angular = angular;
in the "run" phase.
See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview
It's possible to do it in CSS
.disabled{_x000D_
cursor:default;_x000D_
pointer-events:none;_x000D_
text-decoration:none;_x000D_
color:black;_x000D_
}
_x000D_
<a href="https://www.google.com" target="_blank" class="disabled">Google</a>
_x000D_
See at:
Please note that the text-decoration: none;
and color: black;
is not needed but it makes the link look more like plain text.
Yes, if you use the SQL Server Agent.
Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.
Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:
exec MyStoredProcedure
That's the overview, post back here if you need any further advice.
[I actually thought I might get in first on this one, boy was I wrong :)]
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
In some cases, Reflection doesn't work properly.
You could use dictionaries, if all item types are the same. For instance, if your items are strings :
Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);
Or ints:
Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);
In case someone is trying to run a script in a RAILS environment, rails provide a runner to execute scripts in rails context via
rails runner my_script.rb
More details here: https://guides.rubyonrails.org/command_line.html#rails-runner
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
Try this:
Select
Id,
Salt,
Password,
BannedEndDate,
(Select Count(*)
From LoginFails
Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
From Users
Where username = '" + LoginModel.Username + "'
And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!
Hope that helps!
Some feedback on the segment of code, though for the most part, it should work...
void main(int c,char **args)
int main
- the standard defines main
as returning an int
.c
and args
are typically named argc
and argv
, respectfully, but you are allowed to name them anything...
{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
args[1]
is longer than 50 bytes, buffer
will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy
......
dir=opendir(buffer); //this part
If this returning NULL
, it can be for a few reasons:
./your_program my directory
, which will fail, because it tries to opendir("my")
)req.connection
has been deprecated since [email protected]. Using req.connection.removeAddress
to get the client IP might still work but is discouraged.
Luckily, req.socket.remoteAddress
has been there since [email protected] and is a perfect replacement:
The string representation of the remote IP address. For example,
'74.125.127.100'
or'2001:4860:a005::68'
. Value may beundefined
if the socket is destroyed (for example, if the client disconnected).
CompressFormat is too slow...
Try ByteBuffer.
???Bitmap to byte???
width = bitmap.getWidth();
height = bitmap.getHeight();
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byteArray = byteBuffer.array();
???byte to bitmap???
Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name());
Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
bitmap_tmp.copyPixelsFromBuffer(buffer);
You just need to create a class which extends Exception (for a checked exception) or any subclass of Exception, or RuntimeException (for a runtime exception) or any subclass of RuntimeException.
Then, in your code, just use
if (word.contains(" "))
throw new MyException("some message");
}
Read the Java tutorial. This is basic stuff that every Java developer should know: http://docs.oracle.com/javase/tutorial/essential/exceptions/
An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.
Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.
If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.
It is the difference between identity and equivalence.
a == b
means that a and b are identical, that is, they are symbols for very same object in memory.
a.equals( b )
means that they are equivalent, that they are symbols for objects that in some sense have the same value -- although those objects may occupy different places in memory.
Note that with equivalence, the question of how to evaluate and compare objects comes into play -- complex objects may be regarded as equivalent for practical purposes even though some of their contents differ. With identity, there is no such question.
If you use custom Makefiles, you can double click on the .includes file and add it there.
Take this code as an example:
elements = ['a', 'b', 'c', 'd', 'e']
index = 0
for element in elements:
print element, index
index += 1
You loop over the list and store an index variable as well. enumerate()
does the same thing, but more concisely:
elements = ['a', 'b', 'c', 'd', 'e']
for index, element in enumerate(elements):
print element, index
The index, element
notation is required because enumerate
returns a tuple ((1, 'a')
, (2, 'b')
, ...) that is unpacked into two different variables.
What about using a tabular inside \author{}
, just like in IEEE macros:
\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c}
I. M. Author & M. Y. Coauthor \\
My Department & Coauthor Department \\
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle
\end{document}
This will produce two columns authors with any documentclass
.
Results:
Very nice pdf about many GIT secrets.
Add is same as svn's add (how ever sometimes it is used to mark file resolved).
Commit also is same as svn's , but it commit change into your local repository.
const url = "http://www.example.com/1234"
const id = url.split('/').pop();
Try this, it is much easier
The output gives 1234
There is an issue on Chromium open since 2011, that if you are explicitly setting the domain as 'localhost', you should set it as false
or undefined
.
according to this it's proxy isssues, try to disable ssl and set registry to http instead of https . hope it helps!
npm config set registry=http://registry.npmjs.org/
npm config set strict-ssl false
Check if npm config production value is set to true. If this value is true, it will skip over the dev dependencies.
Run npm config get production
To set it: npm config set -g production false
Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:
URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo
in your activity:
Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Uri uri = intent.getData();
String valueOne = uri.getQueryParameter("keyOne");
String valueTwo = uri.getQueryParameter("keyTwo");
}
As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.
In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.
Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever
This is the default modal css for 768px and up:
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
...
}
They have a class modal-lg
for larger widths
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.
@media (min-width: 768px) {
.modal-xl {
width: 90%;
max-width:1200px;
}
}
HTML
<div class="modal-dialog modal-xl">
Demo: http://jsbin.com/yefas/1
The other solution works great for square images. Here is a solution that will work for an image of any dimension. The canvas will always fit the image rather than the other solution which may cause portions of the image to be cropped off.
var canvas;
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
drawRotated(0);
}
image.src="http://greekgear.files.wordpress.com/2011/07/bob-barker.jpg";
$("#clockwise").click(function(){
angleInDegrees+=90 % 360;
drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){
if(angleInDegrees == 0)
angleInDegrees = 270;
else
angleInDegrees-=90 % 360;
drawRotated(angleInDegrees);
});
function drawRotated(degrees){
if(canvas) document.body.removeChild(canvas);
canvas = document.createElement("canvas");
var ctx=canvas.getContext("2d");
canvas.style.width="20%";
if(degrees == 90 || degrees == 270) {
canvas.width = image.height;
canvas.height = image.width;
} else {
canvas.width = image.width;
canvas.height = image.height;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
if(degrees == 90 || degrees == 270) {
ctx.translate(image.height/2,image.width/2);
} else {
ctx.translate(image.width/2,image.height/2);
}
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,-image.width/2,-image.height/2);
document.body.appendChild(canvas);
}
You have a basic answer here: Get city name using geolocation
But for what you are looking for, i'd recommend this way.
Only if you also need administrative_area_level_1,to store different things for Paris, Texas, US and Paris, Ile-de-France, France and provide a manual fallback:
--
There is a problem in Michal's way, in that it takes the first result, not a particular one. He uses results[0]. The way I see fit (I just modified his code) is to take ONLY the result whose type is "locality", which is always present, even in an eventual manual fallback in case the browser does not support geolocation.
His way: fetched results are different from using http://maps.googleapis.com/maps/api/geocode/json?address=bucharest&sensor=false than from using http://maps.googleapis.com/maps/api/geocode/json?latlng=44.42514,26.10540&sensor=false (searching by name / searching by lat&lng)
This way: same fetched results.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(results);
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++)
{
if (results[j].types[0]=='locality')
{
indice=j;
break;
}
}
alert('The good number is: '+j);
console.log(results[j]);
for (var i=0; i<results[j].address_components.length; i++)
{
if (results[j].address_components[i].types[0] == "locality") {
//this is the object you are looking for City
city = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
//this is the object you are looking for State
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}
//city data
alert(city.long_name + " || " + region.long_name + " || " + country.short_name)
} else {
alert("No results found");
}
//}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>
HTML CODE:
<div>
<video class="center" src="vd/vd1.mp4" controls poster="dossierimage/imagex.jpg" width="600">?</video>
</div>
CSS CODE:
.center {
margin-left: auto;
margin-right: auto;
display: block
}
If you're looking for a particular string, put quotes around it:
awk '$1 == "findtext" {print $3}'
Otherwise, awk will assume it's a variable name.
This SQL request works for me :
ALTER TABLE users
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;
This is my working code for express 4.0.
express 4.0 is very different from 3.0 and others.
4.0 you have /bin/www file, which you are going to add https here.
"npm start" is standard way you start express 4.0 server.
readFileSync() function should use __dirname get current directory
while require() use ./ refer to current directory.
First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.
no such directory found error:
key: fs.readFileSync('../private.key'),
cert: fs.readFileSync('../public.cert')
error, no such directory found
key: fs.readFileSync('./private.key'),
cert: fs.readFileSync('./public.cert')
Working code should be
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
Complete https code is:
const https = require('https');
const fs = require('fs');
// readFileSync function must use __dirname get current directory
// require use ./ refer to current directory.
const options = {
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
};
// Create HTTPs server.
var server = https.createServer(options, app);
Edit:
In 2.7 / 3.2 there is a new writeheader()
method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader()
method now available in 2.7 / 3.2:
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
dw.writeheader()
# continue on to write data
Instantiating DictWriter requires a fieldnames argument.
From the documentation:
The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.
Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with
statement was added in 2.6. If using 2.5: from __future__ import with_statement
with open(infile,'rb') as fin:
dr = csv.DictReader(fin, delimiter='\t')
# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
headers = {}
for n in dw.fieldnames:
headers[n] = n
dw.writerow(headers)
for row in dr:
dw.writerow(row)
As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
for row in dr:
dw.writerow(row)
You need to add a css rule that removes the after content (through a class)..
An update due to some valid comments.
The more correct way to completely remove/disable the :after
rule is to use
p.no-after:after{content:none;}
Original answer
You need to add a css rule that removes the after content (through a class)..
p.no-after:after{content:"";}
and add that class to your p
when you want to with this line
$('p').addClass('no-after'); // replace the p selector with what you need...
a working example at : http://www.jsfiddle.net/G2czw/
I tried the Homebrew and tarball points from the post by sospedra. It wasn't enough.
I found yarn installed in: ~/.config/yarn/global/node_modules/yarn
I ran yarn global remove yarn
. Restarted terminal and it was gone.
Originally, what brought me here was yarn reverting to an older version, but I didn't know why, and attempts to uninstall or upgrade failed.
When I would checkout an older branch of a certain project the version of yarn being used would change from 1.9.4
to 0.19.1
.
Even after taking steps to remove yarn, it remained, and at 0.19.1
.
From the Mozilla Developer Network (MDN) documentation, HTMLElement.click() is what you're looking for. You can find out more events here.
Setting isBodyHtml
to true
allows you to use HTML tags in the message body:
msg = new MailMessage("[email protected]",
"[email protected]", "Message from PSSP System",
"This email sent by the PSSP system<br />" +
"<b>this is bold text!</b>");
msg.IsBodyHtml = true;
It depends on your client.
However, if you're using the psql client, then you can use the following:
my_db=> \set myvar 5
my_db=> SELECT :myvar + 1 AS my_var_plus_1;
my_var_plus_1
---------------
6
If you are using text variables you need to quote.
\set myvar 'sometextvalue'
select * from sometable where name = :'myvar';
The closest approach I can think of is NULLIF:
SELECT
ISNULL(NULLIF(O.ShipName, C.CompanyName), 1),
O.ShipName,
C.CompanyName,
O.OrderId
FROM [Northwind].[dbo].[Orders] O
INNER JOIN [Northwind].[dbo].[Customers] C
ON C.CustomerId = O.CustomerId
GO
NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.
So, above query will return 1 for records in which that columns are equal, the first expression otherwise.
If you have a slow page or network connection, chances are that none of the above will work. I have tried them all and the only thing that worked for me is to wait for the last visible element on that page. Take for example the Bing webpage. They have placed a CAMERA icon (search by image button) next to the main search button that is visible only after the complete page has loaded. If everyone did that, then all we have to do is use an explicit wait like in the examples above.
Because the people who designed the library format didn't want to "waste" space for rarely used information like C preprocessor macros and function declarations.
Since you need that info to tell your compiler "this function is available later when the linker is doing its job", they had to come up with a second file where this shared information could be stored.
Most languages after C/C++ store this information in the output (Java bytecode, for example) or they don't use a precompiled format at all, get always distributed in source form and compile on the fly (Python, Perl).
Generic solution for combining two maps which can possibly share common keys:
In-place:
public static <K, V> void mergeInPlace(Map<K, V> map1, Map<K, V> map2,
BinaryOperator<V> combiner) {
map2.forEach((k, v) -> map1.merge(k, v, combiner::apply));
}
Returning a new map:
public static <K, V> Map<K, V> merge(Map<K, V> map1, Map<K, V> map2,
BinaryOperator<V> combiner) {
Map<K, V> map3 = new HashMap<>(map1);
map2.forEach((k, v) -> map3.merge(k, v, combiner::apply));
return map3;
}
In the case of Android, the StringUtils class from commons isn't available, so for this I used
android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)
http://developer.android.com/reference/android/text/TextUtils.html
In general, this depends what your map contains. If it has null values, things can get tricky and containsKey(key)
or get(key, default)
should be used to detect of the element really exists. In many cases the code can become simpler you can define a default value:
def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x1 = mymap.get('likes', '[nothing specified]')
println "x value: ${x}" }
Note also that containsKey()
or get()
are much faster than setting up a closure to check the element mymap.find{ it.key == "likes" }
. Using closure only makes sense if you really do something more complex in there. You could e.g. do this:
mymap.find{ // "it" is the default parameter
if (it.key != "likes") return false
println "x value: ${it.value}"
return true // stop searching
}
Or with explicit parameters:
mymap.find{ key,value ->
(key != "likes") return false
println "x value: ${value}"
return true // stop searching
}
run
gradle clean
then try
gradle build
it worked for me
Oracle 11g provides a PIVOT
operation that does what you want.
Oracle 11g solution
select * from
(select id, k, v from _kv)
pivot(max(v) for k in ('name', 'age', 'gender', 'status')
(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)
I obtained this solution from: http://orafaq.com/wiki/PIVOT
EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml
option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)
select * from
(select id, k, v from _kv)
pivot xml (max(v)
for k in (any) )
(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)
Edit2: Changed v
in the pivot
and pivot xml
statements to max(v)
since it is supposed to be aggregated as mentioned in one of the comments. I also added the in
clause which is not optional for pivot
. Of course, having to specify the values in the in
clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.
For the second part of your question, "get usage statistics of the given partition", psutil makes this easy with the disk_usage(path) function. Given a path, disk_usage()
returns a named tuple including total, used, and free space expressed in bytes, plus the percentage usage.
Simple example from documentation:
>>> import psutil
>>> psutil.disk_usage('/')
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
Psutil works with Python versions from 2.6 to 3.6 and on Linux, Windows, and OSX among other platforms.
func scrollToTop() {
NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
[tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
call this function wherever you want UITableView scroll to top
Env: macOS Mojave 10.14.4
Install: homebrew
Location:/usr/local/Cellar/mongodb/4.0.3_1
Note :If update version by
brew upgrade mongo
,the folder 4.0.4_1
will be removed and replace with the new version folder
When a there are 2 columns for primary keys they make up a composite primary key therefore you have to make sure that in the table that is being referenced there are also 2 columns of the same data type.
Not directly accessible like in angular1 but you can easily play with NgFormControl and RxJS observables:
<input type="text" [ngFormControl]="term"/>
this.items = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.wikipediaService.search(term));
This blog post explains it clearly: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
Here it is for an autocomplete but it works all scenarios.
With Xcode 4.2 you can use the -scheme flag to do this:
xcodebuild -scheme <SchemeName> archive
After this command the Archive will show up in the Xcode Organizer.
Although some answers here maybe great, none helped my case (which is very similar to OP's error message).
This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).
To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:
// pulled data in this life cycle hook, saving it to my store
created() {
FetchData.getProfile()
.then(myProfile => {
const mp = myProfile.data;
console.log(mp)
this.$store.dispatch('dispatchMyProfile', mp)
this.propsToPass = mp;
})
.catch(error => {
console.log('There was an error:', error.response)
})
}
// called my store here
computed: {
menu() {
return this.$store.state['myProfile'].profile
}
},
// then in my template, I pass this "menu" method in child component
<LeftPanel :data="menu" />
_x000D_
This cleared that error away. I deployed it again to firebase hosting, and viola!
Hope this bit helps you.
You can use duplicated
to do this very quickly.
test[!duplicated(test$id),]
Benchmarks, for the speed freaks:
ju <- function() test[!duplicated(test$id),]
gs1 <- function() do.call(rbind, lapply(split(test, test$id), head, 1))
gs2 <- function() do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
jply <- function() ddply(test,.(id),function(x) head(x,1))
jdt <- function() {
testd <- as.data.table(test)
setkey(testd,id)
# Initial solution (slow)
# testd[,lapply(.SD,function(x) head(x,1)),by = key(testd)]
# Faster options :
testd[!duplicated(id)] # (1)
# testd[, .SD[1L], by=key(testd)] # (2)
# testd[J(unique(id)),mult="first"] # (3)
# testd[ testd[,.I[1L],by=id] ] # (4) needs v1.8.3. Allows 2nd, 3rd etc
}
library(plyr)
library(data.table)
library(rbenchmark)
# sample data
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
benchmark(ju(), gs1(), gs2(), jply(), jdt(),
replications=5, order="relative")[,1:6]
# test replications elapsed relative user.self sys.self
# 1 ju() 5 0.03 1.000 0.03 0.00
# 5 jdt() 5 0.03 1.000 0.03 0.00
# 3 gs2() 5 3.49 116.333 2.87 0.58
# 2 gs1() 5 3.58 119.333 3.00 0.58
# 4 jply() 5 3.69 123.000 3.11 0.51
Let's try that again, but with just the contenders from the first heat and with more data and more replications.
set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
benchmark(ju(), jdt(), order="relative")[,1:6]
# test replications elapsed relative user.self sys.self
# 1 ju() 100 5.48 1.000 4.44 1.00
# 2 jdt() 100 6.92 1.263 5.70 1.15
Use collect($comments_collection)
.
Else, try json_encode($comments_collection)
to convert to json.
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
You could do something like this:
var object = {
foo:{a:'first'},
bar:{},
baz:{}
}
function getAttributeByIndex(obj, index){
var i = 0;
for (var attr in obj){
if (index === i){
return obj[attr];
}
i++;
}
return null;
}
var first = getAttributeByIndex(object, 0); // returns the value of the
// first (0 index) attribute
// of the object ( {a:'first'} )
You can bootstrap multiple angular applications, but:
1) You need to manually bootstrap them
2) You should not use "document" as the root, but the node where the angular interface is contained to:
var todoRootNode = jQuery('[ng-controller=TodoController]');
angular.bootstrap(todoRootNode, ['TodoApp']);
This would be safe.
The below code works on all APIs.(Kotlin)
However, getActiveNetworkInfo() is deprecated only in API 29 and works on all APIs , so we can use it in all Api's below 29
fun isInternetAvailable(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return result
}
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
WebSockets:
Ratified IETF standard (6455) with support across all modern browsers and even legacy browsers using web-socket-js polyfill.
Uses HTTP compatible handshake and default ports making it much easier to use with existing firewall, proxy and web server infrastructure.
Much simpler browser API. Basically one constructor with a couple of callbacks.
Client/browser to server only.
Only supports reliable, in-order transport because it is built On TCP. This means packet drops can delay all subsequent packets.
WebRTC:
Just beginning to be supported by Chrome and Firefox. MS has proposed an incompatible variant. The DataChannel component is not yet compatible between Firefox and Chrome.
WebRTC is browser to browser in ideal circumstances but even then almost always requires a signaling server to setup the connections. The most common signaling server solutions right now use WebSockets.
Transport layer is configurable with application able to choose if connection is in-order and/or reliable.
Complex and multilayered browser API. There are JS libs to provide a simpler API but these are young and rapidly changing (just like WebRTC itself).
You can do this with SQL Server Management Studio.
? Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, expand the menu "INSERT and UPDATE specification" and select "Cascade" as Delete Rule.
I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module"
to both external as well as internal js scripts.
Say, you have a file 'module.js':
var a = 10;
export {a};
You can use it in an external script, in which you do the import, eg.:
<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>
test.js:
import {a} from "./module.js";
alert(a);
You can also use it in an internal script, eg.:
<!DOCTYPE html><html><body>
<script type="module">
import {a} from "./module.js";
alert(a);
</script>
</body></html>
It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:
import {a} from "module.js"; // this won't work
The simplest way is to upgrade to Maven 3.3.1 or higher to take advantage of the ${maven.projectBasedir}/.mvn/jvm.config
support.
Then you can use any options from Maven's SL4FJ's SimpleLogger support to configure all loggers or particular loggers. For example, here is a how to make all warning at warn
level, except for a the PMD which is configured to log at error
:
cat .mvn/jvm.config
-Dorg.slf4j.simpleLogger.defaultLogLevel=warn -Dorg.slf4j.simpleLogger.log.net.sourceforge.pmd=error
See here for more details on logging with Maven.
Instead of using a submit button, try using a <button type="button">Submit</button>
You can then call a javascript function in the button, and after the alert popup is confirmed, you can manually submit the form with document.getElementById("form").submit(); ... so you'll need to name and id your form for that to work.
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true)
, just write if(condition)
(This way, for example, you'll not write =
by mistake).
You can also use df.icol(n)
to access a column by integer.
Update: icol
is deprecated and the same functionality can be achieved by:
df.iloc[:, n] # to access the column at the nth position
Think of it as a kind of turnstile like you might find at a football ground. There are parallel steams of people wanting to get in but at the turnstile they are 'synchronised'. Only one person at a time can get through. All those wanting to get through will do, but they may have to wait until they can go through.
os.path.realpath(__file__)
will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.
I was encountering this error while compiling my application with SDL. This was caused by SDL defining it's own main function in SDL_main.h. To prevent SDL define the main function an SDL_MAIN_HANDLED macro has to be defined before the SDL.h header is included.
How about using good(?) old goto
?
:loop
echo Ooops
goto loop
See also this for a more useful example.
The solution found here helped us to update master to a previous commit that had already been pushed:
git checkout master
git reset --hard e3f1e37
git push --force origin e3f1e37:master
The key difference from the accepted answer is the commit hash "e3f1e37:" before master in the push command.
Another way is like this:
multiple_cmd() {
tail -n1 $1;
ls $1
};
export -f multiple_cmd;
find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;
in one line
multiple_cmd() { tail -1 $1; ls $1 }; export -f multiple_cmd; find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;
multiple_cmd()
" - is a functionexport -f multiple_cmd
" - will export it so any other subshell can see itfind *.txt -exec bash -c 'multiple_cmd "$0"' {} \;
" - find that will execute the function on your exampleIn this way multiple_cmd can be as long and as complex, as you need.
Hope this helps.
I have used sub-query and it worked great!
SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories
I have used this command to troubleshoot client certificate negotiation:
openssl s_client -connect www.test.com:443 -prexit
The output will probably contain "Acceptable client certificate CA names" and a list of CA certificates from the server, or possibly "No client certificate CA names sent", if the server doesn't always require client certificates.
All solutions already proposed have severe problems. Some solutions fail to work on large arrays, some provide wrong output, some throw an error on btoa call if an intermediate string contains multibyte characters, some consume more memory than needed.
So I implemented a direct conversion function which just works regardless of the input. It converts about 5 million bytes per second on my machine.
https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
/*_x000D_
MIT License_x000D_
Copyright (c) 2020 Egor Nepomnyaschih_x000D_
Permission is hereby granted, free of charge, to any person obtaining a copy_x000D_
of this software and associated documentation files (the "Software"), to deal_x000D_
in the Software without restriction, including without limitation the rights_x000D_
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell_x000D_
copies of the Software, and to permit persons to whom the Software is_x000D_
furnished to do so, subject to the following conditions:_x000D_
The above copyright notice and this permission notice shall be included in all_x000D_
copies or substantial portions of the Software._x000D_
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR_x000D_
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,_x000D_
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE_x000D_
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER_x000D_
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,_x000D_
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE_x000D_
SOFTWARE._x000D_
*/_x000D_
_x000D_
/*_x000D_
// This constant can also be computed with the following algorithm:_x000D_
const base64abc = [],_x000D_
A = "A".charCodeAt(0),_x000D_
a = "a".charCodeAt(0),_x000D_
n = "0".charCodeAt(0);_x000D_
for (let i = 0; i < 26; ++i) {_x000D_
base64abc.push(String.fromCharCode(A + i));_x000D_
}_x000D_
for (let i = 0; i < 26; ++i) {_x000D_
base64abc.push(String.fromCharCode(a + i));_x000D_
}_x000D_
for (let i = 0; i < 10; ++i) {_x000D_
base64abc.push(String.fromCharCode(n + i));_x000D_
}_x000D_
base64abc.push("+");_x000D_
base64abc.push("/");_x000D_
*/_x000D_
const base64abc = [_x000D_
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",_x000D_
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",_x000D_
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",_x000D_
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",_x000D_
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"_x000D_
];_x000D_
_x000D_
/*_x000D_
// This constant can also be computed with the following algorithm:_x000D_
const l = 256, base64codes = new Uint8Array(l);_x000D_
for (let i = 0; i < l; ++i) {_x000D_
base64codes[i] = 255; // invalid character_x000D_
}_x000D_
base64abc.forEach((char, index) => {_x000D_
base64codes[char.charCodeAt(0)] = index;_x000D_
});_x000D_
base64codes["=".charCodeAt(0)] = 0; // ignored anyway, so we just need to prevent an error_x000D_
*/_x000D_
const base64codes = [_x000D_
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,_x000D_
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,_x000D_
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,_x000D_
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255,_x000D_
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,_x000D_
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,_x000D_
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,_x000D_
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51_x000D_
];_x000D_
_x000D_
function getBase64Code(charCode) {_x000D_
if (charCode >= base64codes.length) {_x000D_
throw new Error("Unable to parse base64 string.");_x000D_
}_x000D_
const code = base64codes[charCode];_x000D_
if (code === 255) {_x000D_
throw new Error("Unable to parse base64 string.");_x000D_
}_x000D_
return code;_x000D_
}_x000D_
_x000D_
export function bytesToBase64(bytes) {_x000D_
let result = '', i, l = bytes.length;_x000D_
for (i = 2; i < l; i += 3) {_x000D_
result += base64abc[bytes[i - 2] >> 2];_x000D_
result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];_x000D_
result += base64abc[((bytes[i - 1] & 0x0F) << 2) | (bytes[i] >> 6)];_x000D_
result += base64abc[bytes[i] & 0x3F];_x000D_
}_x000D_
if (i === l + 1) { // 1 octet yet to write_x000D_
result += base64abc[bytes[i - 2] >> 2];_x000D_
result += base64abc[(bytes[i - 2] & 0x03) << 4];_x000D_
result += "==";_x000D_
}_x000D_
if (i === l) { // 2 octets yet to write_x000D_
result += base64abc[bytes[i - 2] >> 2];_x000D_
result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];_x000D_
result += base64abc[(bytes[i - 1] & 0x0F) << 2];_x000D_
result += "=";_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
export function base64ToBytes(str) {_x000D_
if (str.length % 4 !== 0) {_x000D_
throw new Error("Unable to parse base64 string.");_x000D_
}_x000D_
const index = str.indexOf("=");_x000D_
if (index !== -1 && index < str.length - 2) {_x000D_
throw new Error("Unable to parse base64 string.");_x000D_
}_x000D_
let missingOctets = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0,_x000D_
n = str.length,_x000D_
result = new Uint8Array(3 * (n / 4)),_x000D_
buffer;_x000D_
for (let i = 0, j = 0; i < n; i += 4, j += 3) {_x000D_
buffer =_x000D_
getBase64Code(str.charCodeAt(i)) << 18 |_x000D_
getBase64Code(str.charCodeAt(i + 1)) << 12 |_x000D_
getBase64Code(str.charCodeAt(i + 2)) << 6 |_x000D_
getBase64Code(str.charCodeAt(i + 3));_x000D_
result[j] = buffer >> 16;_x000D_
result[j + 1] = (buffer >> 8) & 0xFF;_x000D_
result[j + 2] = buffer & 0xFF;_x000D_
}_x000D_
return result.subarray(0, result.length - missingOctets);_x000D_
}_x000D_
_x000D_
export function base64encode(str, encoder = new TextEncoder()) {_x000D_
return bytesToBase64(encoder.encode(str));_x000D_
}_x000D_
_x000D_
export function base64decode(str, decoder = new TextDecoder()) {_x000D_
return decoder.decode(base64ToBytes(str));_x000D_
}
_x000D_
When you call loadTeachers()
on DOMReady the context of this
will not be the #CourseSelect
element.
You can fix this by triggering a change()
event on the #CourseSelect
element on load of the DOM:
$("#CourseSelect").change(loadTeachers).change(); // or .trigger('change');
Alternatively can use $.proxy
to change the context the function runs under:
$("#CourseSelect").change(loadTeachers);
$.proxy(loadTeachers, $('#CourseSelect'))();
Or the vanilla JS equivalent of the above, bind()
:
$("#CourseSelect").change(loadTeachers);
loadTeachers.bind($('#CourseSelect'));
This would work just fine, set the height to desired pixel
#inner-right{
height: 100px;
overflow:auto;
}
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
For different layouts like ConstraintLayout
and others, they have their own LayoutParams
, like so:
pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
or
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
-(IBAction)SegmentbtnCLK:(id)sender
{ [self sortArryofDictionary];
[self.objtable reloadData];}
-(void)sortArryofDictionary
{ NSSortDescriptor *sorter;
switch (sortcontrol.selectedSegmentIndex)
{case 0:
sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];
break;
case 1:
sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES];
default:
break; }
NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil];
[arr sortUsingDescriptors:sortdiscriptor];
}
I had the same, eclipse polluted files even with one line change. Solution: Eclipse git settings -> Add Entry: Key: core.autocrlf Values: true
move
struct body bodies[n];
to after
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
Rest all looks fine.
I had the same problem and error, I tried changing the ports for http port from 80 to 81 and ssl port from 443 to 444 but still received the same error so I reverted the ports to default and ran setup_xampp.bat which solve the problem in seconds.
In ruby 1.9.3 there is a chainable method called with_index
which can be chained to map.
For example:
array.map.with_index { |item, index| ... }
PreparedStatement ps=con.prepareStatement("select * from stud");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
This code worked for me:
$(function(){
$('input:radio').change(function(){
alert('changed');
});
});
According to the curl man page:
You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.
So the simplest and most efficient (curl will send them all down a single TCP connection [those to the same origin]) approach would be put them all on a single invocation of curl e.g.:
curl http://example.com/?update_=1 http://example.com/?update_=2
Latest news:
Google announce that with Android N and Android Studio 2.1+, platform will support Java 8. Also stable version of studio 2.1 was released.
At last we can use lambda expressions. No more list filter in for loop. Horeeey.
exit code 139 (people say this means memory fragmentation)
No, it means that your program died with signal 11
(SIGSEGV
on Linux and most other UNIXes), also known as segmentation fault
.
Could anybody tell me why the run fails but debug doesn't?
Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).
Your first step should be running this program under Valgrind, and fixing all errors it reports.
If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out
) and then analyze that core dump with GDB: gdb ./a.out core
; then use where
command.
Without jQuery : DEMO
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
AAA
</div>
</div>
Disable swipe progmatically by-
final View touchView = findViewById(R.id.Pager);
touchView.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
and use this to swipe manually
touchView.setCurrentItem(int index);
So you have this code:
<a class="dropdown-toggle" data-toggle="dropdown">Show menu</a>
<ul class="dropdown-menu" role="menu">
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
Normally it works on click event, and you want it work on hover event. This is very simple, just use this javascript/jquery code:
$(document).ready(function () {
$('.dropdown-toggle').mouseover(function() {
$('.dropdown-menu').show();
})
$('.dropdown-toggle').mouseout(function() {
t = setTimeout(function() {
$('.dropdown-menu').hide();
}, 100);
$('.dropdown-menu').on('mouseenter', function() {
$('.dropdown-menu').show();
clearTimeout(t);
}).on('mouseleave', function() {
$('.dropdown-menu').hide();
})
})
})
This works very well and here is the explanation: we have a button, and a menu. When we hover the button we display the menu, and when we mouseout of the button we hide the menu after 100ms. If you wonder why i use that, is because you need time to drag the cursor from the button over the menu. When you are on the menu, the time is reset and you can stay there as many time as you want. When you exit the menu, we will hide the menu instantly without any timeout.
I've used this code in many projects, if you encounter any problem using it, feel free to ask me questions.
date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
Following on from LachlanB's answer, if your ApiController doesn't sit within a particular directory (like /api) you can instead test the request using RouteTable.Routes.GetRouteData, for example:
protected void Application_PostAuthorizeRequest()
{
// WebApi SessionState
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
if (routeData != null && routeData.RouteHandler is HttpControllerRouteHandler)
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
Data in XML format are rarely organized in a way that would allow the xmlToDataFrame
function to work. You're better off extracting everything in lists and then binding the lists together in a data frame:
require(XML)
data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
xml_data <- xmlToList(data)
In the case of your example data, getting location and start time is fairly straightforward:
location <- as.list(xml_data[["data"]][["location"]][["point"]])
start_time <- unlist(xml_data[["data"]][["time-layout"]][
names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"])
Temperature data is a bit more complicated. First you need to get to the node that contains the temperature lists. Then you need extract both the lists, look within each one, and pick the one that has "hourly" as one of its values. Then you need to select only that list but only keep the values that have the "value" label:
temps <- xml_data[["data"]][["parameters"]]
temps <- temps[names(temps) == "temperature"]
temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]
temps <- unlist(temps[[1]][sapply(temps, names) == "value"])
out <- data.frame(
as.list(location),
"start_valid_time" = start_time,
"hourly_temperature" = temps)
head(out)
latitude longitude start_valid_time hourly_temperature
1 29.81 -82.42 2013-06-19T16:00:00-04:00 91
2 29.81 -82.42 2013-06-19T17:00:00-04:00 90
3 29.81 -82.42 2013-06-19T18:00:00-04:00 89
4 29.81 -82.42 2013-06-19T19:00:00-04:00 85
5 29.81 -82.42 2013-06-19T20:00:00-04:00 83
6 29.81 -82.42 2013-06-19T21:00:00-04:00 80
and doesnt give any clues
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
Don't ignore the exception, it contains information about what went wrong and why.
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.
In your debugger, place a breakpoint inside the catch
block and examine the details of the exception. You'll find it contains a lot of information.
I try to figure out how to get a better result with pure JS and i get something this:
DEMO: https://jsfiddle.net/f5r3emjt/1/
const tbody = document.getElementById("tbody");
let rowSelected;
tbody.onclick = (e) => {
for (let i = 0; i < e.path.length; ++i) {
if (e.path[i].tagName == "TR") {
selectRow(e.path[i]);
break;
}
}
};
function selectRow(r) {
if (rowSelected !== undefined) rowSelected.style.backgroundColor = "white";
rowSelected = r;
rowSelected.style.backgroundColor = "dodgerblue";
}
And now you can use the variable rowSelected in other function like you want or call another function after set the style
My favorite:
df = df.iloc[0:0]
But be aware df.index.max() will be nan. To add items I use:
df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data
Just use two Listboxes, one for header and other for data
for headers - set RowSource property to top row e.g. Incidents!Q4:S4
for data - set Row Source Property to Incidents!Q5:S10
Unless you have to write formulas or formatting you should consider writing out a .csv file. Infinitely simpler, infinitely faster, and Excel will do the conversion to .xls or .xlsx automatically and correctly by definition.
The best solution ever.
Array.prototype.checkIfArrayIsUnique = function() {
this.sort();
for ( var i = 1; i < this.length; i++ ){
if(this[i-1] == this[i])
return false;
}
return true;
}
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
You can give https://github.com/ersiner/osx-env-sync a try. It handles both command line and GUI apps from a single source and works withe the latest version of OS X (Yosemite).
You can use path substitutions and other shell tricks since what you write is regular bash script to be sourced by bash in the first place. No restrictions.. (Check osx-env-sync documentation and you'll understand how it achieves this.)
I answered a similar question here where you'll find more.
An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with
npm install connect-timeout
and in the code it has to be (Edited as per comment, how to include it in the code)
var timeout = require('connect-timeout');
app.use(timeout('100s'));
I faced a similar issue on Xcode 12 with macOS 10.15 and cocoapods. Just make sure that the xcode-select command points to the SDK you want to build against. It should build without issues afterwards.
This answer covers:
There are a number of ways to retrieve data from multiple tables in a database. In this answer, I will be using ANSI-92 join syntax. This may be different to a number of other tutorials out there which use the older ANSI-89 syntax (and if you are used to 89, may seem much less intuitive - but all I can say is to try it) as it is much easier to understand when the queries start getting more complex. Why use it? Is there a performance gain? The short answer is no, but it is easier to read once you get used to it. It is easier to read queries written by other folks using this syntax.
I am also going to use the concept of a small caryard which has a database to keep track of what cars it has available. The owner has hired you as his IT Computer guy and expects you to be able to drop him the data that he asks for at the drop of a hat.
I have made a number of lookup tables that will be used by the final table. This will give us a reasonable model to work from. To start off, I will be running my queries against an example database that has the following structure. I will try to think of common mistakes that are made when starting out and explain what goes wrong with them - as well as of course showing how to correct them.
The first table is simply a color listing so that we know what colors we have in the car yard.
mysql> create table colors(id int(3) not null auto_increment primary key,
-> color varchar(15), paint varchar(10));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| color | varchar(15) | YES | | NULL | |
| paint | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
mysql> insert into colors (color, paint) values ('Red', 'Metallic'),
-> ('Green', 'Gloss'), ('Blue', 'Metallic'),
-> ('White' 'Gloss'), ('Black' 'Gloss');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from colors;
+----+-------+----------+
| id | color | paint |
+----+-------+----------+
| 1 | Red | Metallic |
| 2 | Green | Gloss |
| 3 | Blue | Metallic |
| 4 | White | Gloss |
| 5 | Black | Gloss |
+----+-------+----------+
5 rows in set (0.00 sec)
The brands table identifies the different brands of the cars out caryard could possibly sell.
mysql> create table brands (id int(3) not null auto_increment primary key,
-> brand varchar(15));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from brands;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| brand | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)
mysql> insert into brands (brand) values ('Ford'), ('Toyota'),
-> ('Nissan'), ('Smart'), ('BMW');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from brands;
+----+--------+
| id | brand |
+----+--------+
| 1 | Ford |
| 2 | Toyota |
| 3 | Nissan |
| 4 | Smart |
| 5 | BMW |
+----+--------+
5 rows in set (0.00 sec)
The model table will cover off different types of cars, it is going to be simpler for this to use different car types rather than actual car models.
mysql> create table models (id int(3) not null auto_increment primary key,
-> model varchar(15));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from models;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| model | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> insert into models (model) values ('Sports'), ('Sedan'), ('4WD'), ('Luxury');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from models;
+----+--------+
| id | model |
+----+--------+
| 1 | Sports |
| 2 | Sedan |
| 3 | 4WD |
| 4 | Luxury |
+----+--------+
4 rows in set (0.00 sec)
And finally, to tie up all these other tables, the table that ties everything together. The ID field is actually the unique lot number used to identify cars.
mysql> create table cars (id int(3) not null auto_increment primary key,
-> color int(3), brand int(3), model int(3));
Query OK, 0 rows affected (0.01 sec)
mysql> show columns from cars;
+-------+--------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------+------+-----+---------+----------------+
| id | int(3) | NO | PRI | NULL | auto_increment |
| color | int(3) | YES | | NULL | |
| brand | int(3) | YES | | NULL | |
| model | int(3) | YES | | NULL | |
+-------+--------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> insert into cars (color, brand, model) values (1,2,1), (3,1,2), (5,3,1),
-> (4,4,2), (2,2,3), (3,5,4), (4,1,3), (2,2,1), (5,2,3), (4,5,1);
Query OK, 10 rows affected (0.00 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> select * from cars;
+----+-------+-------+-------+
| id | color | brand | model |
+----+-------+-------+-------+
| 1 | 1 | 2 | 1 |
| 2 | 3 | 1 | 2 |
| 3 | 5 | 3 | 1 |
| 4 | 4 | 4 | 2 |
| 5 | 2 | 2 | 3 |
| 6 | 3 | 5 | 4 |
| 7 | 4 | 1 | 3 |
| 8 | 2 | 2 | 1 |
| 9 | 5 | 2 | 3 |
| 10 | 4 | 5 | 1 |
+----+-------+-------+-------+
10 rows in set (0.00 sec)
This will give us enough data (I hope) to cover off the examples below of different types of joins and also give enough data to make them worthwhile.
So getting into the grit of it, the boss wants to know The IDs of all the sports cars he has.
This is a simple two table join. We have a table that identifies the model and the table with the available stock in it. As you can see, the data in the model
column of the cars
table relates to the models
column of the cars
table we have. Now, we know that the models table has an ID of 1
for Sports
so lets write the join.
select
ID,
model
from
cars
join models
on model=ID
So this query looks good right? We have identified the two tables and contain the information we need and use a join that correctly identifies what columns to join on.
ERROR 1052 (23000): Column 'ID' in field list is ambiguous
Oh noes! An error in our first query! Yes, and it is a plum. You see, the query has indeed got the right columns, but some of them exist in both tables, so the database gets confused about what actual column we mean and where. There are two solutions to solve this. The first is nice and simple, we can use tableName.columnName
to tell the database exactly what we mean, like this:
select
cars.ID,
models.model
from
cars
join models
on cars.model=models.ID
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 3 | Sports |
| 8 | Sports |
| 10 | Sports |
| 2 | Sedan |
| 4 | Sedan |
| 5 | 4WD |
| 7 | 4WD |
| 9 | 4WD |
| 6 | Luxury |
+----+--------+
10 rows in set (0.00 sec)
The other is probably more often used and is called table aliasing. The tables in this example have nice and short simple names, but typing out something like KPI_DAILY_SALES_BY_DEPARTMENT
would probably get old quickly, so a simple way is to nickname the table like this:
select
a.ID,
b.model
from
cars a
join models b
on a.model=b.ID
Now, back to the request. As you can see we have the information we need, but we also have information that wasn't asked for, so we need to include a where clause in the statement to only get the Sports cars as was asked. As I prefer the table alias method rather than using the table names over and over, I will stick to it from this point onwards.
Clearly, we need to add a where clause to our query. We can identify Sports cars either by ID=1
or model='Sports'
. As the ID is indexed and the primary key (and it happens to be less typing), lets use that in our query.
select
a.ID,
b.model
from
cars a
join models b
on a.model=b.ID
where
b.ID=1
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 3 | Sports |
| 8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)
Bingo! The boss is happy. Of course, being a boss and never being happy with what he asked for, he looks at the information, then says I want the colors as well.
Okay, so we have a good part of our query already written, but we need to use a third table which is colors. Now, our main information table cars
stores the car color ID and this links back to the colors ID column. So, in a similar manner to the original, we can join a third table:
select
a.ID,
b.model
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
where
b.ID=1
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 3 | Sports |
| 8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)
Damn, although the table was correctly joined and the related columns were linked, we forgot to pull in the actual information from the new table that we just linked.
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
where
b.ID=1
+----+--------+-------+
| ID | model | color |
+----+--------+-------+
| 1 | Sports | Red |
| 8 | Sports | Green |
| 10 | Sports | White |
| 3 | Sports | Black |
+----+--------+-------+
4 rows in set (0.00 sec)
Right, that's the boss off our back for a moment. Now, to explain some of this in a little more detail. As you can see, the from
clause in our statement links our main table (I often use a table that contains information rather than a lookup or dimension table. The query would work just as well with the tables all switched around, but make less sense when we come back to this query to read it in a few months time, so it is often best to try to write a query that will be nice and easy to understand - lay it out intuitively, use nice indenting so that everything is as clear as it can be. If you go on to teach others, try to instill these characteristics in their queries - especially if you will be troubleshooting them.
It is entirely possible to keep linking more and more tables in this manner.
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
While I forgot to include a table where we might want to join more than one column in the join
statement, here is an example. If the models
table had brand-specific models and therefore also had a column called brand
which linked back to the brands
table on the ID
field, it could be done as this:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
and b.brand=d.ID
where
b.ID=1
You can see, the query above not only links the joined tables to the main cars
table, but also specifies joins between the already joined tables. If this wasn't done, the result is called a cartesian join - which is dba speak for bad. A cartesian join is one where rows are returned because the information doesn't tell the database how to limit the results, so the query returns all the rows that fit the criteria.
So, to give an example of a cartesian join, lets run the following query:
select
a.ID,
b.model
from
cars a
join models b
+----+--------+
| ID | model |
+----+--------+
| 1 | Sports |
| 1 | Sedan |
| 1 | 4WD |
| 1 | Luxury |
| 2 | Sports |
| 2 | Sedan |
| 2 | 4WD |
| 2 | Luxury |
| 3 | Sports |
| 3 | Sedan |
| 3 | 4WD |
| 3 | Luxury |
| 4 | Sports |
| 4 | Sedan |
| 4 | 4WD |
| 4 | Luxury |
| 5 | Sports |
| 5 | Sedan |
| 5 | 4WD |
| 5 | Luxury |
| 6 | Sports |
| 6 | Sedan |
| 6 | 4WD |
| 6 | Luxury |
| 7 | Sports |
| 7 | Sedan |
| 7 | 4WD |
| 7 | Luxury |
| 8 | Sports |
| 8 | Sedan |
| 8 | 4WD |
| 8 | Luxury |
| 9 | Sports |
| 9 | Sedan |
| 9 | 4WD |
| 9 | Luxury |
| 10 | Sports |
| 10 | Sedan |
| 10 | 4WD |
| 10 | Luxury |
+----+--------+
40 rows in set (0.00 sec)
Good god, that's ugly. However, as far as the database is concerned, it is exactly what was asked for. In the query, we asked for for the ID
from cars
and the model
from models
. However, because we didn't specify how to join the tables, the database has matched every row from the first table with every row from the second table.
Okay, so the boss is back, and he wants more information again. I want the same list, but also include 4WDs in it.
This however, gives us a great excuse to look at two different ways to accomplish this. We could add another condition to the where clause like this:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
or b.ID=3
While the above will work perfectly well, lets look at it differently, this is a great excuse to show how a union
query will work.
We know that the following will return all the Sports cars:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
And the following would return all the 4WDs:
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=3
So by adding a union all
clause between them, the results of the second query will be appended to the results of the first query.
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=1
union all
select
a.ID,
b.model,
c.color
from
cars a
join models b
on a.model=b.ID
join colors c
on a.color=c.ID
join brands d
on a.brand=d.ID
where
b.ID=3
+----+--------+-------+
| ID | model | color |
+----+--------+-------+
| 1 | Sports | Red |
| 8 | Sports | Green |
| 10 | Sports | White |
| 3 | Sports | Black |
| 5 | 4WD | Green |
| 7 | 4WD | White |
| 9 | 4WD | Black |
+----+--------+-------+
7 rows in set (0.00 sec)
As you can see, the results of the first query are returned first, followed by the results of the second query.
In this example, it would of course have been much easier to simply use the first query, but union
queries can be great for specific cases. They are a great way to return specific results from tables from tables that aren't easily joined together - or for that matter completely unrelated tables. There are a few rules to follow however.
Now, you might be wondering what the difference is between using union
and union all
. A union
query will remove duplicates, while a union all
will not. This does mean that there is a small performance hit when using union
over union all
but the results may be worth it - I won't speculate on that sort of thing in this though.
On this note, it might be worth noting some additional notes here.
order by
but you can't use the alias anymore. In the query above, appending an order by a.ID
would result in an error - as far as the results are concerned, the column is called ID
rather than a.ID
- even though the same alias has been used in both queries.order by
statement, and it must be as the last statement.For the next examples, I am adding a few extra rows to our tables.
I have added Holden
to the brands table.
I have also added a row into cars
that has the color
value of 12
- which has no reference in the colors table.
Okay, the boss is back again, barking requests out - *I want a count of each brand we carry and the number of cars in it!` - Typical, we just get to an interesting section of our discussion and the boss wants more work.
Rightyo, so the first thing we need to do is get a complete listing of possible brands.
select
a.brand
from
brands a
+--------+
| brand |
+--------+
| Ford |
| Toyota |
| Nissan |
| Smart |
| BMW |
| Holden |
+--------+
6 rows in set (0.00 sec)
Now, when we join this to our cars table we get the following result:
select
a.brand
from
brands a
join cars b
on a.ID=b.brand
group by
a.brand
+--------+
| brand |
+--------+
| BMW |
| Ford |
| Nissan |
| Smart |
| Toyota |
+--------+
5 rows in set (0.00 sec)
Which is of course a problem - we aren't seeing any mention of the lovely Holden
brand I added.
This is because a join looks for matching rows in both tables. As there is no data in cars that is of type Holden
it isn't returned. This is where we can use an outer
join. This will return all the results from one table whether they are matched in the other table or not:
select
a.brand
from
brands a
left outer join cars b
on a.ID=b.brand
group by
a.brand
+--------+
| brand |
+--------+
| BMW |
| Ford |
| Holden |
| Nissan |
| Smart |
| Toyota |
+--------+
6 rows in set (0.00 sec)
Now that we have that, we can add a lovely aggregate function to get a count and get the boss off our backs for a moment.
select
a.brand,
count(b.id) as countOfBrand
from
brands a
left outer join cars b
on a.ID=b.brand
group by
a.brand
+--------+--------------+
| brand | countOfBrand |
+--------+--------------+
| BMW | 2 |
| Ford | 2 |
| Holden | 0 |
| Nissan | 1 |
| Smart | 1 |
| Toyota | 5 |
+--------+--------------+
6 rows in set (0.00 sec)
And with that, away the boss skulks.
Now, to explain this in some more detail, outer joins can be of the left
or right
type. The Left or Right defines which table is fully included. A left outer join
will include all the rows from the table on the left, while (you guessed it) a right outer join
brings all the results from the table on the right into the results.
Some databases will allow a full outer join
which will bring back results (whether matched or not) from both tables, but this isn't supported in all databases.
Now, I probably figure at this point in time, you are wondering whether or not you can merge join types in a query - and the answer is yes, you absolutely can.
select
b.brand,
c.color,
count(a.id) as countOfBrand
from
cars a
right outer join brands b
on b.ID=a.brand
join colors c
on a.color=c.ID
group by
a.brand,
c.color
+--------+-------+--------------+
| brand | color | countOfBrand |
+--------+-------+--------------+
| Ford | Blue | 1 |
| Ford | White | 1 |
| Toyota | Black | 1 |
| Toyota | Green | 2 |
| Toyota | Red | 1 |
| Nissan | Black | 1 |
| Smart | White | 1 |
| BMW | Blue | 1 |
| BMW | White | 1 |
+--------+-------+--------------+
9 rows in set (0.00 sec)
So, why is that not the results that were expected? It is because although we have selected the outer join from cars to brands, it wasn't specified in the join to colors - so that particular join will only bring back results that match in both tables.
Here is the query that would work to get the results that we expected:
select
a.brand,
c.color,
count(b.id) as countOfBrand
from
brands a
left outer join cars b
on a.ID=b.brand
left outer join colors c
on b.color=c.ID
group by
a.brand,
c.color
+--------+-------+--------------+
| brand | color | countOfBrand |
+--------+-------+--------------+
| BMW | Blue | 1 |
| BMW | White | 1 |
| Ford | Blue | 1 |
| Ford | White | 1 |
| Holden | NULL | 0 |
| Nissan | Black | 1 |
| Smart | White | 1 |
| Toyota | NULL | 1 |
| Toyota | Black | 1 |
| Toyota | Green | 2 |
| Toyota | Red | 1 |
+--------+-------+--------------+
11 rows in set (0.00 sec)
As we can see, we have two outer joins in the query and the results are coming through as expected.
Now, how about those other types of joins you ask? What about Intersections?
Well, not all databases support the intersection
but pretty much all databases will allow you to create an intersection through a join (or a well structured where statement at the least).
An Intersection is a type of join somewhat similar to a union
as described above - but the difference is that it only returns rows of data that are identical (and I do mean identical) between the various individual queries joined by the union. Only rows that are identical in every regard will be returned.
A simple example would be as such:
select
*
from
colors
where
ID>2
intersect
select
*
from
colors
where
id<4
While a normal union
query would return all the rows of the table (the first query returning anything over ID>2
and the second anything having ID<4
) which would result in a full set, an intersect query would only return the row matching id=3
as it meets both criteria.
Now, if your database doesn't support an intersect
query, the above can be easily accomlished with the following query:
select
a.ID,
a.color,
a.paint
from
colors a
join colors b
on a.ID=b.ID
where
a.ID>2
and b.ID<4
+----+-------+----------+
| ID | color | paint |
+----+-------+----------+
| 3 | Blue | Metallic |
+----+-------+----------+
1 row in set (0.00 sec)
If you wish to perform an intersection across two different tables using a database that doesn't inherently support an intersection query, you will need to create a join on every column of the tables.
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:
Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
startActivity(i);
In this statement replace ActivityName by Name of Class of Activity, this code resides in.
I have got inspiration from multiple sources on the internet to derive into the solution below. Wanted to take into account both some default value and to provide a way to compare each entry for a generic approach which this solves.
Usage: (giving value "Second")
var defaultItemValue = { id: -1, name: "Undefined" };
var containers: Container[] = [{ id: 1, name: "First" }, { id: 2, name: "Second" }];
GetContainer(2).name;
Implementation:
class Container {
id: number;
name: string;
}
public GetContainer(containerId: number): Container {
var comparator = (item: Container): boolean => {
return item.id == containerId;
};
return this.Get<Container>(this.containers, comparator, this.defaultItemValue);
}
private Get<T>(array: T[], comparator: (item: T) => boolean, defaultValue: T): T {
var found: T = null;
array.some(function(element, index) {
if (comparator(element)) {
found = element;
return true;
}
});
if (!found) {
found = defaultValue;
}
return found;
}
It is very convenient to use train_test_split
without performing reindexing after dividing to several sets and not writing some additional code. Best answer above does not mention that by separating two times using train_test_split
not changing partition sizes won`t give initially intended partition:
x_train, x_remain = train_test_split(x, test_size=(val_size + test_size))
Then the portion of validation and test sets in the x_remain change and could be counted as
new_test_size = np.around(test_size / (val_size + test_size), 2)
# To preserve (new_test_size + new_val_size) = 1.0
new_val_size = 1.0 - new_test_size
x_val, x_test = train_test_split(x_remain, test_size=new_test_size)
In this occasion all initial partitions are saved.
Try LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0). Best of all it's free!
Steps with version 4.35.1:
click 'Add Connection'
Click Next with 'Build data context automatically' and 'Default(LINQ to SQL)' selected.
Under 'Provider' choose 'SQL CE 4.0'.
Under 'Database' with 'Attach database file' selected, choose 'Browse' to select your .sdf file.
Click 'OK'.
Voila! It should show the tables in .sdf and be able to query it via right clicking the table or writing LINQ code in your favorite .NET language or even SQL. How cool is that?
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
You can use:
\\
That's ok, for example:
if (invName.substring(j,k).equals("\\")) {
copyf=invName.substring(0,j);
}
Explanation on practice. If you try to save your object, e.g.:
Set<Folder> folders = message.getFolders();
folders.remove(inputFolder);
folders.add(trashFolder);
message.setFiles(folders);
MESSAGESDAO.getMessageDAO().save(message);
you don't need to set updated object to a parent object:
message.setFiles(folders);
Simple save your parent object like:
Set<Folder> folders = message.getFolders();
folders.remove(inputFolder);
folders.add(trashFolder);
// Not set updated object here
MESSAGESDAO.getMessageDAO().save(message);
You can try with following command:
sudo service mongod start
You can try a rebase --interactive
session to amend your old commit (provided you did not already push those commits to another repo).
Sometimes the thing fixed in b.2. cannot be amended to the not-quite perfect commit it fixes, because that commit is buried deeply in a patch series.
That is exactly what interactive rebase is for: use it after plenty of "a"s and "b"s, by rearranging and editing commits, and squashing multiple commits into one.Start it with the last commit you want to retain as-is:
git rebase -i <after-this-commit>
An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit.
You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:
pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...
The oneline descriptions are purely for your pleasure; git rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.
By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.
The accepted answer resulted in errors for me when attempting REASSIGN OWNED BY or DROP OWNED BY. The following worked for me:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
DROP USER username;
The user may have privileges in other schemas, in which case you will have to run the appropriate REVOKE line with "public" replaced by the correct schema. To show all of the schemas and privilege types for a user, I edited the \dp command to make this query:
SELECT
n.nspname as "Schema",
CASE c.relkind
WHEN 'r' THEN 'table'
WHEN 'v' THEN 'view'
WHEN 'm' THEN 'materialized view'
WHEN 'S' THEN 'sequence'
WHEN 'f' THEN 'foreign table'
END as "Type"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.array_to_string(c.relacl, E'\n') LIKE '%username%';
I'm not sure which privilege types correspond to revoking on TABLES, SEQUENCES, or FUNCTIONS, but I think all of them fall under one of the three.
To make it a little clear :
If the username: abcdef and the old password : a123b456, new password: m987n654
alter user abcdef identified by m987n654 replace a123b456;
On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see here for the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers
. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.
In your case, you're trying to send an Authorization
header, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headers
header (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorization
in its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.
Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.
tl;dr - If you'd like to send Authorization
headers, your server had better be configured to allow it. Set your server up so it responds to an OPTIONS
request at that url with an Access-Control-Allow-Headers: Authorization
header.
I had a slightly different scenario, but this is the top Google result so I'll answer my issue too. I could run the tests but only about half of them actually ran, with no error output.
Eventually I debugged and stepped through all the tests, and came upon a Stack Overflow Error
when creating Test Instances of some models.
In the test instance methods, a child model created a parent and the parent created a child, which created an infinite loop. I removed the parent creation from the child, and now all my tests work!
I've the same problem, and the below solution exactly work for me....!
Edit eclipse.ini
file and remove these two lines:
--launcher.library
.%%..\eclipse\plugins\eclipse\plugins\org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120522-1813
Make sure make a separate copy of this file before any changing...:)
Since JDK 11:
String file = ...
Path path = Paths.get(file);
String content = Files.readString(path);
// Or readString(path, someCharset), if you need a Charset different from UTF-8
Finlay, I have faced same issue in my application. I have developed Phone Gap app for
android:minSdkVersion="7" & android:targetSdkVersion="18"
which is recent version of android platform.
I have found the issue using Google Docs
May be issue is that i have write some JS function which works on KEY-CODE
to validate only Alphabets & Number but key board has different key code specially for computer keyboard & Mobile keyboard. So that was my issue.
I am not sure whether my answer is correct or not and it might be possible that it could be smiler to above answer but i will try to list out some points which should be care while we are building the app.I hope you follow this to solve this kind of issue.
Use the android:minSdkVersion="?"
as per your requirement & android:targetSdkVersion="?"
should be latest in which your app will targeting. see more
Try to add only those permission which will be use in your application and remove all which are unnecessary .
Check out the supported screen by application
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true"/>
May be you have implement some costume code or costume widget which couldn't able to run in some device or tab late so before writing the long code first try to write some beta code and test it whether your code will run in all device or not.
And I hope Google will publish a tool which can validate your code before the upload the app and also says that due to some specific reason we are not allow to run your app in some device so we can easily solve it.
I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:
no peer certificate available No client certificate CA names sent
In my output there was also:
Protocol : TLSv1.3
I added -tls1_2
and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2
In my case I didn't needed start adb.exe. I only started the BlueStacks before android studio.
After that when I press "Run" in android studio, bluestacks is detected as a new emulator.
Regards.
Use IList<IWebElement>
instead of List<IWebElement>
.
For instance:
IList<IWebElement> options = elem.FindElements(By.TagName("option"));
foreach (IWebElement option in options)
{
Console.WriteLine(option.Text);
}
After generating ctags, you can also use the following in vim:
:tag <f_name>
Above will take you to function definition.
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
This also works fine .Simple and easy.see http://jsfiddle.net/uZc8w/570/
$('#myimage').removeAttr("click");
Is Perl easily available to you?
$ perl -n -e 'if ($. == 7) { print; exit(0); }'
Obviously substitute whatever number you want for 7.
The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.
Update to keep this answer fresh:
If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.
$(window).on('hashchange', function() {
//.. work ..
});
The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.
With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).
In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.
This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.
I faced the same issue because I was querying db for more than 1000 iterations. I have used try and finally in my code. But was still getting error.
To solve this I just logged into oracle db and ran below query:
ALTER SYSTEM SET open_cursors = 8000 SCOPE=BOTH;
And this solved my problem immediately.
Handy if you are already in the directory you want to add to PATH:
set PATH=%PATH%;%CD%
It works with the standard Windows cmd, but not in PowerShell.
For PowerShell, the %CD%
equivalent is [System.Environment]::CurrentDirectory
.
The difference is that Visibility.Hidden
hides the control, but reserves the space it occupies in the layout. So it renders whitespace instead of the control.
Visibilty.Collapsed
does not render the control and does not reserve the whitespace. The space the control would take is 'collapsed', hence the name.
The exact text from the MSDN:
Collapsed: Do not display the element, and do not reserve space for it in layout.
Hidden: Do not display the element, but reserve space for the element in layout.
Visible: Display the element.
See: http://msdn.microsoft.com/en-us/library/system.windows.visibility.aspx
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
I had a similar issue and none of the answers worked for me. Maybe someone finds my solution helpful. In case you do not mind submitting on button click, only attaching to click event setting UseSubmitBehavior="false"
may be worth trying.
Sometimes it is just how you export and import it. For this error message it could be, that the default keyword is missing.
export default SampleClass {}
Where you instantiate it:
import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();
Option 2, with curly braces:
export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();
There are only two options:
Find out by reading all rows (and then you might as well store them)
run a specialized SELECT COUNT(*) query beforehand.
Going twice through the DataReader loop is really expensive, you would have to re-execute the query.
And (thanks to Pete OHanlon) the second option is only concurrency-safe when you use a transaction with a Snapshot isolation level.
Since you want to end up storing all rows in memory anyway the only sensible option is to read all rows in a flexible storage (List<>
or DataTable
) and then copy the data to any format you want. The in-memory operation will always be much more efficient.
If the data is actually a factor
then you can use the levels()
function, e.g.
levels( data$product_code )
If it's not a factor, but it should be, you can convert it to factor first by using the factor()
function, e.g.
levels( factor( data$product_code ) )
Another option, as mentioned above, is the unique()
function:
unique( data$product_code )
The main difference between the two (when applied to a factor
) is that levels
will return a character vector in the order of levels, including any levels that are coded but do not occur. unique
will return a factor
in the order the values first appear, with any non-occurring levels omitted (though still included in levels
of the returned factor).
Just use the below code. It will shadow surround the entire DIV
-webkit-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
-moz-box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
box-shadow: -1px 1px 5px 9px rgba(0,0,0,0.75);
Hope this will work
for(int i=0;i<str.length();i++)
{
System.out.println(str.charAt(i));
}
I received this error in my code because I'd not run JSON.parse(result).
So my result was a string instead of an array of objects.
i.e. I got:
"[{},{}]"
instead of:
[{},{}]
import { Storage } from '@ionic/storage';
...
private static readonly SERVER = 'server';
...
getStorage(): Promise {
return this.storage.get(LoginService.SERVER);
}
...
this.getStorage()
.then((value) => {
let servers: Server[] = JSON.parse(value) as Server[];
}
);
SVN is one repo and lots of clients. Git is a repo with lots of client repos, each with a user. It's decentralised to a point where people can track their own edits locally without having to push things to an external server.
SVN is designed to be more central where Git is based on each user having their own Git repo and those repos push changes back up into a central one. For that reason, Git gives individuals better local version control.
Meanwhile you have the choice between TortoiseGit, GitExtensions (and if you host your "central" git-repository on github, their own client – GitHub for Windows).
If you're looking on getting out of SVN, you might want to evaluate Bazaar for a bit. It's one of the next generation of version control systems that have this distributed element. It isn't POSIX dependant like git so there are native Windows builds and it has some powerful open source brands backing it.
But you might not even need these sorts of features yet. Have a look at the features, advantages and disadvantages of the distributed VCSes. If you need more than SVN offers, consider one. If you don't, you might want to stick with SVN's (currently) superior desktop integration.
Much of the reason that it took > 48 hours to do your inserts is because of your indexes. It is incredibly faster to:
1 - Drop all indexes 2 - Do all inserts 3 - Create indexes again
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}