Above mentioned answers are correct but what if you are doing a heavy process after losing the focus from the relevant component. For that, I came with a solution with two flags where the focus out event process will only take place when losing the focus from relevant component only.
isFocusInsideComponent = false;
isComponentClicked = false;
@HostListener('click')
clickInside() {
this.isFocusInsideComponent = true;
this.isComponentClicked = true;
}
@HostListener('document:click')
clickout() {
if (!this.isFocusInsideComponent && this.isComponentClicked) {
// do the heavy process
this.isComponentClicked = false;
}
this.isFocusInsideComponent = false;
}
Hope this will help you. Correct me If have missed anything.
Code example is given on the author site's. You can use babelfish to translate the texts (Japanese to English).
As far as I understand Japanese, this zip inflate code is meant to decode ZIP data (streams) not ZIP archive.
I would use cron to run a script every minute, and make that script run your script four times with a 15-second sleep between runs.
(That assumes your script is quick to run - you could adjust the sleep times if not.)
That way, you get all the benefits of cron
as well as your 15 second run period.
Edit: See also @bmb's comment below.
Try this:
#yourElementId
{
background: url(yourImageLocation.jpg) no-repeat center center;
width: 100px;
height: 100px;
}
Keep in mind that width
and height
will only work if your DOM element has layout (a block displayed element, like a div
or an img
). If it is not (a span, for example), add display: block;
to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.
You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.
The ISO-8601 format for a DATETIME
when using only the date is: YYYYMMDD
(no dashes or antyhing!)
For a DATETIME
with the time portion, it's YYYY-MM-DDTHH:MM:SS
(with dashes, and a T
in the middle to separate date and time portions).
If you want to convert a string to a DATE
for SQL Server 2008 or newer, you can use YYYY-MM-DD
(with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.
So in your case, you should try:
declare @a datetime
declare @b datetime
set @a = '2012-04-06T12:23:45' -- 6th of April, 2012
set @b = '2012-08-06T21:10:12' -- 6th of August, 2012
exec LogProcedure 'AccountLog', N'test', @a, @b
Furthermore - your stored proc has problem, since you're concatenating together datetime
and string into a string, but you're not converting the datetime
to string first, and also, you're forgetting the close quotes in your statement after both dates.
So change this line here to this:
IF @DateFirst <> '' and @DateLast <> ''
SET @FinalSQL = @FinalSQL + ' OR CONVERT(Date, DateLog) >= ''' +
CONVERT(VARCHAR(50), @DateFirst, 126) + -- convert @DateFirst to string for concatenation!
''' AND CONVERT(Date, DateLog) <=''' + -- you need closing quotes after @DateFirst!
CONVERT(VARCHAR(50), @DateLast, 126) + '''' -- convert @DateLast to string and also: closing tags after that missing!
With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.
Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/
But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing
-rw-r--r--@
thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:
-rw-r--rw-@
This did it. The message disappeared.
Try this
div_x000D_
{_x000D_
width:100px;_x000D_
height:100px;_x000D_
background:red;_x000D_
transition: all 1s ease-in-out;_x000D_
-webkit-transition: all 1s ease-in-out;_x000D_
-moz-transition: all 1s ease-in-out;_x000D_
-o-transition: all 1s ease-in-out;_x000D_
-ms-transition: all 1s ease-in-out;_x000D_
position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
transform: translate(3em,0);_x000D_
-webkit-transform: translate(3em,0);_x000D_
-moz-transform: translate(3em,0);_x000D_
-o-transform: translate(3em,0);_x000D_
-ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:
function getHostname(href) {
if (typeof URL === 'object') {
// workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
var dummyNode = document.createElement('a');
dummyNode.href = href;
return dummyNode.hostname;
} else {
// Martin Konecny's solution
return new URL(href).hostname;
}
}
To check if one or more columns all exist, you can use set.issubset
, as in:
if set(['A','C']).issubset(df.columns):
df['sum'] = df['A'] + df['C']
As @brianpck points out in a comment, set([])
can alternatively be constructed with curly braces,
if {'A', 'C'}.issubset(df.columns):
See this question for a discussion of the curly-braces syntax.
Or, you can use a list comprehension, as in:
if all([item in df.columns for item in ['A','C']]):
If you need multiple modifications, like when using ant design, you can combine multiple functions like this:
const {
override,
removeModuleScopePlugin,
fixBabelImports,
} = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
removeModuleScopePlugin(),
);
Performance difference aside, using re.compile and using the compiled regular expression object to do match (whatever regular expression related operations) makes the semantics clearer to Python run-time.
I had some painful experience of debugging some simple code:
compare = lambda s, p: re.match(p, s)
and later I'd use compare in
[x for x in data if compare(patternPhrases, x[columnIndex])]
where patternPhrases
is supposed to be a variable containing regular expression string, x[columnIndex]
is a variable containing string.
I had trouble that patternPhrases
did not match some expected string!
But if I used the re.compile form:
compare = lambda s, p: p.match(s)
then in
[x for x in data if compare(patternPhrases, x[columnIndex])]
Python would have complained that "string does not have attribute of match", as by positional argument mapping in compare
, x[columnIndex]
is used as regular expression!, when I actually meant
compare = lambda p, s: p.match(s)
In my case, using re.compile is more explicit of the purpose of regular expression, when it's value is hidden to naked eyes, thus I could get more help from Python run-time checking.
So the moral of my lesson is that when the regular expression is not just literal string, then I should use re.compile to let Python to help me to assert my assumption.
You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.
These lines in your makefile,
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h
and this line in your .cpp file,
#include "StdCUtil/split.h"
are in conflict.
With your makefile in your source directory and with that -I
option you should be using #include "split.h"
in your source file, and your dependency should be ../StdCUtil/split.h
.
Another option:
INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/.. # Ugly!
DEPS = $(INC_DIR)/split.h
With this your #include
directive would remain as #include "StdCUtil/split.h"
.
Yet another option is to place your makefile in the parent directory:
root
|____Makefile
|
|___Core
| |____DBC.cpp
| |____Lock.cpp
| |____Trace.cpp
|
|___StdCUtil
|___split.h
With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core
and StdCUtil
directories. Object
, for example. With this, your makefile becomes:
INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.
DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.
all: $(OBJS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CC) $(CFLAGS) -c $< -o $@
$(OBJ_DIR)/Trace.o: $(DEPS)
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.
Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.
Then your HTML. I took the liberty to correct that too
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
<p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){ // here too, you put a space between it
$Name=$row['Name'];
$Username=$row['User_name'];
$Password=$row['User_password'];
}
?>
Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)
Anyway, welcome to Stack Overflow
Expanding on Dave's answer, you can set the contentMode
of the button's imageView
all in IB, without any code, using Runtime Attributes:
1
means UIViewContentModeScaleAspectFit
,2
would mean
UIViewContentModeScaleAspectFill
.This error message might possibly indicate something else.
In my case I defined another Docker-Image elsewhere from which the current Docker inherited its settings (docker-compos.yml
):
FROM my_own_image:latest
The error message I got:
qohelet$ docker-compose up
Building web
Step 1/22 : FROM my_own_image:latest
ERROR: Service 'web' failed to build: pull access denied for my_own_image, repository does not exist or may require 'docker login'
Due to a reinstall the previous Docker were gone and I couldn't build my docker using docker-compose up
with this command:
sudo docker build -t my_own_image:latest -f MyOwnImage.Dockerfile .
In your specific case you might have defined your own php-docker.
This should cover it:
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
countries.dispatchEvent(event); //we use countries as it's referred to by ID - but this could be any JS element var
This could be bound for example to a keypress event, so when the element has focus the user can type and it will expand automatically...
--Context--
modal.find("select").not("[readonly]").on("keypress", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
this.dispatchEvent(event);
});
I think the one of the easiest ways out would be to parse the string returned by URL.getQuery() as
public static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
return map;
}
You can use the map returned by this function to retrieve the value keying in the parameter name.
Just in addition to the above answers, for the question where and when you should call getLocationOnScreen
?
For any information that is related to the view
, will be available only after the view has been laid out(created) on the screen. So to get the location put your code inside view.post(Runnable)
which is called after view
has been laid out, like this:
view.post(new Runnable() {
@Override
public void run() {
// This code will run when view created and rendered on screen
// So as the answer to this question, you can put the code here
int[] location = new int[2];
myView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
}
});
Using 'DropDownList' for the 'DropDownStyle' property of the combo box doesn't work as it changes the look and feel of the combo box. I am using Visual Studio 2019 Community Edition.
Using 'e.Handled = True' also doesn't work either as it still allows user input. Using 'False' for the 'Enabled' property of the combo box also doesn't work too because it stops the user from being able to use the combo box.
All of the "solutions" that have been proposed above are complete rubbish. What really works is this following code which restricts user input to certain keys such as up / down (for navigating through the list of all available choices in the combo box), suppressing all other key inputs:-
Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles
ComboBox1.KeyDown
REM The following code is executed whenever the user has pressed
REM a key. Added on Wednesday 1st January 2020.
REM Determine what key the user has pressed. Added on Wednesday
REM 1st January 2020.
Select Case e.KeyCode
Case Keys.Down, Keys.Up
REM This section is for whenever the user has pressed either
REM the arrow down key or arrow up key. Added on Wednesday
REM 1st January 2020.
Case Else
REM This section is for whenever the user has pressed any
REM other key. Added on Wednesday 1st January 2020.
REM Cancelling the key that the user has pressed. Added on
REM Wednesday 1st January 2020.
e.SuppressKeyPress = True
End Select
End Sub
Hello+World
is how a browser will encode form data (application/x-www-form-urlencoded
) for a GET
request and this is the generally accepted form for the query part of a URI.
http://host/path/?message=Hello+World
If you sent this request to a Java servlet, the servlet would correctly decode the parameter value. Usually the only time there are issues here is if the encoding doesn't match.
Strictly speaking, there is no requirement in the HTTP or URI specs that the query part to be encoded using application/x-www-form-urlencoded
key-value pairs; the query part just needs to be in the form the web server accepts. In practice, this is unlikely to be an issue.
It would generally be incorrect to use this encoding for other parts of the URI (the path for example). In that case, you should use the encoding scheme as described in RFC 3986.
http://host/Hello%20World
More here.
The .cer and .crt file should be interchangable as far as importing them into a keystore.
Take a look at the contents of the .cer file. Erase anything before the -----BEGIN CERTIFICATE-----
line and after the -----END CERTIFICATE-----
line. You'll be left with the BEGIN/END lines with a bunch of Base64-encoded stuff between them.
-----BEGIN CERTIFICATE-----
MIIDQTCCAqqgAwIBAgIJALQea21f1bVjMA0GCSqGSIb3DQEBBQUAMIG1MQswCQYD
...
pfDACIDHTrwCk5OefMwArfEkSBo/
-----END CERTIFICATE-----
Then just import it into your keyfile using keytool.
keytool -import -alias myalias -keystore my.keystore -trustcacerts -file mycert.cer
I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.
Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:
import matplotlib.pyplot as plt
import numpy as np
import warnings
def fftPlot(sig, dt=None, plot=True):
# Here it's assumes analytic signal (real signal...) - so only half of the axis is required
if dt is None:
dt = 1
t = np.arange(0, sig.shape[-1])
xLabel = 'samples'
else:
t = np.arange(0, sig.shape[-1]) * dt
xLabel = 'freq [Hz]'
if sig.shape[0] % 2 != 0:
warnings.warn("signal preferred to be even in size, autoFixing it...")
t = t[0:-1]
sig = sig[0:-1]
sigFFT = np.fft.fft(sig) / t.shape[0] # Divided by size t for coherent magnitude
freq = np.fft.fftfreq(t.shape[0], d=dt)
# Plot analytic signal - right half of frequence axis needed only...
firstNegInd = np.argmax(freq < 0)
freqAxisPos = freq[0:firstNegInd]
sigFFTPos = 2 * sigFFT[0:firstNegInd] # *2 because of magnitude of analytic signal
if plot:
plt.figure()
plt.plot(freqAxisPos, np.abs(sigFFTPos))
plt.xlabel(xLabel)
plt.ylabel('mag')
plt.title('Analytic FFT plot')
plt.show()
return sigFFTPos, freqAxisPos
if __name__ == "__main__":
dt = 1 / 1000
# Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
f0 = 200 # [Hz]
t = np.arange(0, 1 + dt, dt)
sig = 1 * np.sin(2 * np.pi * f0 * t) + \
10 * np.sin(2 * np.pi * f0 / 2 * t) + \
3 * np.sin(2 * np.pi * f0 / 4 * t) +\
7.5 * np.sin(2 * np.pi * f0 / 5 * t)
# Result in frequencies
fftPlot(sig, dt=dt)
# Result in samples (if the frequencies axis is unknown)
fftPlot(sig)
Resolved like this:
# chown -R <user>: node_modules
When I align elements in center I use the bootstrap class text-center:
<div class="text-center">Centered content goes here</div>
You do not need {{}}
in when conditions. What you are searching for is:
- fail: msg="unsupported version"
when: version not in acceptable_versions
There are couple of little visual studio extensions for this purpose:
In case of TFS 2012, looks like there is no need for 'Go offline' extensions. I read something about a new feature called local workspace for the similar purpose.
Alternatively I had good success with Git-TF. All the goodness of git and when you are ready, you can push it to TFS.
If you want to validate email then use input with type="email" instead of type="text". AngularJS has email validation out of the box, so no need to use ng-pattern for this.
Here is the example from original documentation:
<script>
function Ctrl($scope) {
$scope.text = '[email protected]';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<br/>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<br>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
For more details read this doc: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
Live example: http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
If you are not satisfied with built-in email validator and you want to use your custom RegExp pattern validation then ng-pattern directive can be applied and according to the documentation the error message can be displayed like this:
The validator sets the pattern error key if the ngModel.$viewValue does not match a RegExp
<script>
function Ctrl($scope) {
$scope.text = '[email protected]';
$scope.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required>
<br/><br/>
<span class="error" ng-show="myForm.input.$error.required">
Required!
</span><br/>
<span class="error" ng-show="myForm.input.$error.pattern">
Not valid email!
</span>
<br><br>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/>
</form>
Plunker: https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview
One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:
def conf_decorator(dec):
"""Enables behavior like this:
@threaded
def f(): ...
or
@threaded(thread=KThread)
def f(): ...
(assuming threaded is wrapped with this function.)
Sends any accumulated kwargs to threaded.
"""
c_kwargs = {}
@wraps(dec)
def wrapped(f=None, **kwargs):
if f:
r = dec(f, **c_kwargs)
c_kwargs = {}
return r
else:
c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment
return wrapped
return wrapped
The solution is to replace c_kwargs = {}
with c_kwargs.clear()
If someone thinks up a more practical example, feel free to edit this post.
we can create nested cte.please see the below cte in example
;with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from [HumanResources].[Department]
)
select * from cte_data,cte_data1
I was looking for a more direct implementation like avijendr suggested.
I had a little trouble with his/her syntax, but I got this to work:
if ($('.user-forms input[id*="chkPrint"]:not(:checked)').length > 0)
In my case, I had a table with a class user-forms
, and I was checking if any of the checkboxes that had the string checkPrint
in their id
were unchecked.
What worked for me was CurrentCellDirtyStateChanged
in combination with datagridView1.EndEdit()
private void dataGridView1_CurrentCellDirtyStateChanged( object sender, EventArgs e ) {
if ( dataGridView1.CurrentCell is DataGridViewCheckBoxCell ) {
DataGridViewCheckBoxCell cb = (DataGridViewCheckBoxCell)dataGridView1.CurrentCell;
if ( (byte)cb.Value == 1 ) {
dataGridView1.CurrentRow.Cells["time_loadedCol"].Value = DateTime.Now.ToString();
}
}
dataGridView1.EndEdit();
}
As of today 11th April 2020, this is easily possible with backdrop-filter
CSS property which is now a stable feature in Chrome, Safari & Edge.
I wanted this in our Hybrid mobile app so also available in Android/Chrome Webview & Safari WebView.
Simply add the CSS property:
.my-class {
backdrop-filter: blur(30px);
background: transparent; // Make sure there is not backgorund
}
See it working in this pen or try the demo:
#main-wrapper {_x000D_
width: 300px;_x000D_
height: 300px;_x000D_
background: url("https://i.picsum.photos/id/1001/500/500.jpg") no-repeat center;_x000D_
background-size: cover;_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.my-effect {_x000D_
position: absolute;_x000D_
top: 300px;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
font-size: 22px;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
color: black;_x000D_
-webkit-backdrop-filter: blur(15px);_x000D_
backdrop-filter: blur(15px);_x000D_
transition: top 700ms;_x000D_
}_x000D_
_x000D_
#main-wrapper:hover .my-effect {_x000D_
top: 0;_x000D_
}
_x000D_
<h4>Hover over the image to see the effect</h4>_x000D_
_x000D_
<div id="main-wrapper">_x000D_
<div class="my-effect">_x000D_
Glossy effect worked!_x000D_
</div>_x000D_
</div>
_x000D_
Let's take an example of McDonald's app because it's quite colourful. I took its screenshot and added as the background in the body
of my app.
I wanted to show a text on top of it with the glossy effect. Using backdrop-filter: blur(20px);
on the overlay above it, I was able to see this:
SQL JOINS difference:
Very simple to remember :
INNER JOIN
only show records common to both tables.
OUTER JOIN
all the content of the both tables are merged together either they are matched or not.
LEFT JOIN
is same as LEFT OUTER JOIN
- (Select records from the first (left-most) table with matching right table records.)
RIGHT JOIN
is same as RIGHT OUTER JOIN
- (Select records from the second (right-most) table with matching left table records.)
You actually can use sed to do it, provided it is GNU sed.
... | sed 's/match/command \0/e'
How it works:
Try this:
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down'
Most probably the issue of ImagePullBackOff is due to either the image not being present or issue with the pod YAML file.
What I will do is this
kubectl get pod -n $namespace $POD_NAME --export > pod.yaml | kubectl -f apply -
I would also see the pod.yaml to see the why the earlier pod didn't work
If you want to make the first item unselectable, try this:
DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");
Set permission to your current user by running the command
$ sudo chown -R <username> .git/
Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.
setup.py
filepath_to/project_name/
setup.py
In setup.py
, write:
import setuptools
setuptools.setup(name='project_name')
Run this code in console:
python -m pip install --editable filepath_to/project_name
Instead of python
, you may need to use python3
or something, depending on how your python is installed. Also, you can use -e
instead of --editable
.
Now, your directory will look more or less like this. I don't know what the egg stuff is.
filepath_to/project_name/
setup.py
test_3.egg-info/
dependency_links.txt
PKG-INFO
SOURCES.txt
top_level.txt
This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.
Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:
filepath_to/project_name/
top_level_file.py
subdirectory/
subfile.py
setup.py |
test_3.egg-info/ |----- Ignore these guys
... |
Now, if top_level_file.py
looks like this:
x = 1
Then I can import it from subfile.py
, or really any other file anywhere else on your computer.
# subfile.py OR some_other_python_file_somewhere_else.py
import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.
print(top_level_file.x)
This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib
shenanigans, please let me know.
The simple <u>some text</u>
should work for you.
I have tried this with your data and it is working :
%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
It's much easier if you use Response.raw
and shutil.copyfileobj()
:
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
This streams the file to disk without using excessive memory, and the code is simple.
This should work:
Select
LTRIM(RTRIM(SUBSTRING(FullName, 0, CHARINDEX(' ', FullName)))) As FirstName
, LTRIM(RTRIM(SUBSTRING(FullName, CHARINDEX(' ', FullName)+1, 8000)))As LastName
FROM TABLE
Edit: Adopted Aaron's and Jonny's hint with the fixed length of 8000 to avoid unnecessary calculations.
Another technique is to type-hint (coerce) the incoming values to int
type after exploding the string.
Note that these techniques will work as demonstrated in my demo link unless you have set php to use strict typing.
The following techniques should not be used to sanitize non-numeric strings; it assumes that all values will be numeric.
If float values are passed into these techniques, they will be truncated/floored to integers.
Code: (Demo)
$string = "1,2,3";
$array = explode(',', $string);
var_dump($array);
echo "\n---\n";
array_walk($array, function(int &$int){;});
var_dump($array);
echo "\n---\n";
var_dump(
array_map(function(int $i){ return $i; }, explode(',', $string))
);
echo "\n---\n";
var_dump(
array_map(fn(int $i) => $i, explode(',', $string)) // PHP 7.4 arrow function syntax
);
Output:
array(3) {
[0]=> string(1) "1"
[1]=> string(1) "2"
[2]=> string(1) "3"
}
---
array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
---
array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
---
array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
I kind of bumped into this project at SourceForge. It seems to me it's still active.
My two cents.
To help others who do not have a full disk to troubleshoot this problem, first inspect your error log (for me the path is given in my /etc/mysql/my.cnf
file):
tail /var/log/mysql/error.log
My problem turned out to be a new IP address allocated after some network router reconfiguration, so I needed to change the bind-address
variable.
Sometimes you want to sort an array of objects on an arbitrary value. Since compareTo() always uses the same information about the instance, you might want to use a different technique. One way is to use a standard sorting algorithm. Let's say you have an array of books and you want to sort them on their height, which is stored as an int and accessible through the method getHeight(). Here's how you could sort the books in your array. (If you don't want to change the original array, simply make a copy and sort that.)
`int tallest; // the index of tallest book found thus far
Book temp; // used in the swap
for(int a = 0; a < booksArray.length - 1; a++) {
tallest = a; // reset tallest to current index
// start inner loop at next index
for(int b = a + 1; b < booksArray.length; b++)
// check if the book at this index is taller than the
// tallest found thus far
if(booksArray[b].getHeight() > booksArray[tallest].getHeight())
tallest = b;
// once inner loop is complete, swap the tallest book found with
// the one at the current index of the outer loop
temp = booksArray[a];
booksArray[a] = booksArray[tallest];
booksArray[tallest] = temp;
}`
When this code is done, the array of Book object will be sorted by height in descending order--an interior designer's dream!
ansible-playbook release.yml --extra-vars "username=hello password=bye"
#you can now use the above command anywhere in the playbook as an example below:
tasks:
- name: Create a new user in Linux
shell: useradd -m -p {{username}} {{password}}"
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
You can solve this by increasing the maximum request length in your web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
</configuration>
The example above is for a 100Mb limit.
If you're using libraries that look up a large amount of configation behind-the-scenes, such as WCF, you might consider doing this:
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "MyWcfClientWrapper.dll.config");
Or in PowerShell:
[AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "MyWcfClientWrapper.dll.config")
IMO this technique is a code smell and is really only suitable for use in ad hoc scripting. If you find yourself wanting to do this in production code, maybe it's time for an architectural review.
The following is NOT recommended:
As a technical curiosity, here's a variation on the theme. You can create a static constructor inside one of the classes housed in the DLL, and make this call from there. I wouldn't recommend doing this except as a last resort.
:g/^\s*$/d
^ begin of a line
\s* at least 0 spaces and as many as possible (greedy)
$ end of a line
paste
:command -range=% DBL :<line1>,<line2>g/^\s*$/d
in your .vimrc,then restart your vim. if you use command :5,12DBL it will delete all blank lines between 5th row and 12th row. I think my answer is the best answer!
Generally speaking, IN
and JOIN
are different queries that can yield different results.
SELECT a.*
FROM a
JOIN b
ON a.col = b.col
is not the same as
SELECT a.*
FROM a
WHERE col IN
(
SELECT col
FROM b
)
, unless b.col
is unique.
However, this is the synonym for the first query:
SELECT a.*
FROM a
JOIN (
SELECT DISTINCT col
FROM b
)
ON b.col = a.col
If the joining column is UNIQUE
and marked as such, both these queries yield the same plan in SQL Server
.
If it's not, then IN
is faster than JOIN
on DISTINCT
.
See this article in my blog for performance details:
I used this: config.log_level = :info
edit-in config/environments/performance.rb
Working great for me, rejecting SQL output, and show only rendering and important info.
Set the trigger
option of the popover to hover
instead of click
, which is the default one.
This can be done using either data-*
attributes in the markup:
<a id="popover" data-trigger="hover">Popover</a>
Or with an initialization option:
$("#popover").popover({ trigger: "hover" });
Here's a DEMO.
use this:
pil_image = PIL.Image.open('Image.jpg').convert('RGB')
open_cv_image = numpy.array(pil_image)
# Convert RGB to BGR
open_cv_image = open_cv_image[:, :, ::-1].copy()
Depending on your development environment you may not even have the choice what encoding your string data type will use internally.
But for storing and exchanging data I would always use UTF-8, if you have the choice. If you have mostly ASCII data this will give you the smallest amount of data to transfer, while still being able to encode everything. Optimizing for the least I/O is the way to go on modern machines.
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
this few lines are the simple answer for this question in sql server.
WITH mycte AS
(
SELECT CAST('2011-01-01' AS DATETIME) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue + 1 < '2021-12-31'
)
SELECT DateValue
FROM mycte
OPTION (MAXRECURSION 0)
In my case i had few things missing. I didnt install JDK and JRE of 64 bit while eclipse was of 64 bit version. Once done and JDK\bin path was set in PATH variable eclipse worked fine :)
See here: Search Path
Summary:
#include <stdio.h>
When the include file is in brackets the preprocessor first searches in paths specified via the -I flag. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).
#include "myFile.h"
When the include file is in quotes the preprocessor first searches in the current directory, then paths specified by -iquote, then -I paths, then the standard paths.
-nostdinc can be used to prevent the preprocessor from searching the standard paths at all.
Environment variables can also be used to add search paths.
When compiling if you use the -v flag you can see the search paths used.
Hashmap type Overwrite that key if hashmap key is same key
map.put("1","1111");
map.put("1","2222");
output
key:value
1:2222
UPDATE YourTable SET columnName = null WHERE YourCondition
let view = ...
let point = ...
view.bounds.contains(point)
bool CGRectContainsPoint(CGRect rect, CGPoint point);
Parameters
rect
The rectangle to examine.point
The point to examine.
Return Value
true if the rectangle is not null or empty and the point is located within the rectangle; otherwise, false.A point is considered inside the rectangle if its coordinates lie inside the rectangle or on the minimum X or minimum Y edge.
As an alternative you can just put this line in your code blocks and check php logs, for really slow functions it's pretty useful:
trigger_error("Task done at ". strftime('%H:%m:%S', time()), E_USER_NOTICE);
For serious debugging use XDebug + Cachegrind, see https://blog.nexcess.net/2011/01/29/diagnosing-slow-php-execution-with-xdebug-and-kcachegrind/
Aditionally to the answer from @srk, you should uninstall package setuptools
:
python -m pip uninstall pip setuptools
If you want to uninstall all other packages first, this answer has some hints: https://stackoverflow.com/a/11250821/265954
Note: before you use the commands from that answer, please carefully read the comments about side effects and how to avoid uninstalling pip
and setuptools
too early. E.g. pip freeze | grep -v "^-e" | grep -v "^(setuptools|pip)" | xargs pip uninstall -y
Here's exactly what the setup looks like.
I have tried several implementations, but would like to share my own.
It uses G-force
as unit for the threshold calculation. It makes it a bit easier to understand what is going on, and also with setting a good threshold.
It simply registers a increase in G force and triggers the listener if it exceeds the threshold. It doesn't use any direction thresholds, cause you don't really need that if you just want to register a good shake.
Of-course you need the standard registering and UN-registering of this listener in the Activity
.
Also, to check what threshold you need, I recommend the following app (I am not in any way connected to that app)
public class UmitoShakeEventListener implements SensorEventListener {
/**
* The gforce that is necessary to register as shake. (Must include 1G
* gravity)
*/
private final float shakeThresholdInGForce = 2.25F;
private final float gravityEarth = SensorManager.GRAVITY_EARTH;
private OnShakeListener listener;
public void setOnShakeListener(OnShakeListener listener) {
this.listener = listener;
}
public interface OnShakeListener {
public void onShake();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// ignore
}
@Override
public void onSensorChanged(SensorEvent event) {
if (listener != null) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float gX = x / gravityEarth;
float gY = y / gravityEarth;
float gZ = z / gravityEarth;
//G-Force will be 1 when there is no movement. (gravity)
float gForce = FloatMath.sqrt(gX * gX + gY * gY + gZ * gZ);
if (gForce > shakeThresholdInGForce) {
listener.onShake();
}
}
}
}
In case of OO... To say that a Given Class has and "Default" means that this Default (value) must declared acondingly an then may be usd as an Default Parameter ex:
class Pagination {
public:
int currentPage;
//...
Pagination() {
currentPage = 1;
//...
}
// your Default Pagination
static Pagination& Default() {
static Pagination pag;
return pag;
}
};
On your Method ...
shared_ptr<vector<Auditoria> >
findByFilter(Auditoria& audit, Pagination& pagination = Pagination::Default() ) {
This solutions is quite suitable since in this case, "Global default Pagination" is a single "reference" value. You will also have the power to change default values at runtime like an "gobal-level" configuration ex: user pagination navigation preferences and etc..
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?
this question might have your answer, it worked for me.
For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers
// yourLabel is your UILabel.
float widthIs =
[self.yourLabel.text
boundingRectWithSize:self.yourLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:self.yourLabel.font }
context:nil]
.size.width;
NSLog(@"the width of yourLabel is %f", widthIs);
After using the recommended way of implementing expandable/collapsible items residing in a RecyclerView
on RecyclerView expand/collapse items answered by HeisenBerg, I've seen some noticeable artifacts whenever the RecyclerView
is refreshed by invoking TransitionManager.beginDelayedTransition(ViewGroup)
and subsequently notifyDatasetChanged()
.
His original answer:
final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mExpandedPosition = isExpanded ? -1 : position;
TransitionManager.beginDelayedTransition(recyclerView);
notifyDataSetChanged();
}
});
Modified:
final boolean isExpanded = position == mExpandedPosition;
holder.details.setVisibility(isExpanded ? View.VISIBLE : View.GONE);
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mExpandedHolder != null) {
mExpandedHolder.details.setVisibility(View.GONE);
notifyItemChanged(mExpandedPosition);
}
mExpandedPosition = isExpanded ? -1 : holder.getAdapterPosition();
mExpandedHolder = isExpanded ? null : holder;
notifyItemChanged(holder.getAdapterPosition());
}
}
int
that keeps track of expanded itemViewHolder
used during item collapseNotice that the method TransitionManager.beginDelayedTransition(ViewGroup)
and notifyDataSetChanged()
are replaced by notifyItemChanged(int)
to target specific item and some little tweaks.
After the modification, the previous unwanted effects should be gone. However, this may not be the perfect solution. It only did what I wanted, eliminating the eyesores.
::EDIT::
For clarification, both mExpandedPosition
and mExpandedHolder
are globals.
This is too late but posting my experience for people looking at it later:-
In MS VS 2010 I had the same issue. It got resolved by putting quotes to post build copy command args which contained spaces!
In Project Properties --> Configuration Properties --> Build Events --> Post-Build Event --> Command Line
change:
copy $(ProjectDir)a\b\c $(OutputPath)
to
copy "$(ProjectDir)a\b\c" "$(OutputPath)"
This is similar to qntmfred's solution, but using a direct table dump. This option is slightly faster (see BCP docs):
to export:
bcp "[MyDatabase].dbo.Customer " out "Customer.bcp" -N -S localhost -T -E
to import:
bcp [MyDatabase].dbo.Customer in "Customer.bcp" -N -S localhost -T -E -b 10000
I faced the issue and was able to resolve it by making sure that the data types were exactly matching .
I was using SequelPro for adding the constraint and it was making the primary key as unsigned by default .
FOR SQL SERVER
EXEC sp_addlinkedserver @server='servername'
No need to specify other parameters. You can go through this article.
I think you want only the decimal value, in this case you can use the following:
declare @val decimal (8, 3)
SET @val = 123.456
SELECT @val - ROUND(@val,0,1)
Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.
update Original
set Original.Vaal= t.vaal
from Original join (select * from staging1 union select * from staging2) t
on Original.id=t.id
Summarized: Oracle under Windows has problems with usernames containing non-English letters or special characters:
If your machine is fresh installed, first look here. All the network related or 32 vs. 64 related issues may be not significant for you:
As others already pointed out partly, this error is highly related to the name of the TEMP dir. It occurred to me when installing Oracle 11g first time on a totally fresh Windows (e.g. Server 2008 R2 or Win 7, not important).
As I found out, on my machine the problem was, that the username contained a German special character ("ö"). Moreover Oracle cannot handle any special character, I assume, the TEMP path is limited to letters. Other colleagues here have reported problems with underscore and chinese characters.
Explanation: In Windows the TEMP dir (environment variable %TEMP%) is by default in the user directory, for example:
C:\Users\ThisUser\AppData\Local\Temp
If "ThisUser" contains special or non-ASCII characters, then in this case this affects the TEMP path, and that is where Oracle is gettings problems.
Setting the TEMP dir to different directory is of course another possibility instead of installing with another username.
Moreover, Oracle is not a fully native Windows citizen which everybody will recognize, if he opens the Oracle install logfile with notepad ;-) Obviously, this is not programmed cleanly and portable, e.g. with using "std::endl" instead of "\n" . (Yes, Notepad++ and other editors do the job.)
Overall, my impression is, if the database were of the same quality as it's installer, Oracle would not be so successful ..
Last remark: Yes, after failed install because of the special characters you see only one Oracle service named OracleRemExecService, but there is no reason to stop this manually as recommended in other solutions, if you are able to install again a fresh OS..
It worked for me:
Template HTML:
I added (ngModelChange)="selectChange($event)"
to my select
.
<div>
<label for="myListOptions">My List Options</label>
<select (ngModelChange)="selectChange($event)" [(ngModel)]=model.myListOptions.id >
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption.id">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.ts
this function:
selectChange( $event) {
//In my case $event come with a id value
this.model.myListOptions = this.listOptions[$event];
}
Note:
I try with [select]="oneOption.id==model.myListOptions.id"
and not work.
============= Another ways can be: =========
Template HTML:
I added [compareWith]="compareByOptionId
to my select
.
<div>
<label for="myListOptions">My List Options</label>
<select [(ngModel)]=model.myListOptions [compareWith]="compareByOptionId">
<option *ngFor="let oneOption of listOptions" [ngValue]="oneOption">{{oneOption.name}}</option>
</select>
</div>
On component.ts:
listOptions = [
{ id: 0, name: "Perfect" },
{ id: 1, name: "Low" },
{ id: 2, name: "Minor" },
{ id: 3, name: "High" },
];
An you need add to component.ts
this function:
/* Return true or false if it is the selected */
compareByOptionId(idFist, idSecond) {
return idFist && idSecond && idFist.id == idSecond.id;
}
What's the pythonic way to use getters and setters?
The "Pythonic" way is not to use "getters" and "setters", but to use plain attributes, like the question demonstrates, and del
for deleting (but the names are changed to protect the innocent... builtins):
value = 'something'
obj.attribute = value
value = obj.attribute
del obj.attribute
If later, you want to modify the setting and getting, you can do so without having to alter user code, by using the property
decorator:
class Obj:
"""property demo"""
#
@property # first decorate the getter method
def attribute(self): # This getter method name is *the* name
return self._attribute
#
@attribute.setter # the property decorates with `.setter` now
def attribute(self, value): # name, e.g. "attribute", is the same
self._attribute = value # the "value" name isn't special
#
@attribute.deleter # decorate with `.deleter`
def attribute(self): # again, the method name is the same
del self._attribute
(Each decorator usage copies and updates the prior property object, so note that you should use the same name for each set, get, and delete function/method.
After defining the above, the original setting, getting, and deleting code is the same:
obj = Obj()
obj.attribute = value
the_value = obj.attribute
del obj.attribute
You should avoid this:
def set_property(property,value): def get_property(property):
Firstly, the above doesn't work, because you don't provide an argument for the instance that the property would be set to (usually self
), which would be:
class Obj:
def set_property(self, property, value): # don't do this
...
def get_property(self, property): # don't do this either
...
Secondly, this duplicates the purpose of two special methods, __setattr__
and __getattr__
.
Thirdly, we also have the setattr
and getattr
builtin functions.
setattr(object, 'property_name', value)
getattr(object, 'property_name', default_value) # default is optional
The @property
decorator is for creating getters and setters.
For example, we could modify the setting behavior to place restrictions the value being set:
class Protective(object):
@property
def protected_value(self):
return self._protected_value
@protected_value.setter
def protected_value(self, value):
if acceptable(value): # e.g. type or range check
self._protected_value = value
In general, we want to avoid using property
and just use direct attributes.
This is what is expected by users of Python. Following the rule of least-surprise, you should try to give your users what they expect unless you have a very compelling reason to the contrary.
For example, say we needed our object's protected attribute to be an integer between 0 and 100 inclusive, and prevent its deletion, with appropriate messages to inform the user of its proper usage:
class Protective(object):
"""protected property demo"""
#
def __init__(self, start_protected_value=0):
self.protected_value = start_protected_value
#
@property
def protected_value(self):
return self._protected_value
#
@protected_value.setter
def protected_value(self, value):
if value != int(value):
raise TypeError("protected_value must be an integer")
if 0 <= value <= 100:
self._protected_value = int(value)
else:
raise ValueError("protected_value must be " +
"between 0 and 100 inclusive")
#
@protected_value.deleter
def protected_value(self):
raise AttributeError("do not delete, protected_value can be set to 0")
(Note that __init__
refers to self.protected_value
but the property methods refer to self._protected_value
. This is so that __init__
uses the property through the public API, ensuring it is "protected".)
And usage:
>>> p1 = Protective(3)
>>> p1.protected_value
3
>>> p1 = Protective(5.0)
>>> p1.protected_value
5
>>> p2 = Protective(-5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
File "<stdin>", line 15, in protected_value
ValueError: protectected_value must be between 0 and 100 inclusive
>>> p1.protected_value = 7.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 17, in protected_value
TypeError: protected_value must be an integer
>>> p1.protected_value = 101
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in protected_value
ValueError: protectected_value must be between 0 and 100 inclusive
>>> del p1.protected_value
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 18, in protected_value
AttributeError: do not delete, protected_value can be set to 0
Yes they do. .setter
and .deleter
make copies of the original property. This allows subclasses to properly modify behavior without altering the behavior in the parent.
class Obj:
"""property demo"""
#
@property
def get_only(self):
return self._attribute
#
@get_only.setter
def get_or_set(self, value):
self._attribute = value
#
@get_or_set.deleter
def get_set_or_delete(self):
del self._attribute
Now for this to work, you have to use the respective names:
obj = Obj()
# obj.get_only = 'value' # would error
obj.get_or_set = 'value'
obj.get_set_or_delete = 'new value'
the_value = obj.get_only
del obj.get_set_or_delete
# del obj.get_or_set # would error
I'm not sure where this would be useful, but the use-case is if you want a get, set, and/or delete-only property. Probably best to stick to semantically same property having the same name.
Start with simple attributes.
If you later need functionality around the setting, getting, and deleting, you can add it with the property decorator.
Avoid functions named set_...
and get_...
- that's what properties are for.
After I set core.autocrlf=true
I was getting "LF will be replaced by CRLF" (note not "CRLF will be replaced by LF") when I was git add
ing (or perhaps it was it on git commit
?) edited files in windows on a repository (that does use LF) that was checked out before I set core.autocrlf=true
.
I made a new checkout with core.autocrlf=true
and now I'm not getting those messages.
public static byte[][] arrayCopy(byte[][] arr){
if(arr!=null){
int[][] arrCopy = new int[arr.length][] ;
System.arraycopy(arr, 0, arrCopy, 0, arr.length);
return arrCopy;
}else { return new int[][]{};}
}
JavaScript Array splice() Method By Example
Example1 by tutsmake -Remove 2 elements from index 1
var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
arr.splice(1,2);
console.log( arr );
_x000D_
Example-2 By tutsmake – Add new element from index 0 JavaScript
var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
arr.splice(0,0,"zero");
console.log( arr );
_x000D_
Example-3 by tutsmake – Add and Remove Elements in Array JavaScript
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb'); // add at index 1
console.log(months);
months.splice(4, 1, 'May'); // replaces 1 element at index 4
console.log(months);
_x000D_
https://www.tutsmake.com/javascript-array-splice-method-by-example/
bool is an alias for the Boolean class. I use the alias when declaring a variable and the class name when calling a method on the class.
You can simply assign null
to the reference. (This will work for any type of array, not just ints
)
int[] arr = new int[]{1, 2, 3, 4};
arr = null;
This will 'clear out' the array. You can also assign a new array to that reference if you like:
int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};
If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.
Another example:
float[] arr = ;// some array that you want to clear
arr = new float[arr.length];
This will create a new float[]
initialized to the default value for float.
I tried following the above tutorial. Thing is tensorflow changes a lot and so do the NVIDIA versions needed for running on a GPU. The next issue is that your driver version determines your toolkit version etc. As of today this information about the software requirements should shed some light on how they interplay:
NVIDIA® GPU drivers —CUDA 9.0 requires 384.x or higher.
CUDA® Toolkit —TensorFlow supports CUDA 9.0.
CUPTI ships with the CUDA Toolkit.
cuDNN SDK (>= 7.2) Note: Make sure your GPU has compute compatibility >3.0
(Optional) NCCL 2.2 for multiple GPU support.
(Optional) TensorRT 4.0 to improve latency and throughput for inference on some models.
And here you'll find the up-to-date requirements stated by tensorflow (which will hopefully be updated by them on a regular basis).
This article helps. In particular, this section:
-File
Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.
i.e.
powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3
means run the file myfile.ps1 and arg1 arg2 & arg3 are the parameters for the PowerShell script.
A simple forEach
loop solves this quite well:
let text = 'the red apple and the green ball';
const toStrip = ['red', 'green'];
toStrip.forEach(x => {
text = text.replace(x, '');
});
console.log(text);
// logs -> the apple and the ball
(When trying to find out how to use kdiff3 from WSL git I ended up here and got the final pieces, so I'll post my solution for anyone else also stumbling in here while trying to find that answer)
With Windows update 1903 it is a lot easier; just use wslpath and there is no need to share TMP from Windows to WSL since the Windows side now has access to the WSL filesystem via \wsl$:
[merge]
renormalize = true
guitool = kdiff3
[diff]
tool = kdiff3
[difftool]
prompt = false
[difftool "kdiff3"]
# Unix style paths must be converted to windows path style
cmd = kdiff3.exe \"`wslpath -w $LOCAL`\" \"`wslpath -w $REMOTE`\"
trustExitCode = false
[mergetool]
keepBackup = false
prompt = false
[mergetool "kdiff3"]
path = kdiff3.exe
trustExitCode = false
Steps for using kdiff3 installed on Windows 10 as diff/merge tool for git in WSL:
# If TMP is passed via WSLENV then use it as TMPDIR
[[ ! -z "$WSLENV" && ! -z "$TMP" ]] && export TMPDIR=$TMP
[merge]
renormalize = true
guitool = kdiff3
[diff]
tool = kdiff3
[difftool]
prompt = false
[difftool "kdiff3"]
#path = kdiff3.exe
# Unix style paths must be converted to windows path style by changing '/mnt/c/' or '/c/' to 'c:/'
cmd = kdiff3.exe \"`echo $LOCAL | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\" \"`echo $REMOTE | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\"
trustExitCode = false
[mergetool]
keepBackup = false
prompt = false
[mergetool "kdiff3"]
path = kdiff3.exe
trustExitCode = false
$(window).height();
To set anything in the middle you can use CSS.
<style>
#divCentre
{
position: absolute;
left: 50%;
top: 50%;
width: 300px;
height: 400px;
margin-left: -150px;
margin-top: -200px;
}
</style>
<div id="divCentre">I am at the centre</div>
I highly recommend the reading of a lecture in SciPy-lectures organization:
https://scipy-lectures.org/intro/language/reusing_code.html
It explains all the commented doubts.
But, new paths can be easily added and avoiding duplication with the following code:
import sys
new_path = 'insert here the new path'
if new_path not in sys.path:
sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
Try this:
git fetch --all
git reset --hard origin/master
Explanation:
git fetch
downloads the latest from remote without trying to merge or rebase anything.
Please let me know if you have any questions!
An executable file needs to have permissions for execute set before you can execute it.
In your machine where you are building the docker image (not inside the docker image itself) try running:
ls -la path/to/directory
The first column of the output for your executable (in this case docker-entrypoint.sh) should have the executable bits set something like:
-rwxrwxr-x
If not then try:
chmod +x docker-entrypoint.sh
and then build your docker image again.
Docker uses it's own file system but it copies everything over (including permissions bits) from the source directories.
Based on this answer. It took some time for me to make this approach working, so I hope my answer will save someone's time.
Directive:
angular.module('app').directive('apsUploadFile', apsUploadFile);
function apsUploadFile() {
var directive = {
restrict: 'E',
templateUrl: 'upload.file.template.html',
link: apsUploadFileLink
};
return directive;
}
function apsUploadFileLink(scope, element, attrs) {
var input = $(element[0].querySelector('#fileInput'));
var button = $(element[0].querySelector('#uploadButton'));
var textInput = $(element[0].querySelector('#textInput'));
if (input.length && button.length && textInput.length) {
button.click(function (e) {
input.click();
});
textInput.click(function (e) {
input.click();
});
}
input.on('change', function (e) {
var files = e.target.files;
if (files[0]) {
scope.fileName = files[0].name;
} else {
scope.fileName = null;
}
scope.$apply();
});
}
upload.file.template.html
<input id="fileInput" type="file" class="ng-hide">
<md-button id="uploadButton"
class="md-raised md-primary"
aria-label="attach_file">
Choose file
</md-button>
<md-input-container md-no-float>
<input id="textInput" ng-model="fileName" type="text" placeholder="No file chosen" ng-readonly="true">
</md-input-container>
Based on Wikipedia's articles.
A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one.
The idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.
This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.
For example, let's say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations of roads you might take, and will only then tell you which way is the fastest. Of course, you might have to wait for a while until the algorithm finishes, and only then can you start driving. The path you will take will be the fastest one (assuming that nothing changed in the external environment).
On the other hand, a greedy algorithm will start you driving immediately and will pick the road that looks the fastest at every intersection. As you can imagine, this strategy might not lead to the fastest arrival time, since you might take some "easy" streets and then find yourself hopelessly stuck in a traffic jam.
In mathematical optimization, greedy algorithms solve combinatorial problems having the properties of matroids.
Dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure.
This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
Bootstrap has many facility of classes to easily style elements if HTML. It includes a various of padding and margin classes for modification of the appearance of the element.
.m-0 { margin:0!important; }
.m-1 { margin:.25rem!important; }
.m-2 { margin:.5rem!important; }
.m-3 { margin:1rem!important; }
.m-4 { margin:1.5rem!important; }
.m-5 { margin:3rem!important; }
.mt-0 { margin-top:0!important; }
.mr-0 { margin-right:0!important; }
.mb-0 { margin-bottom:0!important; }
.ml-0 { margin-left:0!important; }
.mx-0 { margin-left:0!immortant;margin-right:0!immortant; }
.my-0 { margin-top:0!important;margin-bottom:0!important; }
.mt-1 { margin-top:.25rem!important; }
.mr-1 { margin-right:.25rem!important; }
.mb-1 { margin-bottom:.25rem!important; }
.ml-1 { margin-left:.25rem!important; }
.mx-1 { margin-left:.25rem!important;margin-right:.25rem!important; }
.my-1 { margin-top:.25rem!important;margin-bottom:.25rem!important; }
.mt-2 { margin-top:.5rem!important; }
.mr-2 { margin-right:.5rem!important; }
.mb-2 { margin-bottom:.5rem!important; }
.ml-2 { margin-left:.5rem!important; }
.mx-2 { margin-right:.5rem!important;margin-left:.5rem!important; }
.my-2 { margin-top:.5rem!important;margin-bottom:.5rem!important; }
.mt-3 { margin-top:1rem!important; }
.mr-3 { margin-right:1rem!important; }
.mb-3 { margin-bottom:1rem!important; }
.ml-3 { margin-left:1rem!important; }
.mx-3 { margin-right:1rem!important;margin-left:1rem!important; }
.my-3 { margin-bottom:1rem!important;margin-top:1rem!important; }
.mt-4 { margin-top:1.5rem!important; }
.mr-4 { margin-right:1.5rem!important; }
.mb-4 { margin-bottom:1.5rem!important; }
.ml-4 { margin-left:1.5rem!important; }
.mx-4 { margin-right:1.5rem!important;margin-left:1.5rem!important; }
.my-4 { margin-top:1.5rem!important;margin-bottom:1.5rem!important; }
.mt-5 { margin-top:3rem!important; }
.mr-5 { margin-right:3rem!important; }
.mb-5 { margin-bottom:3rem!important; }
.ml-5 { margin-left:3rem!important; }
.mx-5 { margin-right:3rem!important;margin-left:3rem!important; }
.my-5 { margin-top:3rem!important;margin-bottom:3rem!important; }
.mt-auto { margin-top:auto!important; }
.mr-auto { margin-right:auto!important; }
.mb-auto { margin-bottom:auto!important; }
.ml-auto { margin-left:auto!important; }
.mx-auto { margin-right:auto!important;margin-left:auto!important; }
.my-auto { margin-bottom:auto!important;margin-top:auto!important; }
.p-0 { padding:0!important; }
.p-1 { padding:.25rem!important; }
.p-2 { padding:.5rem!important; }
.p-3 { padding:1rem!important; }
.p-4 { padding:1.5rem!important; }
.p-5 { padding:3rem!important; }
.pt-0 { padding-top:0!important; }
.pr-0 { padding-right:0!important; }
.pb-0 { padding-bottom:0!important; }
.pl-0 { padding-left:0!important; }
.px-0 { padding-left:0!important;padding-right:0!important; }
.py-0 { padding-top:0!important;padding-bottom:0!important; }
.pt-1 { padding-top:.25rem!important; }
.pr-1 { padding-right:.25rem!important; }
.pb-1 { padding-bottom:.25rem!important; }
.pl-1 { padding-left:.25rem!important; }
.px-1 { padding-left:.25rem!important;padding-right:.25rem!important; }
.py-1 { padding-top:.25rem!important;padding-bottom:.25rem!important; }
.pt-2 { padding-top:.5rem!important; }
.pr-2 { padding-right:.5rem!important; }
.pb-2 { padding-bottom:.5rem!important; }
.pl-2 { padding-left:.5rem!important; }
.px-2 { padding-right:.5rem!important;padding-left:.5rem!important; }
.py-2 { padding-top:.5rem!important;padding-bottom:.5rem!important; }
.pt-3 { padding-top:1rem!important; }
.pr-3 { padding-right:1rem!important; }
.pb-3 { padding-bottom:1rem!important; }
.pl-3 { padding-left:1rem!important; }
.py-3 { padding-bottom:1rem!important;padding-top:1rem!important; }
.px-3 { padding-right:1rem!important;padding-left:1rem!important; }
.pt-4 { padding-top:1.5rem!important; }
.pr-4 { padding-right:1.5rem!important; }
.pb-4 { padding-bottom:1.5rem!important; }
.pl-4 { padding-left:1.5rem!important; }
.px-4 { padding-right:1.5rem!important;padding-left:1.5rem!important; }
.py-4 { padding-top:1.5rem!important;padding-bottom:1.5rem!important; }
.pt-5 { padding-top:3rem!important; }
.pr-5 { padding-right:3rem!important; }
.pb-5 { padding-bottom:3rem!important; }
.pl-5 { padding-left:3rem!important; }
.px-5 { padding-right:3rem!important;padding-left:3rem!important; }
.py-5 { padding-top:3rem!important;padding-bottom:3rem!important; }
Are dictionaries ordered in Python 3.6+?
They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).
As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:
Make it so. "Dict keeps insertion order" is the ruling. Thanks!
This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.
How does the Python
3.6
dictionary implementation perform better[2] than the older one while preserving element order?
Essentially, by keeping two arrays.
The first array, dk_entries
, holds the entries (of type PyDictKeyEntry
) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).
The second, dk_indices
, holds the indices for the dk_entries
array (that is, values that indicate the position of the corresponding entry in dk_entries
). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices
and the corresponding entry is fetched by indexing dk_entries
. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t
(1
byte) to int32_t
/int64_t
(4
/8
bytes) on 32
/64
bit builds)
In the previous implementation, a sparse array of type PyDictKeyEntry
and size dk_size
had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size
full for performance reasons. (and the empty space still had PyDictKeyEntry
size!).
This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t
(X
depending on dict size) 2/3 * dk_size
s full is kept. The empty space changed from type PyDictKeyEntry
to intX_t
.
So, obviously, creating a sparse array of type PyDictKeyEntry
is much more memory demanding than a sparse array for storing int
s.
You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.
In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.
For example, the dictionary:
d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
is currently stored as [keyhash, key, value]:
entries = [['--', '--', '--'], [-8522787127447073495, 'barry', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [-9092791511155847987, 'timmy', 'red'], ['--', '--', '--'], [-6480567542315338377, 'guido', 'blue']]
Instead, the data should be organized as follows:
indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']]
As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.
[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict
object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==
, !=
). dict
s currently don't offer any of those behaviors/methods.
[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.
Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.
In my case, a script was running command while redirecting both stdout and stderr to a file, something like:
cmd > log 2>&1
I needed to update it such that when there is a failure, take some actions based on the error messages. I could of course remove the dup 2>&1
and capture the stderr from the script, but then the error messages won't go into the log file for reference. While the accepted answer from @lhunath is supposed to do the same, it redirects stdout
and stderr
to different files, which is not what I want, but it helped me to come up with the exact solution that I need:
(cmd 2> >(tee /dev/stderr)) > log
With the above, log will have a copy of both stdout
and stderr
and I can capture stderr
from my script without having to worry about stdout
.
Save a snapshot of the database into a dump.rdb by either running BGSAVE
or SAVE
from the command line. This will create a file named dump.rdb in the same folder as your redis server. See a list of all server commands.
Copy this dump.rdb to the other redis server you want to migrate to. When redis starts up, it looks for this file to initialize the database from.
$(document).ready(function () {
$("#tbl_Customer tbody tr .companyname").click(function () {
var comapnyname = $(this).closest(".trclass").find(".companyname").text();
var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
// var clickedCell = $(this);
alert(comapnyname);
alert(CompanyAddress);
alert(CompanyEmail);
alert(CompanyContactNumber);
alert(CompanyContactPerson);
//alert(clickedCell.text());
});
});
Yes, but you can select only one column in your subselect
SELECT (SELECT id FROM bla) AS my_select FROM bla2
I had a very similar problem and want to share my solution
Given this table (all MySQL 5.6):
create table DailySchedule
(
id int auto_increment primary key,
start_time time not null,
stop_time time not null
);
Select all rows where a given time x (hh:mm:ss)
is between start and stop time. Including the next day.
Note: replace NOW()
with the any time x
you like
SELECT id
FROM DailySchedule
WHERE
(start_time < stop_time AND NOW() BETWEEN start_time AND stop_time)
OR
(stop_time < start_time AND NOW() < start_time AND NOW() < stop_time)
OR
(stop_time < start_time AND NOW() > start_time)
Results
Given
id: 1, start_time: 10:00:00, stop_time: 15:00:00
id: 2, start_time: 22:00:00, stop_time: 12:00:00
NOW = 09:00:00
: 2
NOW = 14:00:00
: 1
NOW = 11:00:00
: 1,2
NOW = 20:00:00
: nothingYou can Simply Change Background Color of a View:
var body : some View{
VStack{
Color.blue.edgesIgnoringSafeArea(.all)
}
}
and You can also use ZStack :
var body : some View{
ZStack{
Color.blue.edgesIgnoringSafeArea(.all)
}
}
I had a similar exception (but different problem) - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document
, and fortunately it's solved easier:
Instead of
List<Document> docs = obj.get("documents");
Document doc = docs.get(0)
which gives error on second line, One can use
List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));
I believe tuple()
takes a list as an argument
For example,
tuple([1,2,3]) # returns (1,2,3)
see what happens if you wrap your array with brackets
Here, as the Text widget does not have a property that allows us to define a border
, we should wrap it with a widget that allows us to define a border.
There are several solutions.
But the best solution is the use of BoxDecoration in the Container widget.
Why choose to use BoxDecoration ?
Because BoxDecoration offers more customization like the possibility to define :
First, the border
and also define:
An example :
Container(
child:Text(' Hello Word '),
decoration: BoxDecoration(
color: Colors.yellow,
border: Border.all(
color: Colors.red ,
width: 2.0 ,
),
borderRadius: BorderRadius.circular(15),
),
),
Output :
Simply use the base transpose function t
, wrapped with as.data.frame
:
final_df <- as.data.frame(t(starting_df))
final_df
A B C D
a 1 2 3 4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd
Above updated. As docendo discimus pointed out, t
returns a matrix. As Mark suggested wrapping it with as.data.frame
gets back a data frame instead of a matrix. Thanks!
This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.
Your problem is that at the moment your incoming_Cid
column defined as CHAR(1)
when it should be CHAR(34)
.
To fix this just issue this command to change your columns' length from 1 to 34
ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);
Here is SQLFiddle demo
For simplicity, you can create a Jenkinsfile at the root of the git repository, similar to the below example 'Jenkinsfile' based on the groovy syntax of the declarative pipeline.
pipeline {
agent any
stages {
stage('Build the Project') {
steps {
git 'https://github.com/jaikrgupta/CarthageAPI-1.0.git'
echo pwd()
sh 'ls -alrt'
sh 'pip install -r requirements.txt'
sh 'python app.py &'
echo "Build stage gets finished here"
}
}
stage('Test') {
steps {
sh 'chmod 777 ./scripts/test-script.sh'
sh './scripts/test-script.sh'
sh 'cat ./test-reports/test_script.log'
echo "Test stage gets finished here"
}
}
}
https://github.com/jaikrgupta/CarthageAPI-1.0.git
You can now set up a new item in Jenkins as a Pipeline job. Select the
Definition
asPipeline script from SCM
andGit
for theSCM
option. Paste the project's git repo link in the Repository URL andJenkinsfile
in the script name box. Then click on thelightweight checkout
option and save the project. So whenever you pushed a commit to the git repo, you can always test the changes running theBuild Now
every time in Jenkins.
Please follow the instructions in the below visuals for easy setup a Jenkins Pipeline's job.
Some plugins require one to run as an Administrator
and will not load unless one has those credentials active in the shell.
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
in cmd window type:
type nul > your_file.txt
This will create 0 bytes in your_file.txt file.
Another way of doing it is by using the echo command:
echo.> your_file.txt
echo. - will create a file with one empty line in it.
Edited on 2019-04-01:
If you need to preserve the content of the file use >>
instead of >
> Creates a new file
>> Preserves content of the file
Example
type nul >> your_file.txt
Edited on 2020-04-07
You can also use call command.
Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call.
Example:
call >> your_file.txt
Using -x test
skip test execution but this also exclude test code compilation.
gradle build -x test
In our case, we have a CI/CD process where one goal is compilation and next goal is testing (Build -> Test).
So, for our first Build
goal we wanted to ensure that the whole project compiles well. For this we have used:
./gradlew build testClasses -x test
On the next goal we simply execute tests.
If keys are unique then there is no need for 2 maps, map of maps, mapOfWhateverThereIs. There needs to be only 1 single map and just a simple wrapper method that would put your keys and value into that map. Example:
Map<String, String> map = new HashMap<>();
public void addKeysAndValue(String key1, String key2, String value){
map.put(key1, value);
map.put(key2, value);
}
public void testIt(){
addKeysAndValue("behemoth", "hipopotam", "hornless rhino");
}
Then use your map as you normally would. You don't even need those fancy getByKeyN and containsKeyN.
Action Filters, jquery stringify, bleh...
Peter, this functionality is native to MVC. That's one of things that makes MVC so great.
$.post('SomeController/Batch', { 'ids': ['1', '2', '3']}, function (r) {
...
});
And in the action,
[HttpPost]
public ActionResult Batch(string[] ids)
{
}
Works like a charm:
If you're using jQuery 1.4+, then you want to look into setting traditional mode:
jQuery.ajaxSettings.traditional = true;
As described here: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters
This even works for complex objects. If you're interested, you should look into the MVC documentation about Model Binding: http://msdn.microsoft.com/en-us/library/dd410405.aspx
The following will do a dry run, as it says. HEAD being current version, PREV is previous, then the path to your file, or committed item:
svn merge --dry-run -rHEAD:PREV https://example.com/svn/myproject/trunk
If the dry run looks good, run the command without the --dry-run
Verify the change in revision and re-commit. To browse for version numbers try:
svn log
One nice clean way is to add a data-default
attribute to the select
<select id="my_select" data-default="b">
...
</select>
An then the code is really simple:
$("#reset").on("click", function () {
var $select = $('#my_select');
$select.val($select.data('default'));
});
Live example: http://jsfiddle.net/T8sCf/7/
If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.
See https://github.com/stisti/jenkins-app/
Download it from https://github.com/stisti/jenkins-app/downloads
The parameter -DskipTests may not work depending on your surefire-plugin version.
You can use "-Dmaven.test.skip.exec" instead of "-DskipTests"
Source: Surefire Parameter Details
You should have a clear idea of exceptions in java. In java there are checked exceptions and unchecked exceptions.
Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.
NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:
CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.
How to resolve: 1.Put your code in try catch block:
2.use throws keyword as shown by other guys above.
Advice:Read more about Exceptions.(I personally love this topic)
As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec
needs to understand it. If you don't want to convert the key using openssl pkcs8
or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:
static final Base64.Decoder DECODER = Base64.getMimeDecoder();
private static byte[] buildPKCS8Key(File privateKey) throws IOException {
final String s = new String(Files.readAllBytes(privateKey.toPath()));
if (s.contains("--BEGIN PRIVATE KEY--")) {
return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
}
if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
throw new RuntimeException("Invalid cert format: "+ s);
}
final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
final byte[] result = new byte[innerKey.length + 26];
System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
System.arraycopy(innerKey, 0, result, 26, innerKey.length);
return result;
}
Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec
constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));
const url = 'data:image/png;base6....';
fetch(url)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], "File name",{ type: "image/png" })
})
Base64 String -> Blob -> File.
I needed this peace of code as a subquery with some data filter before aggregation based on the outer most query but I wasn't able to do this using the chosen answer code because this filter should go in the inner most select (third level query) and the filter params was in the outer most select (first level query), which gave me the error ORA-00904: "TB_OUTERMOST"."COL": invalid identifier as the ANSI SQL states that table references (correlation names) are scoped to just one level deep.
I needed a solution with no levels of subquery and this one below worked great for me:
with
demotable as
(
select 1 group_id, 'David' name from dual union all
select 1 group_id, 'John' name from dual union all
select 1 group_id, 'Alan' name from dual union all
select 1 group_id, 'David' name from dual union all
select 2 group_id, 'Julie' name from dual union all
select 2 group_id, 'Charlie' name from dual
)
select distinct
group_id,
listagg(name, ',') within group (order by name) over (partition by group_id) names
from demotable
-- where any filter I want
group by group_id, name
order by group_id;
In order to retrieve the last row of a table for MS SQL database 2005, You can use the following query:
select top 1 column_name from table_name order by column_name desc;
Note: To get the first row of the table for MS SQL database 2005, You can use the following query:
select top 1 column_name from table_name;
In my case:
-console.log() // works
-console.error() // works
-app.use(logger('dev')) // Morgan is NOT logging requests that look like "GET /myURL 304 9.072 ms - -"
FIX: I was using Visual Studio code, and I had to add this to my Launch Config
"outputCapture": "std"
Suggestion, in case you are running from an IDE, run directly from the command line to make sure the IDE is not causing the problem.
One way you can do is :
myTextView.setTypeface(null, Typeface.ITALIC);
myTextView.setTypeface(null, Typeface.BOLD_ITALIC);
myTextView.setTypeface(null, Typeface.BOLD);
myTextView.setTypeface(null, Typeface.NORMAL);
Another option if you want to keep the previous typeface and don't want to lose previously applied then:
myTextView.setTypeface(textView.getTypeface(), Typeface.NORMAL);
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD);
myTextView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
myTextView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);
I will show visually the problem, using the great example from James answer and adding the alternative solution.
When you do the follow query, without the FETCH
:
Select e from Employee e
join e.phones p
where p.areaCode = '613'
You will have the follow results from Employee
as you expected:
EmployeeId | EmployeeName | PhoneId | PhoneAreaCode |
---|---|---|---|
1 | James | 5 | 613 |
1 | James | 6 | 416 |
But when you add the FETCH
word on JOIN
, this is what happens:
EmployeeId | EmployeeName | PhoneId | PhoneAreaCode |
---|---|---|---|
1 | James | 5 | 613 |
The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416
register when you use WHERE
on the FETCH
join.
So, to bring all phones and apply the WHERE
correctly, you need to have two JOIN
s: one for the WHERE
and another for the FETCH
. Like:
Select e from Employee e
join e.phones p
join fetch e.phones //no alias, to not commit the mistake
where p.areaCode = '613'
Try this way of formation, it is rather fancy ...
Have a look at this jsfiddle
The idea is to choose a the radio as a button instead of the normal circle image.
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers.
Convert style.scss
to style.css
set the arguments
--no-cache --update $FileName$:$FileNameWithoutExtension$.css
and output paths to refresh
$FileNameWithoutExtension$.css
Convert style.scss
to compressed style.min.css
set the arguments
--no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
and output paths to refresh
$FileNameWithoutExtension$.min.css
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
So, you want an 8-character wide field with spaces as the padding? Try "%8d". Here's a reference.
EDIT: What you're trying to do is not something that can be handled by printf alone, because it will not know what the longest number you are writing is. You will need to calculate the largest number before doing any printfs, and then figure out how many digits to use as the width of your field. Then you can use snprintf or similar to make a printf format on the spot.
char format[20];
snprintf(format, 19, "%%%dd\\n", max_length);
while (got_output) {
printf(format, number);
got_output = still_got_output();
}
I'm not sure how to achieve your desired effect through the selector itself -- after all, by definition, there is one selector for the whole list.
However, you can get control on selection changes and draw whatever you want. In this sample project, I make the selector transparent and draw a bar on the selected item.
n:m --> if you dont know both n and m it is simply many to many and it is represented by a bridge table between 2 other tables like
-- This table will hold our phone calls.
CREATE TABLE dbo.PhoneCalls
(
ID INT IDENTITY(1, 1) NOT NULL,
CallTime DATETIME NOT NULL DEFAULT GETDATE(),
CallerPhoneNumber CHAR(10) NOT NULL
)
-- This table will hold our "tickets" (or cases).
CREATE TABLE dbo.Tickets
(
ID INT IDENTITY(1, 1) NOT NULL,
CreatedTime DATETIME NOT NULL DEFAULT GETDATE(),
Subject VARCHAR(250) NOT NULL,
Notes VARCHAR(8000) NOT NULL,
Completed BIT NOT NULL DEFAULT 0
)
this is the bridge table for implementing Mapping between 2 tables
CREATE TABLE dbo.PhoneCalls_Tickets
(
PhoneCallID INT NOT NULL,
TicketID INT NOT NULL
)
One to Many (1:n) is simply one table which has a column as primary key and another table which has this column as a foreign key relationship
Kind of like Product and Product Category where one product Category can have Many products
recordId is property of the object
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Nai_record other = (Nai_record) obj;
if (recordId == null) {
if (other.recordId != null)
return false;
} else if (!recordId.equals(other.recordId))
return false;
return true;
}
The solutions offered here are quite bad.
&
for &, <
for <, >
for >, ä
for ä, ö
for ö ü
for ü ß
for ß, etc.What you need to do:
Loop through the HTML document, find all text nodes, get the textContent
, get the position of the highlight-text with indexOf
(with an optional toLowerCase
if it should be case-insensitive), append everything before indexof
as textNode
, append the matched Text with a highlight span, and repeat for the rest of the textnode (the highlight string might occur multiple times in the textContent
string).
Here is the code for this:
var InstantSearch = {
"highlight": function (container, highlightText)
{
var internalHighlighter = function (options)
{
var id = {
container: "container",
tokens: "tokens",
all: "all",
token: "token",
className: "className",
sensitiveSearch: "sensitiveSearch"
},
tokens = options[id.tokens],
allClassName = options[id.all][id.className],
allSensitiveSearch = options[id.all][id.sensitiveSearch];
function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll)
{
var nodeVal = node.nodeValue, parentNode = node.parentNode,
i, j, curToken, myToken, myClassName, mySensitiveSearch,
finalClassName, finalSensitiveSearch,
foundIndex, begin, matched, end,
textNode, span, isFirst;
for (i = 0, j = tokenArr.length; i < j; i++)
{
curToken = tokenArr[i];
myToken = curToken[id.token];
myClassName = curToken[id.className];
mySensitiveSearch = curToken[id.sensitiveSearch];
finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);
finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);
isFirst = true;
while (true)
{
if (finalSensitiveSearch)
foundIndex = nodeVal.indexOf(myToken);
else
foundIndex = nodeVal.toLowerCase().indexOf(myToken.toLowerCase());
if (foundIndex < 0)
{
if (isFirst)
break;
if (nodeVal)
{
textNode = document.createTextNode(nodeVal);
parentNode.insertBefore(textNode, node);
} // End if (nodeVal)
parentNode.removeChild(node);
break;
} // End if (foundIndex < 0)
isFirst = false;
begin = nodeVal.substring(0, foundIndex);
matched = nodeVal.substr(foundIndex, myToken.length);
if (begin)
{
textNode = document.createTextNode(begin);
parentNode.insertBefore(textNode, node);
} // End if (begin)
span = document.createElement("span");
span.className += finalClassName;
span.appendChild(document.createTextNode(matched));
parentNode.insertBefore(span, node);
nodeVal = nodeVal.substring(foundIndex + myToken.length);
} // Whend
} // Next i
}; // End Function checkAndReplace
function iterator(p)
{
if (p === null) return;
var children = Array.prototype.slice.call(p.childNodes), i, cur;
if (children.length)
{
for (i = 0; i < children.length; i++)
{
cur = children[i];
if (cur.nodeType === 3)
{
checkAndReplace(cur, tokens, allClassName, allSensitiveSearch);
}
else if (cur.nodeType === 1)
{
iterator(cur);
}
}
}
}; // End Function iterator
iterator(options[id.container]);
} // End Function highlighter
;
internalHighlighter(
{
container: container
, all:
{
className: "highlighter"
}
, tokens: [
{
token: highlightText
, className: "highlight"
, sensitiveSearch: false
}
]
}
); // End Call internalHighlighter
} // End Function highlight
};
Then you can use it like this:
function TestTextHighlighting(highlightText)
{
var container = document.getElementById("testDocument");
InstantSearch.highlight(container, highlightText);
}
Here's an example HTML document
<!DOCTYPE html>
<html>
<head>
<title>Example of Text Highlight</title>
<style type="text/css" media="screen">
.highlight{ background: #D3E18A;}
.light{ background-color: yellow;}
</style>
</head>
<body>
<div id="testDocument">
This is a test
<span> This is another test</span>
äöüÄÖÜäöüÄÖÜ
<span>Test123äöüÄÖÜ</span>
</div>
</body>
</html>
By the way, if you search in a database with LIKE
,
e.g. WHERE textField LIKE CONCAT('%', @query, '%')
[which you shouldn't do, you should use fulltext-search or Lucene], then you can escape every character with \ and add an SQL-escape-statement, that way you'll find special characters that are LIKE-expressions.
e.g.
WHERE textField LIKE CONCAT('%', @query, '%') ESCAPE '\'
and the value of @query is not '%completed%'
but '%\c\o\m\p\l\e\t\e\d%'
(tested, works with SQL-Server and PostgreSQL, and every other RDBMS system that supports ESCAPE)
A revised typescript-version:
namespace SearchTools
{
export interface IToken
{
token: string;
className: string;
sensitiveSearch: boolean;
}
export class InstantSearch
{
protected m_container: Node;
protected m_defaultClassName: string;
protected m_defaultCaseSensitivity: boolean;
protected m_highlightTokens: IToken[];
constructor(container: Node, tokens: IToken[], defaultClassName?: string, defaultCaseSensitivity?: boolean)
{
this.iterator = this.iterator.bind(this);
this.checkAndReplace = this.checkAndReplace.bind(this);
this.highlight = this.highlight.bind(this);
this.highlightNode = this.highlightNode.bind(this);
this.m_container = container;
this.m_defaultClassName = defaultClassName || "highlight";
this.m_defaultCaseSensitivity = defaultCaseSensitivity || false;
this.m_highlightTokens = tokens || [{
token: "test",
className: this.m_defaultClassName,
sensitiveSearch: this.m_defaultCaseSensitivity
}];
}
protected checkAndReplace(node: Node)
{
let nodeVal: string = node.nodeValue;
let parentNode: Node = node.parentNode;
let textNode: Text = null;
for (let i = 0, j = this.m_highlightTokens.length; i < j; i++)
{
let curToken: IToken = this.m_highlightTokens[i];
let textToHighlight: string = curToken.token;
let highlightClassName: string = curToken.className || this.m_defaultClassName;
let caseSensitive: boolean = curToken.sensitiveSearch || this.m_defaultCaseSensitivity;
let isFirst: boolean = true;
while (true)
{
let foundIndex: number = caseSensitive ?
nodeVal.indexOf(textToHighlight)
: nodeVal.toLowerCase().indexOf(textToHighlight.toLowerCase());
if (foundIndex < 0)
{
if (isFirst)
break;
if (nodeVal)
{
textNode = document.createTextNode(nodeVal);
parentNode.insertBefore(textNode, node);
} // End if (nodeVal)
parentNode.removeChild(node);
break;
} // End if (foundIndex < 0)
isFirst = false;
let begin: string = nodeVal.substring(0, foundIndex);
let matched: string = nodeVal.substr(foundIndex, textToHighlight.length);
if (begin)
{
textNode = document.createTextNode(begin);
parentNode.insertBefore(textNode, node);
} // End if (begin)
let span: HTMLSpanElement = document.createElement("span");
if (!span.classList.contains(highlightClassName))
span.classList.add(highlightClassName);
span.appendChild(document.createTextNode(matched));
parentNode.insertBefore(span, node);
nodeVal = nodeVal.substring(foundIndex + textToHighlight.length);
} // Whend
} // Next i
} // End Sub checkAndReplace
protected iterator(p: Node)
{
if (p == null)
return;
let children: Node[] = Array.prototype.slice.call(p.childNodes);
if (children.length)
{
for (let i = 0; i < children.length; i++)
{
let cur: Node = children[i];
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
if (cur.nodeType === Node.TEXT_NODE)
{
this.checkAndReplace(cur);
}
else if (cur.nodeType === Node.ELEMENT_NODE)
{
this.iterator(cur);
}
} // Next i
} // End if (children.length)
} // End Sub iterator
public highlightNode(n:Node)
{
this.iterator(n);
} // End Sub highlight
public highlight()
{
this.iterator(this.m_container);
} // End Sub highlight
} // End Class InstantSearch
} // End Namespace SearchTools
Usage:
let searchText = document.getElementById("txtSearchText");
let searchContainer = document.body; // document.getElementById("someTable");
let highlighter = new SearchTools.InstantSearch(searchContainer, [
{
token: "this is the text to highlight" // searchText.value,
className: "highlight", // this is the individual highlight class
sensitiveSearch: false
}
]);
// highlighter.highlight(); // this would highlight in the entire table
// foreach tr - for each td2
highlighter.highlightNode(td2); // this highlights in the second column of table
FWIW, a timeout in seconds value should probably be a configuration setting (read in from a properties file or through injection as in Spring) and not a constant.
I removed the bugs in above code and got below results: Also I am unsure given how NetSerializer requires you to register the types you are serializing, what kind of compatibility or performance differences that could potentially make.
Generating 100000 arrays of data...
Test data generated.
Testing BinarySerializer...
BinaryFormatter: Serializing took 508.9773ms.
BinaryFormatter: Deserializing took 371.8499ms.
Testing ProtoBuf serializer...
ProtoBuf: Serializing took 3280.9185ms.
ProtoBuf: Deserializing took 3190.7899ms.
Testing NetSerializer serializer...
NetSerializer: Serializing took 427.1241ms.
NetSerializer: Deserializing took 78.954ms.
Press any key to end.
Modified Code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace SerializationTests
{
class Program
{
static void Main(string[] args)
{
var count = 100000;
var rnd = new Random((int)DateTime.UtcNow.Ticks & 0xFF);
Console.WriteLine("Generating {0} arrays of data...", count);
var arrays = new List<int[]>();
for (int i = 0; i < count; i++)
{
var elements = rnd.Next(1, 100);
var array = new int[elements];
for (int j = 0; j < elements; j++)
{
array[j] = rnd.Next();
}
arrays.Add(array);
}
Console.WriteLine("Test data generated.");
var stopWatch = new Stopwatch();
Console.WriteLine("Testing BinarySerializer...");
var binarySerializer = new BinarySerializer();
var binarySerialized = new List<byte[]>();
var binaryDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
binarySerialized.Add(binarySerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("BinaryFormatter: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in binarySerialized)
{
binaryDeserialized.Add(binarySerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("BinaryFormatter: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Testing ProtoBuf serializer...");
var protobufSerializer = new ProtoBufSerializer();
var protobufSerialized = new List<byte[]>();
var protobufDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
foreach (var array in arrays)
{
protobufSerialized.Add(protobufSerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("ProtoBuf: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in protobufSerialized)
{
protobufDeserialized.Add(protobufSerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("ProtoBuf: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Testing NetSerializer serializer...");
var netSerializerSerialized = new List<byte[]>();
var netSerializerDeserialized = new List<int[]>();
stopWatch.Reset();
stopWatch.Start();
var netSerializerSerializer = new NS();
foreach (var array in arrays)
{
netSerializerSerialized.Add(netSerializerSerializer.Serialize(array));
}
stopWatch.Stop();
Console.WriteLine("NetSerializer: Serializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
stopWatch.Reset();
stopWatch.Start();
foreach (var serialized in netSerializerSerialized)
{
netSerializerDeserialized.Add(netSerializerSerializer.Deserialize<int[]>(serialized));
}
stopWatch.Stop();
Console.WriteLine("NetSerializer: Deserializing took {0}ms.", stopWatch.Elapsed.TotalMilliseconds);
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
public class BinarySerializer
{
private static readonly BinaryFormatter Formatter = new BinaryFormatter();
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
Formatter.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
var result = (T)Formatter.Deserialize(stream);
return result;
}
}
}
public class ProtoBufSerializer
{
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
var result = ProtoBuf.Serializer.Deserialize<T>(stream);
return result;
}
}
}
public class NS
{
NetSerializer.Serializer Serializer = new NetSerializer.Serializer(new Type[] { typeof(int), typeof(int[]) });
public byte[] Serialize(object toSerialize)
{
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, toSerialize);
return stream.ToArray();
}
}
public T Deserialize<T>(byte[] serialized)
{
using (var stream = new MemoryStream(serialized))
{
Serializer.Deserialize(stream, out var result);
return (T)result;
}
}
}
}
}
Try out this will solve ur problem ....
EditText etxt = (EditText)findviewbyid(R.id.etxt);
String str_value = etxt.getText().toString();
check out my js lib for caching: https://github.com/hoangnd25/cacheJS
My blog post: New way to cache your data with Javascript
Saving cache:
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});
Retrieving cache:
cacheJS.get({blogId: 1,type: 'view'});
Flushing cache
cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});
cacheJS.removeByContext({author:'hoangnd'});
Switching provider
cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};
Using this HTML:
<div id="myElement" style="position: absolute">This stays at the top</div>
This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.
$(window).scroll(function() {
$('#myElement').css('top', $(this).scrollTop() + "px");
});
As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.
Since the Import dialouge is different in Android Studio 1.0.1, I could't get Svyatoslav Lobachs version to work.
Instead I downloaded "Android Support Repository" in the SDK Manager. Then added
dependencies {
...
compile "com.android.support:appcompat-v7:18.0.+"
}
to build.gradle
. Worked for me.
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
From the docs (note: MSDN is a handy resource when you want to know what things do!):
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
Sends the CommandText to the Connection and builds a SqlDataReader.
... and from SqlDataReader ...
Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Try this, it worked for me.
mongod --storageEngine=mmpav1
For me, the solution is:
Check Overwrite the existing database(WITH REPLACE) in optoins tab at left hand side.
Uncheck all other options.
Select source and destination database.
Click ok.
That's it.
For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED
. You can use MySQL's INET_ATON()
function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN
queries
With a running instance of myExecutableName
having a PID 15073
:
hitting Tab twice after $ gdb myExecu
in the command line, will automagically autocompletes to:
$ gdb myExecutableName 15073
and will attach gdb to this process. That's nice!
In addition to the answer of Hugo Ideler.
When using arguments having themself prefix like --
or -
, I was not sure to conflict with gdb one.
It seems gdb takes all after args
option as arguments for the program.
At first I wanted to be sure, I ran gdb with quotes around your args, it is removed at launch.
This works too, but optional:
gdb --args executablename "--arg1" "--arg2" "--arg3"
This doesn't work :
gdb --args executablename "--arg1" "--arg2" "--arg3" -tui
In that case, -tui
is used as my program parameter not as gdb one.
(select add_date,col2 from table_name)
union
(select add_date,col2 from table_name)
union
(select add_date,col2 from table_name)
order by add_date
public class Main {
public static List<String> list = new ArrayList();
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(222);
l.add(100);
l.add(45);
l.add(415);
l.add(311);
l.sort(null);
System.out.println(l.get(0));
}
}
without l.sort(null) returned 222
with l.sort(null) returned 45
Sometimes it can make the assignment of a bool value easier to read at first glance:
// With
button.IsEnabled = someControl.HasError ? false : true;
// Without
button.IsEnabled = !someControl.HasError;
The EOF flag is only set after a read operation attempts to read past the end of the file. get()
is returning the symbolic constant traits::eof()
(which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof()
be true. If you want to check for this condition, you can do something like the following:
int ch;
while ((ch = inf.get()) != EOF) {
std::cout << static_cast<char>(ch) << "\n";
}
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
Just use the -jrm
option to remove the file and directory
structures
zip -jrm /path/to/file.zip /path/to/file
Just in case someone stumbles here, I did it this way
componentDidMount(){
const node = this.refs.trackerRef;
node && node.scrollIntoView({block: "end", behavior: 'smooth'})
}
componentDidUpdate() {
const node = this.refs.trackerRef;
node && node.scrollIntoView({block: "end", behavior: 'smooth'})
}
render() {
return (
<div>
{messages.map((msg, index) => {
return (
<Message key={index} msgObj={msg}
{/*<p>some test text</p>*/}
</Message>
)
})}
<div style={{height: '30px'}} id='#tracker' ref="trackerRef"></div>
</div>
)
}
scrollIntoView
is native DOM feature link
It will always shows tracker
div
To see non-staged (non-added) changes to existing files
git diff
Note that this does not track new files. To see staged, non-commited changes
git diff --cached
I had this issue recently and I am using Android Studio 0.8.4
The problem was the fact that I decided to rename an XML menu layout file that was called main.xml.
Right click on it and chose Refactor --> Rename. Before renaming it, be sure uncheck "Search in comments and strings" and pressed Refactor.
Because my file was originally named 'main', it renamed critical paths in the app.iml and build.gradle, mainly the java.srcDirs in the build.gradle, since the path is defined as 'src/main/java'
.
I hope this helps anyone that may be experiencing this issue.
Here's a good reference on the different formatting you can use with regard to the date:
WARNING: This deletes all commits on the email branch. It's like deleting the email branch and creating it anew at the head of the staging branch.
The easiest way to do it:
//the branch you want to overwrite
git checkout email
//reset to the new branch
git reset --hard origin/staging
// push to remote
git push -f
Now the email branch and the staging are the same.
You are casting ClientID
to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).
Below is another way to capitalize each word in a string. \w
doesn't match Cyrillic characters or Latin characters with diacritics but [[:word:]]
does. upcase
, downcase
, capitalize
, and swapcase
didn't apply to non-ASCII characters until Ruby 2.4.0 which was released in 2016.
"aAa-BBB ä ????? _a a_a".gsub(/\w+/,&:capitalize)
=> "Aaa-Bbb ä ????? _a A_a"
"aAa-BBB ä ????? _a a_a".gsub(/[[:word:]]+/,&:capitalize)
=> "Aaa-Bbb Ä ????? _a A_a"
[[:word:]]
matches characters in these categories:
Ll (Letter, Lowercase)
Lu (Letter, Uppercase)
Lt (Letter, Titlecase)
Lo (Letter, Other)
Lm (Letter, Modifier)
Nd (Number, Decimal Digit)
Pc (Punctuation, Connector)
[[:word:]]
matches all 10 of the characters in the "Punctuation, Connector" (Pc
) category:
005F _ LOW LINE
203F ? UNDERTIE
2040 ? CHARACTER TIE
2054 ? INVERTED UNDERTIE
FE33 ? PRESENTATION FORM FOR VERTICAL LOW LINE
FE34 ? PRESENTATION FORM FOR VERTICAL WAVY LOW LINE
FE4D ? DASHED LOW LINE
FE4E ? CENTRELINE LOW LINE
FE4F ? WAVY LOW LINE
FF3F _ FULLWIDTH LOW LINE
This is another way to only convert the first character of a string to uppercase:
"striNG".sub(/./,&:upcase)
=> "StriNG"
You could return the value using return JsonConvert.SerializeObject(objName); And send it to the front end
Here are the three web pages on which we found the answer. The most difficult part was setting up static ports for SQLEXPRESS.
Provisioning a SQL Server Virtual Machine on Windows Azure. These initial instructions provided 25% of the answer.
How to Troubleshoot Connecting to the SQL Server Database Engine. Reading this carefully provided another 50% of the answer.
How to configure SQL server to listen on different ports on different IP addresses?. This enabled setting up static ports for named instances (eg SQLEXPRESS.) It took us the final 25% of the way to the answer.
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
Depends on whether you really need to physically concatenate the two vectors or you want to give the appearance of concatenation of the sake of iteration. The boost::join function
http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html
will give you this.
std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);
std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...
BOOST_FOREACH(const int & i, boost::join(v0, v1)){
cout << i << endl;
}
should give you
1
2
3
4
5
6
Note boost::join does not copy the two vectors into a new container but generates a pair of iterators (range) that cover the span of both containers. There will be some performance overhead but maybe less that copying all the data to a new container first.
Here is a working code snippet that will print out the full version of currently running Eclipse (or any RCP-based application).
String product = System.getProperty("eclipse.product");
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
Logger log = LoggerFactory.getLogger(getClass());
if (point != null) {
IExtension[] extensions = point.getExtensions();
for (IExtension ext : extensions) {
if (product.equals(ext.getUniqueIdentifier())) {
IContributor contributor = ext.getContributor();
if (contributor != null) {
Bundle bundle = Platform.getBundle(contributor.getName());
if (bundle != null) {
System.out.println("bundle version: " + bundle.getVersion());
}
}
}
}
}
It looks up the currently running "product" extension and takes the version of contributing plugin.
On Eclipse Luna 4.4.0, it gives the result of 4.4.0.20140612-0500
which is correct.
Synchronized keyword in Java has to do with thread-safety, that is, when multiple threads read or write the same variable.
This can happen directly (by accessing the same variable) or indirectly (by using a class that uses another class that accesses the same variable).
The synchronized keyword is used to define a block of code where multiple threads can access the same variable in a safe way.
Syntax-wise the synchronized
keyword takes an Object
as it's parameter (called a lock object), which is then followed by a { block of code }
.
When execution encounters this keyword, the current thread tries to "lock/acquire/own" (take your pick) the lock object and execute the associated block of code after the lock has been acquired.
Any writes to variables inside the synchronized code block are guaranteed to be visible to every other thread that similarly executes code inside a synchronized code block using the same lock object.
Only one thread at a time can hold the lock, during which time all other threads trying to acquire the same lock object will wait (pause their execution). The lock will be released when execution exits the synchronized code block.
Adding synchronized
keyword to a method definition is equal to the entire method body being wrapped in a synchronized code block with the lock object being this
(for instance methods) and ClassInQuestion.getClass()
(for class methods).
- Instance method is a method which does not have static
keyword.
- Class method is a method which has static
keyword.
Without synchronization, it is not guaranteed in which order the reads and writes happen, possibly leaving the variable with garbage.
(For example a variable could end up with half of the bits written by one thread and half of the bits written by another thread, leaving the variable in a state that neither of the threads tried to write, but a combined mess of both.)
It is not enough to complete a write operation in a thread before (wall-clock time) another thread reads it, because hardware could have cached the value of the variable, and the reading thread would see the cached value instead of what was written to it.
Thus in Java's case, you have to follow the Java Memory Model to ensure that threading errors do not happen.
In other words: Use synchronization, atomic operations or classes that use them for you under the hoods.
Sources
http://docs.oracle.com/javase/specs/jls/se8/html/index.html
Java® Language Specification, 2015-02-13
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';
These should both work
While all the answers here are great and most work very well, there is a slightly simpler method which achieves the same effect...
For Push:
NextViewController *nextViewController = [[NextViewController alloc] init];
// Shift the view to take the status bar into account
CGRect frame = nextViewController.view.frame;
frame.origin.y -= 20;
frame.size.height += 20;
nextViewController.view.frame = frame;
[UIView transitionFromView:self.navigationController.topViewController.view toView:nextViewController.view duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
[self.navigationController pushViewController:nextViewController animated:NO];
}];
For Pop:
int numViewControllers = self.navigationController.viewControllers.count;
UIView *nextView = [[self.navigationController.viewControllers objectAtIndex:numViewControllers - 2] view];
[UIView transitionFromView:self.navigationController.topViewController.view toView:nextView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft completion:^(BOOL finished) {
[self.navigationController popViewControllerAnimated:NO];
}];}
Tools --> Preferences
, as shown in below image.expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory
where tnsnames.ora present.Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN
Now you can connect via the TNSnames options.
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
It really depends on the kind of classes as not all classes are created equal.
As general guideline I would suggest 2 options:
The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.
The number of rows effected is returned from execute:
rows_affected=cursor.execute("SELECT ... ")
of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:
cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount
From the inline documentation of python MySQLdb:
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an
if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }
Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string
on the post vars before using them in SQL queries. mysql_real_escape_string
is not good enough for a production site, but should score you extra points in class.
Developers using a mybatis-like framework will prefer != over <>. Reason being the <> will need to be wrapped in CDATA as it could be interpreted as xml syntax. Easier on the eyes too.
Go to My Computer>Properties>Advance System Settings>Environment Variables>
Under the variables of Administrator edit the PATH variable & change its value to "C:\Users\Username\AppData\Roaming\npm"
. Note: The username in the path will be the current Admin user's name that you have logged in with.
You can use expandtabs
to specify the tabstop, like this:
>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1'.expandtabs(30))
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012'.expandtabs(30))
#Output:
Location:10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.
Guid.NewGuid()
, as it creates GUIDs as intended.
Guid.NewGuid()
creates an empty Guid
object, initializes it by calling CoCreateGuid
and returns the object.
new Guid()
merely creates an empty GUID (all zeros, I think).
I guess they had to make the constructor public as Guid
is a struct
.
Another option:
Advantages:
Disadvantages:
Probably you haven't injected $http
service to your controller. There are several ways of doing that.
Please read this reference about DI. Then it gets very simple:
function MyController($scope, $http) {
// ... your code
}
I needed to use the Window.GetWindow(this) method within Loaded event handler. In other words, I used both Ian Oakes' answer in combination with Alex's answer to get a user control's parent.
public MainView()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainView_Loaded);
}
void MainView_Loaded(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
...
}
byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);
At first you need to add semi colon (;) after quantity INT NOT NULL)
then remove ** from ,genre,quantity)**
.
to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.
Using keySet-
id1.keySet().stream()
.filter(x -> x == 1)
.map(x -> id1.get(x))
.collect(Collectors.toList())
CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted
for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :
**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **
For Mysql8->
Query:
SELECT properties, properties->"$.price" FROM book where isbn='978-9730228236' and JSON_EXTRACT(properties, "$.price") > 400;
Data:
mysql> select * from book\G;
*************************** 1. row ***************************
id: 1
isbn: 978-9730228236
properties: {"price": 44.99, "title": "High-Performance Java Persistence", "author": "Vlad Mihalcea", "publisher": "Amazon"}
1 row in set (0.00 sec)