Here's how to do it inside ViewModel
and FusedLocationProviderClient
, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
For the UITextField text comparison I am using below code and working fine for me, let me know if you find any error.
if(txtUsername.text.isEmpty || txtPassword.text.isEmpty)
{
//Do some stuff
}
else if(txtUsername.text == "****" && txtPassword.text == "****")
{
//Do some stuff
}
Both syntaxes are correct. But the result would be Array
. You probably want to do something like this:
foreach ($tmpArray[1] as $value) {
echo $value[0];
foreach($value[1] as $val){
echo $val;
}
}
This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).
"Can you tell if an email customer / user enters is correct & exists?"
Actually these are two separate things. It might exist but might not be correct.
Sometimes you have to take the user inputs at the face value. There are many ways to defeat the system otherwise.
Try this
$("#postcontent").submit(function() {
return false;
};
$('#postsubmit').click(function(){
// your ajax request here
});
As @Sugrue I'm also digging out an old thread.
To explain why there is 32768 (I think it should be 32767, but lets believe experimental testing result) characters limitation we need to dig into Windows API.
No matter how you launch program with command line arguments it goes to ShellExecute, CreateProcess or any extended their version. These APIs basically wrap other NT level API that are not officially documented. As far as I know these calls wrap NtCreateProcess, which requires OBJECT_ATTRIBUTES structure as a parameter, to create that structure InitializeObjectAttributes is used. In this place we see UNICODE_STRING
. So now lets take a look into this structure:
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING;
It uses USHORT
(16-bit length [0; 65535]) variable to store length. And according this, length indicates size in bytes, not characters. So we have: 65535 / 2 = 32767
(because WCHAR
is 2 bytes long).
There are a few steps to dig into this number, but I hope it is clear.
Also, to support @sunetos answer what is accepted. 8191 is a maximum number allowed to be entered into cmd.exe
, if you exceed this limit, The input line is too long.
error is generated. So, answer is correct despite the fact that cmd.exe
is not the only way to pass arguments for new process.
One thing to think about is: Do you have your WCF completely uncoupled from the WindowsService (WS)? A WS is painful because you don't have a lot of control or visibility to them. I try to mitigate this by having all of my non-WS stuff in their own classes so they can be tested independently of the host WS. Using this approach might help you eliminate anything that is happening with the WS runtime vs. your service in particular.
John is likely correct that it is a .config file problem. WCF will always look for the execution context .config. So if you are hosting your WCF in different execution contexts (that is, test with a console application, and deploy with a WS), you need to make sure you have WCF configuration data moved over to the proper .config file. But the underlying issue to me is that you don't know what the problem is because the WS goo gets in the way. If you haven't refactored to that yet so that you can run your service in any context (that is, unit test or console), then I'd sugget doing so. If you spun your service up in a unit test, it would likely fail the same way that you are seeing with the WS which is much easier to debug rather than attempting to do so with the yucky WS plumbing.
If you run Ant from eclipse, the eclipse will use jdk or jre that is configured in the class-path(build path).
If you're in control of the string, you could also use a 'Raw' string type:
>>> string = r"abcd\n"
>>> print(string)
abcd\n
@HpTerm answer Kotlin version:
private fun getDataFromAssets(activity: Activity): String {
var bufferedReader: BufferedReader? = null
var data = ""
try {
bufferedReader = BufferedReader(
InputStreamReader(
activity?.assets?.open("Your_FILE.html"),
"UTF-8"
)
) //use assets? directly if in activity
var mLine:String? = bufferedReader.readLine()
while (mLine != null) {
data+= mLine
mLine=bufferedReader.readLine()
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
return data
}
There are a couple of ways:
If you want to use raw Javascript (without a helper like JQuery), then you could do something like:
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";
// and append it to where you'd like it to go:
document.body.appendChild(element);
The other method is to write the link directly into the document:
document.write("<a href='" + link + "'>" + text + "</a>");
without having a to write a function, this will split according to list, in this case 'Mr.|Dr.|Mrs.', select everything after split with [1], then split again and grab whatever element. In the case below, 'Morris' is returned.
re.split('Mr.|Dr.|Mrs.', 'Mr. Morgan Morris')[1].split()[1]
You can not use DATEDIFF
but you can use this (if columns are not date type):
SELECT
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD')
AS DiffDate from dual
Try adding an event listener for clicks:
document.getElementById('button').addEventListener("click", function() {
alert("You clicked me");
}?);?
Using addEventListener
is probably a better idea then setting onclick
- onclick
can easily be overwritten by another piece of code.
You can use a variable to store whether or not the button has been clicked before:
var clicked = false
document.getElementById('button').addEventListener("click", function() {
clicked = true
}?);?
This did the trick for me when I couldn't get the style spacing to work from the span tag:
<p style='margin-bottom: 5px' >
<span>I Agree</span>
</p>
<span>I Don't Agree</span>
In Management Studio, open the Object Explorer.
Views
Script view as > Create To > New query window
and you're done!
If you want to retrieve the SQL statement that defines the view from T-SQL code, use this:
SELECT
m.definition
FROM sys.views v
INNER JOIN sys.sql_modules m ON m.object_id = v.object_id
WHERE name = 'Example_1'
Rather than adding it to every request, you can just add it as a default config like so.
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
In my case JAVA path was not set in Env variables. Started to work after correct path was set in Env PATH.
Type javac in command prompt and make sure JAVA PATH is correct.
Here is how I have done it:
Canvas g = new Canvas( compass );
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
float rotation = display.getOrientation() * 90;
g.translate( -box.left, -box.top );
g.rotate( -bearing - rotation, box.exactCenterX(), box.exactCenterY() );
drawCompass( g, p );
drawNeedle( g, p );
Just because memcpy
doesn't have to deal with overlapping regions, doesn't mean it doesn't deal with them correctly. The call with overlapping regions produces undefined behavior. Undefined behavior can work entirely as you expect on one platform; that doesn't mean it's correct or valid.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
Check this link: http://css-tricks.com/snippets/jquery/smooth-scrolling/ for a demo, I've used it before and it works quite nicely.
Take a look at -
bellow:
>>> from datetime import datetime
>>> datetime.now().strftime('%d-%b-%Y')
>>> '08-Oct-2011'
>>> datetime.now().strftime('%-d-%b-%Y')
>>> '8-Oct-2011'
>>> today = datetime.date.today()
>>> today.strftime('%d-%b-%Y')
>>> print(today)
when you execute the command
php artisan route:list
You will see all your registered routes in there in table format . Well there you see many columns like Method , URI , Name , Action .. etc.
So basically if you are using route() method that means it will accept only name column values and if you want to use URI column values you should go with url() method of laravel.
Simply add the below to your maven project pom.xml flie:
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
solve(c)
does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c
to invoke matrix multiplication in R.
R performs element by element multiplication when you invoke solve(c) * c
.
I also had this problem on OSX. The solution was uncommenting the extension = pgsql.so
in php.ini.default
and deleting the .default
suffix, since the file php.ini
was not there.
If you are using XAMPP, the php.ini file resides in /XAMPP/xampfiles/etc
Short answer
Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Explanation
Despite its name, java.util.Date
represents an instant on the time-line, not a "date". The actual data stored within the object is a long
count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
The equivalent class to java.util.Date
in JSR-310 is Instant
, thus there is a convenient method toInstant()
to provide the conversion:
Date input = new Date();
Instant instant = input.toInstant();
A java.util.Date
instance has no concept of time-zone. This might seem strange if you call toString()
on a java.util.Date
, because the toString
is relative to a time-zone. However that method actually uses Java's default time-zone on the fly to provide the string. The time-zone is not part of the actual state of java.util.Date
.
An Instant
also does not contain any information about the time-zone. Thus, to convert from an Instant
to a local date it is necessary to specify a time-zone. This might be the default zone - ZoneId.systemDefault()
- or it might be a time-zone that your application controls, such as a time-zone from user preferences. Use the atZone()
method to apply the time-zone:
Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
A ZonedDateTime
contains state consisting of the local date and time, time-zone and the offset from GMT/UTC. As such the date - LocalDate
- can be easily extracted using toLocalDate()
:
Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();
Java 9 answer
In Java SE 9, a new method has been added that slightly simplifies this task:
Date input = new Date();
LocalDate date = LocalDate.ofInstant(input.toInstant(), ZoneId.systemDefault());
This new alternative is more direct, creating less garbage, and thus should perform better.
Cloud Computing is For Service Oriented where as Grid Computing is for Application Oriented. Grid computing is used to build Virtual supercomputer using a middler ware to achieve a common task that can be shared among several resources. most probably this task will be kind of computing or data storage.
Cloud computing is providing services over the internet through several servers uses Virtualization.In cloud computing either you can provide service in three types Iaas , Paas, Saas . This will give you solution when you don't have any resources for a short time Business service over the Internet.
I agree with Als that you can not initialize at time of defining the structure in C. But you can initialize the structure at time of creating instance shown as below.
In C,
struct s {
int i;
int j;
};
struct s s_instance = { 10 ,20 };
in C++ its possible to give direct value in definition of structure shown as below
struct s {
int i;
s(): i(10)
{
}
};
Just modify one of the returned entities:
Customer c = (from x in dataBase.Customers
where x.Name == "Test"
select x).First();
c.Name = "New Name";
dataBase.SaveChanges();
Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}
<select>
<optgroup label = "Choose One">
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</optgroup>
</select>
The msysgit FAQ on Git cannot create a filedirectory with a long path doesn't seem up to date, as it still links to old msysgit ticket #110. However, according to later ticket #122 the problem has been fixed in msysgit 1.9, thus:
git config core.longpaths true
So far, it's worked for me very well.
Be aware of important notice in comment on the ticket #122
don't come back here and complain that it breaks Windows Explorer, cmd.exe, bash or whatever tools you're using.
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
no need for the outside events plugin...
just add an event handler to the .ui-widget-overlay div:
jQuery(document).on('click', 'body > .ui-widget-overlay', function(){
jQuery("#ui-dialog-selector-goes-here").dialog("close");
return false;
});
just make sure that whatever selector you used for the jQuery ui dialog, is also called to close it.. i.e. #ui-dialog-selector-goes-here
Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )
If @MyInt > 0
Begin
Print 'There''s something in the table'
End
I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.
I use JAD Decompiler.
There is an Eclipse plugin for it, jadeclipse. It is pretty nice.
I would do something like this
DEMO in JsBin: http://jsbin.com/ofiqur/1/
<a href="#" id="showmenu">Click Here</a>
<div class="menu">
<ul>
<li><a href="#">Button 1</a></li>
<li><a href="#">Button 2</a></li>
<li><a href="#">Button 3</a></li>
</ul>
</div>
and in jQuery as simple as
var min = "-100px", // remember to set in css the same value
max = "0px";
$(function() {
$("#showmenu").click(function() {
if($(".menu").css("marginLeft") == min) // is it left?
$(".menu").animate({ marginLeft: max }); // move right
else
$(".menu").animate({ marginLeft: min }); // move left
});
});
SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )
A starter bash script to list and run a tool against the DBs...
#!/bin/bash
declare -a dbs
unset opt
for each in $(echo "show databases;" | mysql -u root) ;do
dbs+=($each)
done
echo " The system found [ ${#dbs[@]} ] databases." ;sleep 2
echo
echo "press 1 to run a check"
echo "press 2 to run an optimization"
echo "press 3 to run a repair"
echo "press 4 to run check,repair, and optimization"
echo "press q to quit"
read input
case $input in
1) opt="-c"
;;
2) opt="-o"
;;
3) opt="-r"
;;
4) opt="--auto-repair -c -o"
;;
*) echo "Quitting Application .."; exit 7
;;
esac
[[ -z $opt ]] && exit 7;
echo " running option: mysqlcheck $opt in 5 seconds on all Dbs... "; sleep 5
for ((i=0; i<${#dbs[@]}; i++)) ;do
echo "${dbs[$i]} : "
mysqlcheck $opt ${dbs[$i]} -u root
done
And if you add an alias for it then it's even better right?
git config --global alias.nccommit 'commit -a --allow-empty-message -m ""'
Now you just do an nccommit, nc because of no comment, and everything should be commited.
This will only work if you want to compare exact strings. It will not work in case you want to check if the column string contains any of the strings in the list.
The right way to compare with a list would be :
searchfor = ['john', 'doe']
df = df[~df.col.str.contains('|'.join(searchfor))]
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Define it as
<return type> AnalyzeArray(ArrayList<Integer> list) {
Goto the project repo, right click -> 'Git Bash Here'
In the git bash windows type
cd ~
pwd
i get something like this
/c/Users/<windows_username>
Now copy your public and private keys to this path
C:\Users\<windows_username>\.ssh
i got the below files there
id_rsa
id_rsa.pub
known_hosts
here
Now when ever it needs to use the credentials it uses these files and prompt for password if needed.
dict.keys()
Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.
That's why you see the indices 0 to 7 in the first column. They are produced by enumerate
and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.
In my mind true way is:
# add READ permission to all directories and files under your DocumentRoot
sudo chmod +r /path/to/DocumentRoot/ -R
# add EXECUTE permission to all DIRECTORIES under your DocumentRoot
find /path/to/DocumentRoot/ -type d -exec chmod +x {} \;
If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.
Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time.
This is the same question as Failed to connect to mailserver at "localhost" port 25
also check this php mail function not working
You can use something like this
if ($("#formID input:checkbox:checked").length > 0)
{
// any one is checked
}
else
{
// none is checked
}
Follow the below steps
From feature/branch (enter the below command)
git checkout master
git pull
git checkout feature/branchname
git merge master
Yes, you understood correctly.
CountDownLatch
works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch
.
Any thread, usually the main thread of the application, which calls CountDownLatch.await()
will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown()
once they are completed or ready.
As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch
is that it's not reusable: once count reaches zero you cannot use CountDownLatch
any more.
Edit:
Use CountDownLatch
when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.
A classical example of using CountDownLatch
in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.
P.S. OP's question has a pretty straightforward example so I didn't include one.
As I needed get all elements in a nice way I encountered this SO subject "Traversing 2 dimensional associative array/object" - no matter the name for me, because functionality counts.
var imgs_pl = {
'offer': { 'img': 'wer-handwritter_03.png', 'left': 1, 'top': 2 },
'portfolio': { 'img': 'wer-handwritter_10.png', 'left': 1, 'top': 2 },
'special': { 'img': 'wer-handwritter_15.png', 'left': 1, 'top': 2 }
};
for (key in imgs_pl) {
console.log(key);
for (subkey in imgs_pl[key]) {
console.log(imgs_pl[key][subkey]);
}
}
You can handle popup window or alert box:
Alert alert = driver.switchTo().alert();
alert.accept();
You can also decline the alert box:
Alert alert = driver.switchTo().alert();
alert().dismiss();
If you have phpMyAdmin installed, you can follow the instructions given in the following link: https://mediatemple.net/community/products/dv/204403914/default-mysql-character-set-and-collation You have to match the collate of the database with that of all the tables, as well as the fields of the tables and then recompile all the stored procedures and functions. With that everything should work again.
There is no direct method,
Rename Local Branch,
My current branch is master
git branch -m master_renamed
#master_renamed is new name of master
Delete remote branch,
git push origin --delete master
#origin is remote_name
Push renamed branch into remote,
git push origin master_renamed
That's it...
Try this:
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
You can also use a regular expression to explicitly detect uppercase roman alphabetical characters.
isUpperCase = function(char) {
return !!/[A-Z]/.exec(char[0]);
};
EDIT: the above function is correct for ASCII/Basic Latin Unicode, which is probably all you'll ever care about. The following version also support Latin-1 Supplement and Greek and Coptic Unicode blocks... In case you needed that for some reason.
isUpperCase = function(char) {
return !!/[A-ZÀ-ÖØ-Þ??-??-?????????????-?]/.exec(char[0]);
};
This strategy starts to fall down if you need further support (is ? uppercase?) since some blocks intermix upper and lowercase characters.
Application.Exit
is for Windows Forms applications - it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn't necessarily force the application to exit.
Environment.Exit
is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.
In general you should use Application.Exit
in Windows Forms applications and Environment.Exit
in console applications, (although I prefer to let the Main
method / entry point run to completion rather than call Environment.Exit
in console applications).
For more detail see the MSDN documentation.
UPDATED It works fine in my case:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)
Just changed in 2020. Works fine for me.
it's should overlap, so it turned off. Try to open in your text editor and find display_errors
and turn it on. It works for me
Whenever you want to execute an SQL statement that shouldn't return a value or a record set, the ExecuteNonQuery should be used.
So if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement. This sounds very nice, but whenever you use the SQL Server 2005 IDE or Visual Studio to create a stored procedure it adds a small line that ruins everything.
That line is: SET NOCOUNT ON; This line turns on the NOCOUNT feature of SQL Server, which "Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results" and therefore it makes the stored procedure always to return -1 when called from the application (in my case a web application).
In conclusion, remove that line from your stored procedure, and you will now get a value indicating the number of rows affected by the statement.
Happy programming!
While awk
's printf
can be used, you may want to look into pr
or (on BSDish systems) rs
for formatting.
Version 1 is certainly easier on the eyes, clearer as to your intentions, and easier to add case-conditions to.
I've never tried the second version. In many languages, this wouldn't even compile because each case labels has to evaluate to a constant-expression.
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
Use the range
type. If the user enter a date:
select *
from table
where
update_date
<@
tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');
If the user enters timestamps then you don't need the ::date + 1
part
http://www.postgresql.org/docs/9.2/static/rangetypes.html
http://www.postgresql.org/docs/9.2/static/functions-range.html
Flat files do not allow providing meta information.
I would suggest writing out a HTML table containing the information you need, and let Excel read it instead. You can then use <b> tags to do what you ask for.
Your original attempt to span both tables creates an implicit JOIN. This is frowned upon by most experienced SQL programmers because it separates the tables to be combined with the condition of how.
The UNION
is a good solution for the tables as they are, but there should be no reason they can't be put into the one table with decent indexing. I've seen adding the correct index to a large table increase query speed by three orders of magnitude.
I would first want to know what you are trying to accomplish here to need an argument to be passed to new Runnable() or to run(). The usual way should be to have a Runnable object which passes data(str) to its threads by setting member variables before starting. The run() method then uses these member variable values to do execute someFunc()
With React 16.8. We can do this with hooks like the following example
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const options = [
"Monty Python and the Holy Grail",
"Monty Python's Life of Brian",
"Monty Python's The Meaning of Life"
];
const filmsByTati = [
{
id: 1,
title: "Jour de fête",
releasedYear: 1949
},
{
id: 2,
title: "Play time",
releasedYear: 1967
},
{
id: 3,
releasedYear: 1958,
title: "Mon Oncle"
}
];
const [selectedOption, setSelectedOption] = useState(options[0]);
const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
return (
<div className="App">
<h1>Select Example</h1>
<select
value={selectedOption}
onChange={(e) => setSelectedOption(e.target.value)}
>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
<span>Selected option: {selectedOption}</span>
<select
value={selectedTatiFilm}
onChange={(e) =>
setSelectedTatiFilm(
filmsByTati.find(film => (film.id == e.target.value))
)
}
>
{filmsByTati.map((film) => (
<option key={film.id} value={film.id}>
{film.title}
</option>
))}
</select>
<span>Selected option: {selectedTatiFilm.title}</span>
</div>
);
}
As answered above:
//Parent[@id='1']/Children/child/@name
will only output the name
attribute of the 4 child
nodes belonging to the Parent
specified by its predicate [@id=1]
. You'll then need to change the predicate to [@id=2]
to get the set of child
nodes for the next Parent
.
However, if you ignore the Parent
node altogether and use:
//child/@name
you can select name
attribute of all child
nodes in one go.
name="Child_2"
name="Child_4"
name="Child_1"
name="Child_3"
name="Child_1"
name="Child_2"
name="Child_4"
name="Child_3"
this works
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(soapResponse.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
System.out.println(sw.toString());
return sw.toString();
I added this to the Button of a datagrid to get the values of the cells in the row that the user is clicking:
string DGCell = dataGridView1.Rows[e.RowIndex].Cells[X].Value.ToString();
where X is the cell you want to check. Datagrid column count starts at 1 not 0 in my case. Not sure if it is default of a datagrid or because I am using SQL to populate the info.
Adding following property to your persistence.xml may solve your problem temporarily
<property name="hibernate.enable_lazy_load_no_trans" value="true" />
As @vlad-mihalcea said it's an antipattern and does not solve lazy initialization issue completely, initialize your associations before closing transaction and use DTOs instead.
includes() is not supported by most browsers. Your options are either to use
-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
or to use
-indexof()
var str = "abcde";
var n = str.indexOf("cd");
Which gives you n=2
This is widely supported.
Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,
package main
import "fmt"
func main() {
fmt.Println(string("Hello"[1])) // ASCII only
fmt.Println(string([]rune("Hello, ??")[1])) // UTF-8
fmt.Println(string([]rune("Hello, ??")[8])) // UTF-8
}
Output:
e
e
?
Read:
Go Programming Language Specification section on Conversions.
... What about using Apache's FileFilters from:
org.apache.commons.io
?
just like:
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
...
File dir = new File(".");
String[] filters = { "*.txt"};
IOFileFilter wildCardFilter = new WildcardFileFilter(filters, IOCase.INSENSITIVE);
String[] files = dir.list( wildCardFilter );
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
Have you converted your data from string to JavaScript object?
You can do it with data = eval('(' + string_data + ')');
or, which is safer, data = JSON.parse(string_data);
but later will only works in FF 3.5 or if you include json2.js
jQuery since 1.4.1 also have function for that, $.parseJSON()
.
But actually, $.getJSON()
should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.
You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.
Try something like this:
declare @query varchar(max);
set @query = 'create database TEST...';
exec (@query);
Some time java.lang.NoClassDefFoundError: error appear when use ART instead of Dalvik runtime. To change runtime just go to Developer Option -> Select Runtime -> Dalvik.
Using os.path.getsize
:
>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611
The output is in bytes.
It's also possible letting a ServletContextListener set the System properties:
import java.util.Enumeration;
import javax.servlet.*;
public class SystemPropertiesHelper implements
javax.servlet.ServletContextListener {
private ServletContext context = null;
public void contextInitialized(ServletContextEvent event) {
context = event.getServletContext();
Enumeration<String> params = context.getInitParameterNames();
while (params.hasMoreElements()) {
String param = (String) params.nextElement();
String value =
context.getInitParameter(param);
if (param.startsWith("customPrefix.")) {
System.setProperty(param, value);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
And then put this into your web.xml (should be possible for context.xml too)
<context-param>
<param-name>customPrefix.property</param-name>
<param-value>value</param-value>
<param-type>java.lang.String</param-type>
</context-param>
<listener>
<listener-class>servletUtils.SystemPropertiesHelper</listener-class>
</listener>
It worked for me.
$.get('http://www.your_domain.com/image.jpg', imgLoaded);
function imgLoaded(){
console.log(this, 'loaded');
}
Better to return HttpResponseMessage with StreamContent inside of it.
Here is example:
public HttpResponseMessage GetFile(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string fileName;
string localFilePath;
int fileSize;
localFilePath = getFileFromID(id, out fileName, out fileSize);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).
If you have a very limited number of levels, you could try converting y
into factor and change its levels.
> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
x y w
1 1 1 good
2 2 4 fair
3 4 5 bad
In Jenkins , we have the format is as:
Minute(0-59) Hour(0-23) Day(1-7) Month(1-12) Day of the Week
As discussed in the comments you have based your code on this solution: https://stackoverflow.com/a/8825714/681807
One of the key parts of this solution is to add height: 100%
to html, body
so the #footer
element has a base height to work from - this is missing from your code:
html,body{
height: 100%
}
You will also find that you will run into problems with using bottom: -50px
as this will push your content under the fold when there isn't much content. You will have to add margin-bottom: 50px
to the last element before the #footer
.
Actually the error is being generated by the initMap in the Google's api script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
so basically when the Google Map API is loaded then the initMap function is executed. If you don't have an initMap function, then the initMap is not a function error is generated.
So basically what you have to do is one of the following options:
&callback=angular.noop
if you just want an empty function() (only if you use angular)In .NET 4.5 it's possible to bind to static properties, read more
You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:
public static event EventHandler MyPropertyChanged;
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.
It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.
use this, it realy works:
data.addColumn no of your key, you can add more columns or remove
<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable();
data.addColumn("string", "YEAR");
data.addColumn("number", "NO of record");
data.addRows(<?php $data ?>);
]);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Better way till now:
If you give display:inline-block; to inner divs then child elements of inner divs will also get this property and disturb alignment of inner divs.
Better way is to use two different classes for inner divs with width, margin and float.
Best way till now:
Use flexbox.
This code can help you :
$(document).ready(function() {
$('#calendar').fullCalendar({
events:
[
{
id: 1,
title: 'First Event',
start: ...,
end: ...,
description: 'first description'
},
{
id: 2,
title: 'Second Event',
start: ...,
end: ...,
description: 'second description'
}
],
eventRender: function(event, element) {
element.find('.fc-title').append("<br/>" + event.description);
}
});
}
You mentioned in another comment that you aren't expecting your get_userdata() function to return an stdClass object? If that is the case, you should mind this line in that function:
return $query->row();
Here, the CodeIgniter database object "$query" has its row() method called which returns an stdClass. Alternately, you could run row_array() which returns the same data in array form.
Anyway, I strongly suspect that this isn't the root cause of the problem. Can you give us some more details, perhaps? Play around with some things and let us know how it goes. We can't play with your code, so it's hard to say exactly what's going on.
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
Also:
angular.module('App.filters', [])
.filter('joinBy', function () {
return function (input,delimiter) {
return (input || []).join(delimiter || ',');
};
});
And in template:
{{ itemsArray | joinBy:',' }}
You can achieve LinearLayout cascading like this:
LinearLayout root = (LinearLayout) findViewById(R.id.my_root);
LinearLayout llay1 = new LinearLayout(this);
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);
llay1.addView(llay2);
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5}
will map to {false, true, false, true, false}
.
This is what I did
You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.
Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.
You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.
The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.
You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.
Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.
But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).
You should provide @2x images for the Retina Macbook Pro and future Retina Macs.
Age (full years) of the Person:
SELECT
TRUNC(months_between(sysdate, per.DATE_OF_BIRTH) / 12) AS "Age"
FROM PD_PERSONS per
$('#newType option:first').prop('selected', true);
Common cause for this error is WebDAV. Make sure you uninstall it.
I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.
Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_refresh) {
Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
return true;
} else if (id == R.id.action_map) {
Log.d(APP_TAG, "onOptionsItemSelected Map selected");
Intent intent = new Intent(this, MapsMarkerActivity.class);
intent.putExtra("CITY_NAME", CITY);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public class MapsMarkerActivity extends AppCompatActivity
implements OnMapReadyCallback {
private String cityName = "";
private double longitude;
private double latitude;
static final int numberOptions = 10;
String [] optionArray = new String[numberOptions];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_map);
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Test whether geocoder is present on platform
if(Geocoder.isPresent()){
cityName = getIntent().getStringExtra("CITY_NAME");
geocodeLocation(cityName);
} else {
String noGoGeo = "FAILURE: No Geocoder on this platform.";
Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
return;
}
}
/**
* Manipulates the map when it's available.
* The API invokes this callback when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user receives a prompt to install
* Play services inside the SupportMapFragment. The API invokes this method after the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(latitude, longitude);
// If cityName is not available then use
// Default Location.
String markerDisplay = "Default Location";
if (cityName != null
&& cityName.length() > 0) {
markerDisplay = "Marker in " + cityName;
}
googleMap.addMarker(new MarkerOptions().position(sydney)
.title(markerDisplay));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
/**
* Method to geocode location passed as string (e.g., "Pentagon"), which
* places the corresponding latitude and longitude in the variables lat and lon.
*
* @param placeName
*/
private void geocodeLocation(String placeName){
// Following adapted from Conder and Darcey, pp.321 ff.
Geocoder gcoder = new Geocoder(this);
// Note that the Geocoder uses synchronous network access, so in a serious application
// it would be best to put it on a background thread to prevent blocking the main UI if network
// access is slow. Here we are just giving an example of how to use it so, for simplicity, we
// don't put it on a separate thread. See the class RouteMapper in this package for an example
// of making a network access on a background thread. Geocoding is implemented by a backend
// that is not part of the core Android framework, so we use the static method
// Geocoder.isPresent() to test for presence of the required backend on the given platform.
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gcoder.getFromLocationName(placeName, numberOptions);
} else {
Log.i(MainActivity.APP_TAG, "No Geocoder found");
return;
}
Iterator<Address> locations = results.iterator();
String raw = "\nRaw String:\n";
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
if(opCount == 0 && location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
country = location.getCountryName();
if(country == null) {
country = "";
} else {
country = ", " + country;
}
raw += location+"\n";
optionArray[opCount] = location.getAddressLine(0)+", "
+location.getAddressLine(1)+country+"\n";
opCount ++;
}
// Log the returned data
Log.d(MainActivity.APP_TAG, raw);
Log.d(MainActivity.APP_TAG, "\nOptions:\n");
for(int i=0; i<opCount; i++){
Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
}
Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
} catch (Exception e){
Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
}
}
}
Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753
I was able to solve this problem with these steps:
Excellent answer! I do have a small addition. Regarding this solution:
TypedQuery<CustomObject> typedQuery = em.createQuery(query , String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=100";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();CustomObject.class);
To prevent a class not found error simply insert the full package name. Assuming org.company.directory is the package name of CustomObject:
String query = "SELECT NEW org.company.directory.CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();
Yes, you can do that, but only if #b
is after #a
in the HTML.
If #b
comes immediately after #a
: http://jsfiddle.net/u7tYE/
#a:hover + #b {
background: #ccc
}
<div id="a">Div A</div>
<div id="b">Div B</div>
That's using the adjacent sibling combinator (+
).
If there are other elements between #a
and #b
, you can use this: http://jsfiddle.net/u7tYE/1/
#a:hover ~ #b {
background: #ccc
}
<div id="a">Div A</div>
<div>random other elements</div>
<div>random other elements</div>
<div>random other elements</div>
<div id="b">Div B</div>
That's using the general sibling combinator (~
).
Both +
and ~
work in all modern browsers and IE7+
If #b
is a descendant of #a
, you can simply use #a:hover #b
.
ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.
it can be achieved 2 ways:
Mark the POJO to ignore unknown properties
@JsonIgnoreProperties(ignoreUnknown = true)
Configure ObjectMapper that serializes/De-serializes the POJO/json as below:
ObjectMapper mapper =new ObjectMapper();
// for Jackson version 1.X
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// for Jackson version 2.X
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
Instead of numpy or scipy, I would recommend pandas to do this more swiftly:
df['data'].rolling(3).mean()
This takes the moving average (MA) of 3 periods of the column "data". You can also calculate the shifted versions, for example the one that excludes the current cell (shifted one back) can be calculated easily as:
df['data'].shift(periods=1).rolling(3).mean()
svn revert filename
this should revert a single file.
Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...
The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...
Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)
This command brew install maven30
didn't work for me. Was complaining about a missing FORMULA. But the following command did work. I've got maven-3.0.5 installed.
brew install homebrew/versions/maven30
This is for Mac OS X 10.9 aka Mavericks.
Intent intent = new Intent("com.my.package.MY_UNIQUE_ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
sqlitewraper.context, 0, intent,
PendingIntent.FLAG_NO_CREATE);
FLAG_NO_CREATE is not create pending intent so that it gives boolean value false.
boolean alarmUp = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
new Intent("com.my.package.MY_UNIQUE_ACTION"),
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
System.out.print("k");
}
AlarmManager alarmManager = (AlarmManager) sqlitewraper.context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 1000 * 60, pendingIntent);
After the AlarmManager check the value of Pending Intent it gives true because AlarmManager Update The Flag of Pending Intent.
boolean alarmUp1 = (PendingIntent.getBroadcast(sqlitewraper.context, 0,
new Intent("com.my.package.MY_UNIQUE_ACTION"),
PendingIntent.FLAG_UPDATE_CURRENT) != null);
if (alarmUp1) {
System.out.print("k");
}
Your script should look like:
prog1 &
prog2 &
.
.
progn &
wait
progn+1 &
progn+2 &
.
.
Assuming your system can take n jobs at a time. use wait to run only n jobs at a time.
using javascript:
here input element is used
<input type="text" id="fname" onkeyup="javascript:console.log(window.event.key)">
if you want to use multiline code use curly braces after javascript:
<input type="text" id="fname" onkeyup="javascript:{ console.log(window.event.key); alert('hello'); }">
For OP's terminal Cmder
there is an integration guide, also hinted in the VS Code docs.
If you want to use VS Code tasks and encounter problems after switch to Cmder
, there is an update to @khernand's answer. Copy this into your settings.json
file:
"terminal.integrated.shell.windows": "cmd.exe",
"terminal.integrated.env.windows": {
"CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
},
"terminal.integrated.shellArgs.windows": [
"/k",
"%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
// OLD: "%CMDER_ROOT%\\vendor\\init.bat"
],
The invoked file will open Cmder
as integrated terminal and switch to cmd
for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json
to make tasks work.
Starting with VS Code 1.38, there is also "terminal.integrated.automationShell.windows"
setting, which lets you set your terminal for tasks globally and avoids issues with Cmder
.
"terminal.integrated.automationShell.windows": "cmd.exe"
Expires
and Cache-Control
are "strong caching headers"
Last-Modified
and ETag
are "weak caching headers"
First the browser check Expires/Cache-Control
to determine whether or not to make a request to the server
If have to make a request, it will send Last-Modified/ETag
in the HTTP request. If the Etag
value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.
This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.
Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.
I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).
Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.
<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%
response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );
// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());
// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );
// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
background = stamperDoc.getUnderContent(i);
background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close();
%>
There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.
// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();
Using recursion
for i in range(100):
def do():
try:
## Network related scripts
except SpecificException as ex:
do()
do() ## invoke do() whenever required inside this loop
I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.
Original Repository
where the pull request has been submitted to.Pull requests
tabClose Pull Request
buttonGotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
If you need to loop through child elements recursively:
function recursiveEach($element){
$element.children().each(function () {
var $currentElement = $(this);
// Show element
console.info($currentElement);
// Show events handlers of current element
console.info($currentElement.data('events'));
// Loop her children
recursiveEach($currentElement);
});
}
// Parent div
recursiveEach($("#div"));
NOTE: In this example I show the events handlers registered with an object.
I created an Oracle function that returns a table of numbers
CREATE OR REPLACE FUNCTION [schema].FN_TABLE_NUMBERS(
NUMINI INTEGER,
NUMFIN INTEGER,
EXPONENCIAL INTEGER DEFAULT 0
) RETURN TBL_NUMBERS
IS
NUMEROS TBL_NUMBERS;
INDICE NUMBER;
BEGIN
NUMEROS := TBL_NUMBERS();
FOR I IN (
WITH TABLA AS (SELECT NUMINI, NUMFIN FROM DUAL)
SELECT NUMINI NUM FROM TABLA UNION ALL
SELECT
(SELECT NUMINI FROM TABLA) + (LEVEL*TO_NUMBER('1E'||TO_CHAR(EXPONENCIAL))) NUM
FROM DUAL
CONNECT BY
(LEVEL*TO_NUMBER('1E'||TO_CHAR(EXPONENCIAL))) <= (SELECT NUMFIN-NUMINI FROM TABLA)
) LOOP
NUMEROS.EXTEND;
INDICE := NUMEROS.COUNT;
NUMEROS(INDICE):= i.NUM;
END LOOP;
RETURN NUMEROS;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NUMEROS;
WHEN OTHERS THEN
RETURN NUMEROS;
END;
/
Is necessary create a new data type:
CREATE OR REPLACE TYPE [schema]."TBL_NUMBERS" IS TABLE OF NUMBER;
/
Usage:
SELECT COLUMN_VALUE NUM FROM TABLE([schema].FN_TABLE_NUMBERS(1,10))--integers difference: 1;2;.......;10
And if you need decimals between numbers by exponencial notation:
SELECT COLUMN_VALUE NUM FROM TABLE([schema].FN_TABLE_NUMBERS(1,10,-1));--with 0.1 difference: 1;1.1;1.2;.......;10
SELECT COLUMN_VALUE NUM FROM TABLE([schema].FN_TABLE_NUMBERS(1,10,-2));--with 0.01 difference: 1;1.01;1.02;.......;10
Say your column names are dynamic, you can create an empty row-named matrix and transform it to a data frame.
nms <- sample(LETTERS,sample(1:10))
as.data.frame(t(matrix(nrow=length(nms),ncol=0,dimnames=list(nms))))
Consider using JSONPath
https://packagist.org/packages/flow/jsonpath
There is a pretty clear explanation of how to use it and parse a JSON-file avoiding all the loops proposed. If you are familiar with XPath
for XML
you will start loving this approach.
You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN
operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN
would be faster; however, in actual testing they performed the same.
@firedrawndagger: to list field names/column headers iterate through the recordset Fields collection and insert the name:
Dim myRS as ADODB.Recordset
Dim fld as Field
Dim strFieldName as String
For Each fld in myRS.Fields
Activesheet.Selection = fld.Name
[Some code that moves to next column]
Next
Extension of Mumthezir's version that works better on iOS, based on Mathijs Segers' comment:
(Uses some AngularJS but hopefully you get the idea.)
<label style='position:relative'>
<input type="date"
name="dateField"
onfocus="(this.type='date')"
ng-focus="dateFocus=true" ng-blur="dateFocus=false" />
<span ng-if='!dateFocus && !form.date' class='date-placeholder'>
Enter date
</span>
</label>
Because it's all wrapped in a label
, clicking the span
automatically focuses the input
.
CSS:
.date-placeholder {
display: inline-block;
position: absolute;
text-align: left;
color: #aaa;
background-color: white;
cursor: text;
/* Customize this stuff based on your styles */
top: 4px;
left: 4px;
right: 4px;
bottom: 4px;
line-height: 32px;
padding-left: 12px;
}
Calculate Leave working days in a table column as a default value--updated
If you are using SQL here is the query which can help you: http://gallery.technet.microsoft.com/Calculate...
double[,]
is a 2d array (matrix) while double[][]
is an array of arrays (jagged arrays) and the syntax is:
double[][] ServicePoint = new double[10][];
You can do
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right|center"//or "center_vertical" for center text
android:layoutDirection="rtl"
android:text="hello" />
Following line is enough
android:layoutDirection="rtl"
jQuery: you think a lot about 'QUERYing the DOM' for DOM elements and doing something.
AngularJS: THE model is the truth, and you always think from that ANGLE.
For example, when you get data from THE server which you intend to display in some format in the DOM, in jQuery, you need to '1. FIND' where in the DOM you want to place this data, the '2. UPDATE/APPEND' it there by creating a new node or just setting its innerHTML. Then when you want to update this view, you then '3. FIND' the location and '4. UPDATE'. This cycle of find and update all done within the same context of getting and formatting data from server is gone in AngularJS.
With AngularJS you have your model (JavaScript objects you are already used to) and the value of the model tells you about the model (obviously) and about the view, and an operation on the model automatically propagates to the view, so you don't have to think about it. You will find yourself in AngularJS no longer finding things in the DOM.
To put in another way, in jQuery, you need to think about CSS selectors, that is, where is the div
or td
that has a class or attribute, etc., so that I can get their HTML or color or value, but in AngularJS, you will find yourself thinking like this: what model am I dealing with, I will set the model's value to true. You are not bothering yourself of whether the view reflecting this value is a checked box or resides in a td
element (details you would have often needed to think about in jQuery).
And with DOM manipulation in AngularJS, you find yourself adding directives and filters, which you can think of as valid HTML extensions.
One more thing you will experience in AngularJS: in jQuery you call the jQuery functions a lot, in AngularJS, AngularJS will call your functions, so AngularJS will 'tell you how to do things', but the benefits are worth it, so learning AngularJS usually means learning what AngularJS wants or the way AngularJS requires that you present your functions and it will call it accordingly. This is one of the things that makes AngularJS a framework rather than a library.
If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:
<div class="text_div">
This div <span>contains</span> some text.
</div>
You can then easily change its contents with jQuery:
$('.text_div > span').text('hello everyone');
If you can't wrap it in a span tag, you could use regular expressions.
ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?
Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.
hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost
...and many others...
Usage:
hosts - run hosts command interpreter
hosts <command> <params> - execute hosts command
Commands:
add <host> <aliases> <addr> # <comment> - add new host
set <host|mask> <addr> # <comment> - set ip and comment for host
rem <host|mask> - remove host
on <host|mask> - enable host
off <host|mask> - disable host
view [all] <mask> - display enabled and visible, or all hosts
hide <host|mask> - hide host from 'hosts view'
show <host|mask> - show host in 'hosts view'
print - display raw hosts file
format - format host rows
clean - format and remove all comments
rollback - rollback last operation
backup - backup hosts file
restore - restore hosts file from backup
recreate - empty hosts file
open - open hosts file in notepad
Just having final
will have the intended effect.
final int x = 5;
...
x = 10; // this will cause a compilation error because x is final
Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x
Use this it will work,
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="a"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var m = document.getElementById("a").value;
var n = document.getElementById("b").value;
var sum = m + n;
alert(sum);
}
</script>
</body>
I can see what @Þaw mentioned :
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.
Next you need to use them as below:
$ENROLLEES->query();
$ENROLLEES->result();
and
$ACCOUNTS->query();
$ACCOUNTS->result();
Instead of using
$this->db->query();
$this->db->result();
See this for reference: http://ellislab.com/codeigniter/user-guide/database/connecting.html
If you want to use sha-256 (guid would be faster) then you would need to do something like
SHA256 shaAlgorithm = new SHA256Managed();
byte[] shaDigest = shaAlgorithm.ComputeHash(ASCIIEncoding.ASCII.GetBytes(url));
return BitConverter.ToString(shaDigest);
Of course, it doesn't have to ascii and it can be any other kind of hashing algorithm as well
If you can get their timezone offset, you can just add it to the current timestamp and then use the gmdate function to get their local time.
// let's say they're in the timezone GMT+10
$theirOffset = 10; // $_GET['offset'] perhaps?
$offsetSeconds = $theirOffset * 3600;
echo gmdate("l", time() + $offsetSeconds);
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
The best way Using dirname(). Because SERVER['DOCUMENT_ROOT'] not working all servers, and also return server running path.
$root = dirname( __FILE__ );
$root = __DIR__;
$filePath = realpath(dirname(__FILE__));
$rootPath = realpath($_SERVER['DOCUMENT_ROOT']);
$htmlPath = str_replace($root, '', $filePath);
You could try:
<html>
<head>
<style>
#main {
width: 500; /*Set to whatever*/
height: 500;/*Set to whatever*/
}
</style>
</head>
<body id="main">
</body>
</html>
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.
Here is a solution under 19API lvl:
First of all. Make a Gson obj. --> Gson gson = new Gson();
Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)
YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);
try this:
OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
U can use direct
$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")
-> Here u can use direct string
String all = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String strLine;
while ((strLine = br.readLine()) != null){
all = all + strLine;
}
} catch (IOException e) {
Log.e("notes_err", e.getLocalizedMessage());
}
you may use
ImageSourceConverter class
to get what you want
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
but select-String doesn't seem to have this option.
Correct. PowerShell is not a clone of *nix shells' toolset.
However it is not hard to build something like it yourself:
$regexes = Get-Content RegexFile.txt |
Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }
$fileList | Get-Content | Where-Object {
foreach ($r in $regexes) {
if ($r.IsMatch($_)) {
$true
break
}
}
$false
}
Following worked for me:
CSS
.round {
border-radius: 50%;
overflow: hidden;
width: 30px;
height: 30px;
background: no-repeat 50%;
object-fit: cover;
}
.round img {
display: block;
height: 100%;
width: 100%;
}
HTML
<div class="round">
<img src="test.png" />
</div>
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:
Generic dictionaries in .NET are not thread-safe and they sometimes might throw a NullReference
or even (more frequent) a KeyNotFoundException
when you try to access a key from two concurrent threads. The exception is quite misleading in this case.
If a NullReferenceException
is thrown by unsafe
code, you might look at your pointer variables, and check them for IntPtr.Zero
or something. Which is the same thing ("null pointer exception"), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.
(Another reason for non-using unsafe code unless you need it, by the way)
This edge case is software-specific and pertains to Visual Studio 2019 IDE (and possibly earlier versions).
Method to reproduce the problem: drag any component from the Toolbox to a Windows form on a non-primary monitor with different DPI setting than the primary monitor, and you get a pop-up with “Object reference not set to an instance of an object.” According to this thread this issue has been known for quite some time and at the time of writing it still hasn't been fixed.
In Python you don't use getters or setters or properties just for the fun of it. You first just use attributes and then later, only if needed, eventually migrate to a property without having to change the code using your classes.
There is indeed a lot of code with extension .py that uses getters and setters and inheritance and pointless classes everywhere where e.g. a simple tuple would do, but it's code from people writing in C++ or Java using Python.
That's not Python code.
Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:
<div class="flexslider" style="height: 330px;">
<ul class="slides">
<li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
<li class="post-65><img src="http://localhost/..../banner_image_2.jpg "></li>
<li class="post-67 ">
<div class="fluid-width-video-wrapper ">
<iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
</div>
</li>
</ul>
</div>
Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.
Following is my JS file:
jQuery(document).ready(function($){
jQuery(".flexslider").click(function (e) {
setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated
});
});
function checkiframe(){
var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
console.log(iframe_flag);
var tooglePlay=0;
if (iframe_flag) { //If Visible then AutoPlaying the Video
tooglePlay=1;
setTimeout(toogleVideo, 1000); //Also using timeout here
}
if (!iframe_flag) {
tooglePlay =0;
setTimeout(toogleVideo('hide'), 1000);
}
}
function toogleVideo(state) {
var div = document.getElementsByTagName("iframe")[0].contentWindow;
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
};
Also, as a simpler example, check this out on JSFiddle
/etc/services
is only advisory, it's a listing of well-known ports. It doesn't mean that anything is actually running on that port or that the named service will run on that port.
In PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433.
You can see what is actually running using the netstat
tool (available on OS X, Windows, and Linux, with command line syntax varying across all three).
This is further complicated on Mac OS X systems by the horrible mess of different PostgreSQL packages - Apple's ancient version of PostgreSQL built in to the OS, Postgres.app, Homebrew, Macports, the EnterpriseDB installer, etc etc.
What ends up happening is that the user installs Pg and starts a server from one packaging, but uses the psql
and libpq
client from a different packaging. Typically this occurs when they're running Postgres.app or homebrew Pg and connecting with the psql
that shipped with the OS. Not only do these sometimes have different default ports, but the Pg that shipped with Mac OS X has a different default unix socket path, so even if the server is running on the same port it won't be listening to the same unix socket.
Most Mac users work around this by just using tcp/ip with psql -h localhost
. You can also specify a port if required, eg psql -h localhost -p 5433
. You might have multiple PostgreSQL instances running so make sure you're connecting to the right one by using select version()
and SHOW data_directory;
.
You can also specify a unix socket directory; check the unix_socket_directories
setting of the PostgreSQL instance you wish to connect to and specify that with psql -h
, e.g.psql -h /tmp
.
A cleaner solution is to correct your system PATH
so that the psql
and libpq
associated with the PostgreSQL you are actually running is what's found first on the PATH
. The details of that depend on your Mac OS X version and which Pg packages you have installed. I don't use Mac and can't offer much more detail on that side without spending more time than is currently available.
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
Joining elements in a list space separated:
word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
joined_string = w + joined_string + " "
print(joined_string.rstrim())
In my case I was sending in correct object in ResponseEntity<>().
Correct :
@PostMapping(value = "/get-customer-details", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getCustomerDetails(@RequestBody String requestMessage) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("customerId", "123");
jsonObject.put("mobileNumber", "XXX-XXX-XXXX");
return new ResponseEntity<>(jsonObject.toString(), HttpStatus.OK);
}
Incorrect :
return new ResponseEntity<>(jsonObject, HttpStatus.OK);
Because, jsonObject's toString() method "Encodes the jsonObject as a compact JSON string". Therefore, Spring returns json string directly without any further serialization.
When we send jsonObject instead, Spring tries to serialize it based on produces method used in RequestMapping and fails due to it "Could not find acceptable representation".
Adding a new answer in here because previous answers weren't explaining the issue I had. Problem is that the username required in SQL is the NAME of the app pool, and not its identity.
I ran in IIS with AppPools set to the ApplicationPoolIdentity
identity.
My SQL Security User name with access was called IIS APPPOOL\DefaultAppPool
and it was working fine with a ASP.NET Full Framework .net application.
When launching my ASP.NET Core application, it created a new AppPool with the application name, but no CLR version and still using the same ApplicationPoolIdentity
identity.
But after looking at the user name used via System.Security.Principal.WindowsIdentity.GetCurrent().Name
, I realized it isn't using DefaultAppPool, but the new app pool name. So I had to add a new user called IIS APPPOOL\ApplicationName
in the SQL security tab, and not the default.
public static Stream ToStream(this Image image)
{
var stream = new MemoryStream();
image.Save(stream, image.RawFormat);
stream.Position = 0;
return stream;
}
This seems to work:
@implementation UINavigationBar (custom)
- (void)drawRect:(CGRect)rect {}
@end
navigationController.navigationBar.backgroundColor = [UIColor clearColor];
Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?
RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'
if it gives error like:
Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.
Check it further:
RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'
BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".
Means either your backup is corrupt or taken from newer version.
You can use:
cat f.csv | sed 's/,/ /g' | awk '{print $1 " / " $4}'
or
echo "Hello,World,Questions,Answers,bash shell,script" | sed 's/,/ /g' | awk '{print $1 " / " $4}'
This is the part that replace comma with space
sed 's/,/ /g'
If you just want to find out the number of elements in an array, use count
. Now, to answer your question...
How to calculate how many items in a foreach?
$i = 0;
foreach ($Contents as $item) {
$item[number];// if there are 15 $item[number] in this foreach, I want get the value : 15
$i++;
}
If you only need the index inside the loop, you could use
foreach($Contents as $index=>$item) {
// $index goes from 0 up to count($Contents) - 1
// $item iterates over the elements
}
For example if you use this code , you can load image from db (mysql) and display it in php5 ;)
<?php
$con =mysql_connect("localhost", "root" , "");
$sdb= mysql_select_db("my_database",$con);
$sql = "SELECT * FROM `news` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s=$row['photo'];
echo $row['photo'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
?>
Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) there is an easier way to simulate form requests. Here is an example:
private async Task<System.IO.Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent fileStreamContent = new StreamContent(paramFileStream);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "param1", "param1");
formData.Add(fileStreamContent, "file1", "file1");
formData.Add(bytesContent, "file2", "file2");
var response = await client.PostAsync(actionUrl, formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStreamAsync();
}
}
I ran into this error after my client PC crashed, the jest --watch
command I was running on the server persisted, and I tried to run jest --watch
again.
The addition to /etc/sysctl.conf
described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node
and kill
it.
You can find a list of formatting escapes on this page.
%d
is a signed integer, while %u
is an unsigned integer. Pointers (when treated as numbers) are usually non-negative.
If you actually want to display a pointer, use the %p
format specifier.
Writing if anyone needs (worked for me):
event.stopImmediatePropagation()
From this solution.
If you will call min() around 1kk times with different a, b, c, then use my method:
Here only two comparisons. There is no way to calc faster :P
public static double min(double a, double b, double c) {
if (a > b) { //if true, min = b
if (b > c) { //if true, min = c
return c;
} else { //else min = b
return b;
}
} //else min = a
if (a > c) { // if true, min=c
return c;
} else {
return a;
}
}
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
I give my activity an interface that all the fragments can then use. If you have have many fragments on the same activity, this saves a lot of code re-writing and is a cleaner solution / more modular than making an individual interface for each fragment with similar functions. I also like how it is modular. The downside, is that some fragments will have access to functions they don't need.
public class MyActivity extends AppCompatActivity
implements MyActivityInterface {
private List<String> mData;
@Override
public List<String> getData(){return mData;}
@Override
public void setData(List<String> data){mData = data;}
}
public interface MyActivityInterface {
List<String> getData();
void setData(List<String> data);
}
public class MyFragment extends Fragment {
private MyActivityInterface mActivity;
private List<String> activityData;
public void onButtonPress(){
activityData = mActivity.getData()
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyActivityInterface) {
mActivity = (MyActivityInterface) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement MyActivityInterface");
}
}
@Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
}
Delay operates on a queue. and as far as i know css manipulation (other than through animate) is not queued.
I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows
that will give you the number of rows.
So, if you have a named data range called Data
that has 7 rows, then =ROWS(Data)
will show 7 in that cell.
You need to set$final[$id]
to an array before adding elements to it. Intiialize it with either
$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
or
$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):
You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.
The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.
$("input").keypress(function(e) { if (e.which !== 0) { alert("Character was typed. It was: " + String.fromCharCode(e.which)); } });
keyup
andkeydown
give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between thekeyCode
property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.
The following was the original answer, but is not correct and may not work reliably in all situations.
To match the keycode with a word character (eg., a
would match. space
would not)
$("input").keyup(function(event)
{
var c= String.fromCharCode(event.keyCode);
var isWordcharacter = c.match(/\w/);
});
Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.
There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse
for more details. In this case, you probably want:
git diff HEAD@{1}
The @{1}
means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD
on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.
I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do
git diff HEAD@{1} filename
This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
A faster way to
would be
:x
If you have opened multiple files you may need to do a
:xa
Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.
import time
from selenium import webdriver
def page_has_loaded(driver, sleep_time = 2):
'''
Waits for page to completely load by comparing current page hash values.
'''
def get_page_hash(driver):
'''
Returns html dom hash
'''
# can find element by either 'html' tag or by the html 'root' id
dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
# dom = driver.find_element_by_id('root').get_attribute('innerHTML')
dom_hash = hash(dom.encode('utf-8'))
return dom_hash
page_hash = 'empty'
page_hash_new = ''
# comparing old and new page DOM hash together to verify the page is fully loaded
while page_hash != page_hash_new:
page_hash = get_page_hash(driver)
time.sleep(sleep_time)
page_hash_new = get_page_hash(driver)
print('<page_has_loaded> - page not loaded')
print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))
You can use the following approach:
[lower + x*(upper-lower)/length for x in range(length)]
lower and/or upper must be assigned as floats for this approach to work.
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class
in C++ is private
, so any public
and protected
members from the base class are limited to private
. struct
inheritance on the other hand is public
by default.
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
I don't like my switch
statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case
statements all do exactly the same thing.
If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.
public static int GCD(int x, int y) {
int r;
while (y!=0) {
r = x%y;
x = y;
y = r;
}
return x;
}
If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0)
. This will save you from replacing the ".00"
characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation"
).
Othewise, you of course remove it using SQL query:
select replace(cast([height] as varchar), '.00', '') from table
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
This happened to me when I was trying to push the develop branch (I am using git flow). Someone had push updates to master. to fix it I did:
git co master
git pull
Which fetched those changes. Then,
git co develop
git pull
Which didn't do anything. I think the develop branch already pushed despite the error message. Everything is up to date now and no errors.
Encapsulate your code in a function. You can stop executing a function with return
at any time.