To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below.
If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.
You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.
Try Using DateTime::createFromFormat
$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');
Output
2012-04-24
EDIT:
If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.
$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
OUTPUT:
2010-4-5
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.
Here are the correct versions of both of them on SQL Server 2000.
select t.range as [score range], count(*) as [number of occurences]
from (
select case
when score between 0 and 9 then ' 0- 9'
when score between 10 and 19 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
or
select t.range as [score range], count(*) as [number of occurrences]
from (
select user_id,
case when score >= 0 and score< 10 then '0-9'
when score >= 10 and score< 20 then '10-19'
else '20-99' end as range
from scores) t
group by t.range
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
try
with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:
If you want the exact number of full months, always positive (2000-01-15, 2000-02-14 returns 0), considering a full month is when you reach the same day the next month (something like the age calculation)
public static int GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
return monthDiff - 1;
}
else
{
return monthDiff;
}
}
Edit reason: the old code was not correct in some cases like :
new { From = new DateTime(1900, 8, 31), To = new DateTime(1901, 8, 30), Result = 11 },
Test cases I used to test the function:
var tests = new[]
{
new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 1, 1), Result = 0 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 1, 2), Result = 0 },
new { From = new DateTime(1900, 1, 2), To = new DateTime(1900, 1, 1), Result = 0 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1900, 2, 1), Result = 1 },
new { From = new DateTime(1900, 2, 1), To = new DateTime(1900, 1, 1), Result = 1 },
new { From = new DateTime(1900, 1, 31), To = new DateTime(1900, 2, 1), Result = 0 },
new { From = new DateTime(1900, 8, 31), To = new DateTime(1900, 9, 30), Result = 0 },
new { From = new DateTime(1900, 8, 31), To = new DateTime(1900, 10, 1), Result = 1 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1901, 1, 1), Result = 12 },
new { From = new DateTime(1900, 1, 1), To = new DateTime(1911, 1, 1), Result = 132 },
new { From = new DateTime(1900, 8, 31), To = new DateTime(1901, 8, 30), Result = 11 },
};
Needle module is also good, here is an example which uses needle
module
var needle = require('needle');
needle.get('http://www.google.com', function(error, response) {
if (!error && response.statusCode == 200)
console.log(response.body);
});
My requirement is to
I referred the link: Auto Scale TextView Text to Fit within Bounds (including comments) and also the DialogTitle.java
I found that the solution provided is nice and simple but it does not dynamically change the size of the text box. It works great when
the selected text length from the list view is greater in size than the existing text lenght in the ScalableTextView
. When selected the text having length smaller than the existing text in the ScalableTextView
, it do not increase the size of the text, showing the text in the smaller size.
I modified the ScalableTextView.java to readjust the text size based on the text length. Here is my ScalableTextView.java
public class ScalableTextView extends TextView
{
float defaultTextSize = 0.0f;
public ScalableTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
setSingleLine();
setEllipsize(TruncateAt.END);
defaultTextSize = getTextSize();
}
public ScalableTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
setSingleLine();
setEllipsize(TruncateAt.END);
defaultTextSize = getTextSize();
}
public ScalableTextView(Context context)
{
super(context);
setSingleLine();
setEllipsize(TruncateAt.END);
defaultTextSize = getTextSize();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
setTextSize(TypedValue.COMPLEX_UNIT_PX, defaultTextSize);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final Layout layout = getLayout();
if (layout != null)
{
final int lineCount = layout.getLineCount();
if (lineCount > 0)
{
int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
while (ellipsisCount > 0)
{
final float textSize = getTextSize();
// textSize is already expressed in pixels
setTextSize(TypedValue.COMPLEX_UNIT_PX, (textSize - 1));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
ellipsisCount = layout.getEllipsisCount(lineCount - 1);
}
}
}
}
}
Happy Coding....
I found this workaround - move header row in a table above table with data:
<html>_x000D_
<head>_x000D_
<title>Fixed header</title>_x000D_
<style>_x000D_
table td {width:75px;}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div style="height:auto; width:350px; overflow:auto">_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>header 1</td>_x000D_
<td>header 2</td>_x000D_
<td>header 3</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div style="height:50px; width:350px; overflow:auto">_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>row 1 col 1</td>_x000D_
<td>row 1 col 2</td>_x000D_
<td>row 1 col 3</td> _x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 2 col 1</td>_x000D_
<td>row 2 col 2</td>_x000D_
<td>row 2 col 3</td> _x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 3 col 1</td>_x000D_
<td>row 3 col 2</td>_x000D_
<td>row 3 col 3</td> _x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 4 col 1</td>_x000D_
<td>row 4 col 2</td>_x000D_
<td>row 4 col 3</td> _x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 5 col 1</td>_x000D_
<td>row 5 col 2</td>_x000D_
<td>row 5 col 3</td> _x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 6 col 1</td>_x000D_
<td>row 6 col 2</td>_x000D_
<td>row 6 col 3</td> _x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Short answer: Not likely.
Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.
Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.
It is highly unlikely that adding NameVirtualHost *:443
is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).
If you're running a relatively stock Apache configuration, you probably have this somewhere:
<VirtualHost _default_:443>
Your best bet is to either:
VirtualHost
container, or VirtualHost
block and create a new one. Don't forget to include all the relevant SSL options.I had used the below code to open a new tab in the browser using C# selenium..
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("window.open();");
Say you were opening a file in your current directory. The command would be:
start %cd%\filename.filetype
I hope I answered your question.
Try
npm config set strict-ssl false
This is a alternative shared in this url https://github.com/nodejs/node/issues/3742
It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5
In general you can do this for any python package you want
conda install package_name=package_version
There is a nuance to updating tables then updating the DBML... Foreign key relationships are not immediately always brought over if changes are made to existing tables. The work around is to do a build of the project and then re-add the tables again. I reported this to MS and its being fixed for VS2010.
DBML display does not show new foreign key constraints
Note that the instructions given in the main answer are not clear. To update the table
You need to override Activity.onActivityResult()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CODE_ONE) {
String a = data.getStringExtra("RESULT_CODE_ONE");
}
else if(resultCode == RESULT_CODE_TWO){
// b was clicked
}
else{
}
}
npm install -g remove-node-modules
remove-node-modules
remove-node-modules path/to/folder
Source:
There is no work-around for this aside from ditching the select
element.
The other answers did not work for me, so I checked Telerik's official documentation it says you need to find the button and call the click()
function:
function KeyPressed(sender, eventArgs) {
var button = $find("<%= RadButton1.ClientID %>");
button.click();
}
To resolve, Update Spring Frame Work to 3.2.0 or above!
It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.
First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).
Finding the cell that contains the number of aircraft was:
=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1
I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:
=INDIRECT(ADDRESS(StateRow,1))
This returns the name of the state from the dynamic value in row "StateRow", column 1
Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.
It means that using the bodyParser()
constructor has been deprecated, as of 2014-06-19.
app.use(bodyParser()); //Now deprecated
You now need to call the methods separately
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
And so on.
If you're still getting a warning with urlencoded
you need to use
app.use(bodyParser.urlencoded({
extended: true
}));
The extended
config object key now needs to be explicitly passed, since it now has no default value.
If you are using Express >= 4.16.0, body parser has been re-added under the methods express.json()
and express.urlencoded()
.
Problem below, is to compare table before and after i do big update!.
If you use Linux, you can use commands as follow:
In terminal,
mysqldump -hlocalhost -uroot -p schema_name_here table_name_here > /home/ubuntu/database_dumps/dump_table_before_running_update.sql
mysqldump -hlocalhost -uroot -p schema_name_here table_name_here > /home/ubuntu/database_dumps/dump_table_after_running_update.sql
diff -uP /home/ubuntu/database_dumps/dump_some_table_after_running_update.sql /home/ubuntu/database_dumps/dump_table_before_running_update.sql > /home/ubuntu/database_dumps/diff.txt
You will need online tools for
e.g http://www.dpriver.com/pp/sqlformat.htm [Not the best I've seen]
We have diff.txt, you have to take manually the + - showing inside, which is 1 line of insert statements, that has the values.
Do diff online for the 2 lines - & + in diff.txt, past them in online diff tool
e.g https://www.diffchecker.com [you can save and share it, and has no limit on file size!]
Note: be extra careful if its sensitive/production data!
https://nodejs.org/en/download/releases/ [Download the specified version]
The asterisk is just a repetition operator, but you need to tell it what you repeat. /*abc*/
matches a string containing ab and zero or more c's (because the second * is on the c; the first is meaningless because there's nothing for it to repeat). If you want to match anything, you need to say .*
-- the dot means any character (within certain guidelines). If you want to just match abc, you could just say grep 'abc' myFile
. For your more complex match, you need to use .*
-- grep 'abc.*def' myFile
will match a string that contains abc followed by def with something optionally in between.
Update based on a comment:
*
in a regular expression is not exactly the same as * in the console. In the console, * is part of a glob construct, and just acts as a wildcard (for instance ls *.log
will list all files that end in .log). However, in regular expressions, * is a modifier, meaning that it only applies to the character or group preceding it. If you want * in regular expressions to act as a wildcard, you need to use .*
as previously mentioned -- the dot is a wildcard character, and the star, when modifying the dot, means find one or more dot; ie. find one or more of any character.
Retrieve an object using the tutorial shown in the Flask-SQLAlchemy documentation. Once you have the entity that you want to change, change the entity itself. Then, db.session.commit()
.
For example:
admin = User.query.filter_by(username='admin').first()
admin.email = '[email protected]'
db.session.commit()
user = User.query.get(5)
user.name = 'New Name'
db.session.commit()
Flask-SQLAlchemy is based on SQLAlchemy, so be sure to check out the SQLAlchemy Docs as well.
You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -
public static string GetInnerHtmlFromDiv(string url)
{
string HTML;
using (var wc = new WebClient())
{
HTML = wc.DownloadString(url);
}
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(HTML);
HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
if (element != null)
{
return element.InnerHtml.ToString();
}
return null;
}
--
-- SQL DATEDIFF getting midnight time parts
--
SELECT GETDATE() AS Now,
Convert(DateTime, DATEDIFF(DAY, 0, GETDATE())) AS MidnightToday,
Convert(DateTime, DATEDIFF(DAY, -1, GETDATE())) AS MidnightNextDay,
Convert(DateTime, DATEDIFF(DAY, 1, GETDATE())) AS MidnightYesterDay
go
Now MidnightToday MidnightNextDay MidnightYesterDay
-------------------- --------------------- --------------------- ---------------------
8/27/2014 4:30:22 PM 8/27/2014 12:00:00 AM 8/28/2014 12:00:00 AM 8/26/2014 12:00:00 AM
Use pyplot.text()
(import matplotlib.pyplot as plt
)
import matplotlib.pyplot as plt
x=[1,2,3]
y=[9,8,7]
plt.plot(x,y)
for a,b in zip(x, y):
plt.text(a, b, str(b))
plt.show()
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
This will work for input, textarea and select in normal, hover, focus and active states.
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
textarea:-webkit-autofill:active,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus,
select:-webkit-autofill:active,
{
-webkit-box-shadow: 0 0 0px 1000px white inset !important;
}
Here is SCSS version of the above solution for those who are working with SASS/SCSS.
input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill
{
&, &:hover, &:focus, &:active
{
-webkit-box-shadow: 0 0 0px 1000px white inset !important;
}
}
ELXAN@DB1> create table cedvel(id integer,ad varchar2(15)); Table created. ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id); Table altered. ELXAN@DB1> create sequence test_seq start with 1 increment by 1; Sequence created. ELXAN@DB1> create or replace trigger ad_insert before insert on cedvel REFERENCING NEW AS NEW OLD AS OLD for each row begin select test_seq.nextval into :new.id from dual; end; / 2 3 4 5 6 7 8 Trigger created. ELXAN@DB1> insert into cedvel (ad) values ('nese'); 1 row created.
[For Reference]ThreadLocal cannot solve update problems of shared object. It is recommended to use a staticThreadLocal object which is shared by all operations in the same thread. [Mandatory]remove() method must be implemented by ThreadLocal variables, especially when using thread pools in which threads are often reused. Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory leak.
someone here may find it useful. hhb_curl_exec2 works pretty much like curl_exec, but arg3 is an array which will be populated with the returned http headers (numeric index), and arg4 is an array which will be populated with the returned cookies ($cookies["expires"]=>"Fri, 06-May-2016 05:58:51 GMT"), and arg5 will be populated with... info about the raw request made by curl.
the downside is that it requires CURLOPT_RETURNTRANSFER to be on, else it error out, and that it will overwrite CURLOPT_STDERR and CURLOPT_VERBOSE, if you were already using them for something else.. (i might fix this later)
example of how to use it:
<?php
header("content-type: text/plain;charset=utf8");
$ch=curl_init();
$headers=array();
$cookies=array();
$debuginfo="";
$body="";
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$body=hhb_curl_exec2($ch,'https://www.youtube.com/',$headers,$cookies,$debuginfo);
var_dump('$cookies:',$cookies,'$headers:',$headers,'$debuginfo:',$debuginfo,'$body:',$body);
and the function itself..
function hhb_curl_exec2($ch, $url, &$returnHeaders = array(), &$returnCookies = array(), &$verboseDebugInfo = "")
{
$returnHeaders = array();
$returnCookies = array();
$verboseDebugInfo = "";
if (!is_resource($ch) || get_resource_type($ch) !== 'curl') {
throw new InvalidArgumentException('$ch must be a curl handle!');
}
if (!is_string($url)) {
throw new InvalidArgumentException('$url must be a string!');
}
$verbosefileh = tmpfile();
$verbosefile = stream_get_meta_data($verbosefileh);
$verbosefile = $verbosefile['uri'];
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $verbosefileh);
curl_setopt($ch, CURLOPT_HEADER, 1);
$html = hhb_curl_exec($ch, $url);
$verboseDebugInfo = file_get_contents($verbosefile);
curl_setopt($ch, CURLOPT_STDERR, NULL);
fclose($verbosefileh);
unset($verbosefile, $verbosefileh);
$headers = array();
$crlf = "\x0d\x0a";
$thepos = strpos($html, $crlf . $crlf, 0);
$headersString = substr($html, 0, $thepos);
$headerArr = explode($crlf, $headersString);
$returnHeaders = $headerArr;
unset($headersString, $headerArr);
$htmlBody = substr($html, $thepos + 4); //should work on utf8/ascii headers... utf32? not so sure..
unset($html);
//I REALLY HOPE THERE EXIST A BETTER WAY TO GET COOKIES.. good grief this looks ugly..
//at least it's tested and seems to work perfectly...
$grabCookieName = function($str)
{
$ret = "";
$i = 0;
for ($i = 0; $i < strlen($str); ++$i) {
if ($str[$i] === ' ') {
continue;
}
if ($str[$i] === '=') {
break;
}
$ret .= $str[$i];
}
return urldecode($ret);
};
foreach ($returnHeaders as $header) {
//Set-Cookie: crlfcoookielol=crlf+is%0D%0A+and+newline+is+%0D%0A+and+semicolon+is%3B+and+not+sure+what+else
/*Set-Cookie:ci_spill=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22305d3d67b8016ca9661c3b032d4319df%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2285.164.158.128%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A109%3A%22Mozilla%2F5.0+%28Windows+NT+6.1%3B+WOW64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F43.0.2357.132+Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1436874639%3B%7Dcab1dd09f4eca466660e8a767856d013; expires=Tue, 14-Jul-2015 13:50:39 GMT; path=/
Set-Cookie: sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT;
//Cookie names cannot contain any of the following '=,; \t\r\n\013\014'
//
*/
if (stripos($header, "Set-Cookie:") !== 0) {
continue;
/**/
}
$header = trim(substr($header, strlen("Set-Cookie:")));
while (strlen($header) > 0) {
$cookiename = $grabCookieName($header);
$returnCookies[$cookiename] = '';
$header = substr($header, strlen($cookiename) + 1); //also remove the =
if (strlen($header) < 1) {
break;
}
;
$thepos = strpos($header, ';');
if ($thepos === false) { //last cookie in this Set-Cookie.
$returnCookies[$cookiename] = urldecode($header);
break;
}
$returnCookies[$cookiename] = urldecode(substr($header, 0, $thepos));
$header = trim(substr($header, $thepos + 1)); //also remove the ;
}
}
unset($header, $cookiename, $thepos);
return $htmlBody;
}
function hhb_curl_exec($ch, $url)
{
static $hhb_curl_domainCache = "";
//$hhb_curl_domainCache=&$this->hhb_curl_domainCache;
//$ch=&$this->curlh;
if (!is_resource($ch) || get_resource_type($ch) !== 'curl') {
throw new InvalidArgumentException('$ch must be a curl handle!');
}
if (!is_string($url)) {
throw new InvalidArgumentException('$url must be a string!');
}
$tmpvar = "";
if (parse_url($url, PHP_URL_HOST) === null) {
if (substr($url, 0, 1) !== '/') {
$url = $hhb_curl_domainCache . '/' . $url;
} else {
$url = $hhb_curl_domainCache . $url;
}
}
;
curl_setopt($ch, CURLOPT_URL, $url);
$html = curl_exec($ch);
if (curl_errno($ch)) {
throw new Exception('Curl error (curl_errno=' . curl_errno($ch) . ') on url ' . var_export($url, true) . ': ' . curl_error($ch));
// echo 'Curl error: ' . curl_error($ch);
}
if ($html === '' && 203 != ($tmpvar = curl_getinfo($ch, CURLINFO_HTTP_CODE)) /*203 is "success, but no output"..*/ ) {
throw new Exception('Curl returned nothing for ' . var_export($url, true) . ' but HTTP_RESPONSE_CODE was ' . var_export($tmpvar, true));
}
;
//remember that curl (usually) auto-follows the "Location: " http redirects..
$hhb_curl_domainCache = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL), PHP_URL_HOST);
return $html;
}
t.Log()
will not show up until after the test is complete, so if you're trying to debug a test that is hanging or performing badly it seems you need to usefmt
.
Yes: that was the case up to Go 1.13 (August 2019) included.
And that was followed in golang.org
issue 24929
Consider the following (silly) automated tests:
func TestFoo(t *testing.T) { t.Parallel() for i := 0; i < 15; i++ { t.Logf("%d", i) time.Sleep(3 * time.Second) } } func TestBar(t *testing.T) { t.Parallel() for i := 0; i < 15; i++ { t.Logf("%d", i) time.Sleep(2 * time.Second) } } func TestBaz(t *testing.T) { t.Parallel() for i := 0; i < 15; i++ { t.Logf("%d", i) time.Sleep(1 * time.Second) } }
If I run
go test -v
, I get no log output until all ofTestFoo
is done, then no output until all ofTestBar
is done, and again no more output until all ofTestBaz
is done.
This is fine if the tests are working, but if there is some sort of bug, there are a few cases where buffering log output is problematic:
- When iterating locally, I want to be able to make a change, run my tests, see what's happening in the logs immediately to understand what's going on, hit CTRL+C to shut the test down early if necessary, make another change, re-run the tests, and so on.
IfTestFoo
is slow (e.g., it's an integration test), I get no log output until the very end of the test. This significantly slows down iteration.- If
TestFoo
has a bug that causes it to hang and never complete, I'd get no log output whatsoever. In these cases,t.Log
andt.Logf
are of no use at all.
This makes debugging very difficult.- Moreover, not only do I get no log output, but if the test hangs too long, either the Go test timeout kills the test after 10 minutes, or if I increase that timeout, many CI servers will also kill off tests if there is no log output after a certain amount of time (e.g., 10 minutes in CircleCI).
So now my tests are killed and I have nothing in the logs to tell me what happened.
But for (possibly) Go 1.14 (Q1 2020): CL 127120
testing: stream log output in verbose mode
The output now is:
=== RUN TestFoo
=== PAUSE TestFoo
=== RUN TestBar
=== PAUSE TestBar
=== RUN TestGaz
=== PAUSE TestGaz
=== CONT TestFoo
TestFoo: main_test.go:14: hello from foo
=== CONT TestGaz
=== CONT TestBar
TestGaz: main_test.go:38: hello from gaz
TestBar: main_test.go:26: hello from bar
TestFoo: main_test.go:14: hello from foo
TestBar: main_test.go:26: hello from bar
TestGaz: main_test.go:38: hello from gaz
TestFoo: main_test.go:14: hello from foo
TestGaz: main_test.go:38: hello from gaz
TestBar: main_test.go:26: hello from bar
TestFoo: main_test.go:14: hello from foo
TestGaz: main_test.go:38: hello from gaz
TestBar: main_test.go:26: hello from bar
TestGaz: main_test.go:38: hello from gaz
TestFoo: main_test.go:14: hello from foo
TestBar: main_test.go:26: hello from bar
--- PASS: TestFoo (1.00s)
--- PASS: TestGaz (1.00s)
--- PASS: TestBar (1.00s)
PASS
ok dummy/streaming-test 1.022s
It is indeed in Go 1.14, as Dave Cheney attests in "go test -v
streaming output":
In Go 1.14,
go test -v
will streamt.Log
output as it happens, rather than hoarding it til the end of the test run.Under Go 1.14 the
fmt.Println
andt.Log
lines are interleaved, rather than waiting for the test to complete, demonstrating that test output is streamed whengo test -v
is used.
Advantage, according to Dave:
This is a great quality of life improvement for integration style tests that often retry for long periods when the test is failing.
Streamingt.Log
output will help Gophers debug those test failures without having to wait until the entire test times out to receive their output.
You can use Powermock for mocking the call. Like:
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("MyEnvVariable")).thenReturn("DesiredValue");
You can also mock all the calls with:
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv(Mockito.anyString())).thenReturn(envVariable);
This is exactly what bytearray
is for:
newFileByteArray = bytearray(newFileBytes)
newFile.write(newFileByteArray)
If you're using Python 3.x, you can use bytes
instead (and probably ought to, as it signals your intention better). But in Python 2.x, that won't work, because bytes
is just an alias for str
. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that.
Python 3.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
b'{\x03\xff\x00d'
Python 2.x:
>>> bytearray(newFileBytes)
bytearray(b'{\x03\xff\x00d')
>>> bytes(newFileBytes)
'[123, 3, 255, 0, 100]'
There is an animationend
Event that can be observed see documentation here,
also for css transition
animations you could use the transitionend
event
There is no need for additional libraries these all work with vanilla JS
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
As has been suggested, using the string.format method is nice and simple and very readable.
In vb.net the " + " is used for addition and the " & " is used for string concatenation.
In your example:
MsgBox("Variable = " + variable)
becomes:
MsgBox("Variable = " & variable)
I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx
maybe call
variable.ToString()
update:
Use string interpolation (vs2015 onwards I believe):
MsgBox($"Variable = {variable}")
I used a function to get current datetime
protected function getCurrentDate()
{
$now = Carbon::now();
return $now->toDateTimeString('');
}
However I get an error.
Carbon\Exceptions\UnitException
Precision unit expected among: minute, second, millisecond and microsecond.
Any ideas how to get the time in a format like day.month.Year Hour:minute
you can slide up and down any view or layout by using bellow code in android app
boolean isClicked=false;
LinearLayout mLayoutTab = (LinearLayout)findViewById(R.id.linearlayout);
if(isClicked){
isClicked = false;
mLayoutTab.animate()
.translationYBy(120)
.translationY(0)
.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
}else{
isClicked = true;
mLayoutTab.animate()
.translationYBy(0)
.translationY(120)
.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
}
sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOUR_PASSWORD_HERE';
FLUSH PRIVILEGES;
mysql -u root -p # and it works
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
I've found out that somethimes one ScrollView regains focus and the other loses focus. You can prevent that, by only granting one of the scrollView focus:
scrollView1= (ScrollView) findViewById(R.id.scrollscroll);
scrollView1.setAdapter(adapter);
scrollView1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
scrollView1.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
Keep in mind that the copy constructor limits the class type to that of the copy constructor. Consider the example:
// Need to clone person, which is type Person
Person clone = new Person(person);
This doesn't work if person
could be a subclass of Person
(or if Person
is an interface). This is the whole point of clone, is that it can can clone the proper type dynamically at runtime (assuming clone is properly implemented).
Person clone = (Person)person.clone();
or
Person clone = (Person)SomeCloneUtil.clone(person); // See Bozho's answer
Now person
can be any type of Person
assuming that clone
is properly implemented.
When you use VARIABLE = value
, if value
is actually a reference to another variable, then the value is only determined when VARIABLE
is used. This is best illustrated with an example:
VAL = foo
VARIABLE = $(VAL)
VAL = bar
# VARIABLE and VAL will both evaluate to "bar"
When you use VARIABLE := value
, you get the value of value
as it is now. For example:
VAL = foo
VARIABLE := $(VAL)
VAL = bar
# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"
Using VARIABLE ?= val
means that you only set the value of VARIABLE
if VARIABLE
is not set already. If it's not set already, the setting of the value is deferred until VARIABLE
is used (as in example 1).
VARIABLE += value
just appends value
to VARIABLE
. The actual value of value
is determined as it was when it was initially set, using either =
or :=
.
let JSONData = jsonString.data(using: .utf8)!
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
guard let userDictionary = jsonResult as? Dictionary<String, AnyObject> else {
throw NSError()}
Use genfromtxt
instead. It's a much more general method than loadtxt
:
import numpy as np
print np.genfromtxt('col.txt',dtype='str')
Using the file col.txt
:
foo bar
cat dog
man wine
This gives:
[['foo' 'bar']
['cat' 'dog']
['man' 'wine']]
If you expect that each row has the same number of columns, read the first row and set the attribute filling_values
to fix any missing rows.
What helped for me, was to put the following line in the ready function:
$(document).ready(function()
{
..
...
// codes works on all bootstrap modal windows in application
$('.modal').on('hidden.bs.modal', function(e)
{
$(this).removeData();
}) ;
...
..
});
When a modal window is closed and opened again, the previous entered and selected values, will be reset to the initial values.
I hope this will help you as well!
You can use the %
operator to find the remainder of a division, and compare the result with 0
.
Example:
if (number % divisor == 0)
{
//code for perfect divisor
}
else
{
//the number doesn't divide perfectly by divisor
}
Here is a simple jQuery UI solution based on the example here:
http://jqueryui.com/button/#radio
Modified code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Radios</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#radio" ).buttonset();
});
</script>
</head>
<body>
<form>
<div id="radio">
<input type="radio" id="radio1" name="radio"><label for="radio1"><img src="image1.gif" /></label>
<input type="radio" id="radio2" name="radio" checked="checked"><label for="radio2"><img src="image2.gif" /></label>
<input type="radio" id="radio3" name="radio"><label for="radio3"><img src="image3.gif" /></label>
</div>
</form>
</body>
</html>
jQueryUI takes care of the image background so you know which button is checked.
Beware: If you want to set a button to checked or unchecked via Javascript, you must call the refresh function:
$('#radio3').prop('checked', true).button("refresh");
Another option besides awk is nl which allows for options -v
for setting starting value and -n <lf,rf,rz>
for left, right and right with leading zeros justified. You can also include -s
for a field separator such as -s ","
for comma separation between line numbers and your data.
In a Unix environment, this can be done as
cat <infile> | ...other stuff... | nl -v 0 -n rz
or simply
nl -v 0 -n rz <infile>
Example:
echo "Here
are
some
words" > words.txt
cat words.txt | nl -v 0 -n rz
Out:
000000 Here
000001 are
000002 some
000003 words
You can, but the variable in your last include will overwrite the variable in your first one:
myfile.php
$var = 'test';
mysecondfile.php
$var = 'tester';
test.php
include 'myfile.php';
echo $var;
include 'mysecondfile.php';
echo $var;
Output:
test
tester
I suggest using different variable names.
instead of getting Notepad++, You can simply Open the file with Wordpad and then Save As - Plain Text document
A.replaceWith(span)
- No parent neededGeneric form:
target.replaceWith(element)
Way better/cleaner than the previous method.
For your use case:
A.replaceWith(span)
...
).Examples:
// Initially [child1, target, child3]
target.replaceWith(span, "foo") // [child1, span, "foo", child3]
const list = ["bar", span]
target.replaceWith(...list, "fizz") // [child1, "bar", span, "fizz", child3]
null
targetIf your target has a chance to be null, you can consider using the newish ?.
optional chaining operator. Nothing will happen if target doesn't exist. Read more here.
target?.replaceWith(element)
Supported Browsers - 94% Apr 2020
Exactly what Nick Carver did there but I think it would be best if used the DOM setAttribute method.
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
var link = document.getElementById("abc");
link.setAttribute("href", "xyz.php");
return false;
}
</script>
It's one extra line of code but find it better structure-wise.
If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.
CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);
If I am getting you correctly, when you say that clicking does nothing, do you mean that it does not point to your URL?
In the anchor tag <a href>
it looks like you did not pass your file path to the href
attribute. So, replace the # with your actual path for the file that you want to link.
<li><a href="#">Action</a></li>
<li><a href="action link here">Another action</a></li>
<li><a href="something else link here">Something else here</a></li>
<li class="divider"></li>
<li><a href="seperated link here">Separated link</a></li>
I hope this helps with your issue.
I had the same problem, Android Studio just could not identify the android-sdk folder. All I did was to uninstall and reinstall android studio, and this time it actually identified the folder. Hope it also works out for you.
If no From: header is specified in the e-mail headers, the MTA uses the full name of the current user, in this case "Apache". You can edit full user names in /etc/passwd
JEP 259 provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces. Before Stack-Walking API, common ways of accessing stack frames were:
Throwable::getStackTrace
andThread::getStackTrace
return an array ofStackTraceElement
objects, which contain the class name and method name of each stack-trace element.
SecurityManager::getClassContext
is a protected method, which allows aSecurityManager
subclass to access the class context.JDK-internal
sun.reflect.Reflection::getCallerClass
method which you shouldn't use anyway
Using these APIs are usually inefficient:
These APIs require the VM to eagerly capture a snapshot of the entire stack, and they return information representing the entire stack. There is no way to avoid the cost of examining all the frames if the caller is only interested in the top few frames on the stack.
In order to find the immediate caller's class, first obtain a StackWalker
:
StackWalker walker = StackWalker
.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
Then either call the getCallerClass()
:
Class<?> callerClass = walker.getCallerClass();
or walk
the StackFrame
s and get the first preceding StackFrame
:
walker.walk(frames -> frames
.map(StackWalker.StackFrame::getDeclaringClass)
.skip(1)
.findFirst());
The smarter_csv
gem was specifically created for this use-case: to read data from CSV file and quickly create database entries.
require 'smarter_csv'
options = {}
SmarterCSV.process('input_file.csv', options) do |chunk|
chunk.each do |data_hash|
Moulding.create!( data_hash )
end
end
You can use the option chunk_size
to read N csv-rows at a time, and then use Resque in the inner loop to generate jobs which will create the new records, rather than creating them right away - this way you can spread the load of generating entries to multiple workers.
See also: https://github.com/tilo/smarter_csv
/* Keyword value */
cursor: pointer;
cursor: auto;
/* URL, with a keyword fallback */
cursor: url(hand.cur), pointer;
/* URL and coordinates, with a keyword fallback */
cursor: url(cursor1.png) 4 12, auto;
cursor: url(cursor2.png) 2 2, pointer;
/* Global values */
cursor: inherit;
cursor: initial;
cursor: unset;
/* 2 URLs and coordinates, with a keyword fallback */
cursor: url(one.svg) 2 2, url(two.svg) 5 5, progress;
Note: cursor support for many format icons!
such as .cur, .png, .svg, .jpeg, .webp
, and so on
li:hover{
cursor: url("https://cdn.xgqfrms.xyz/cursor/mouse.cur"), pointer;
color: #0f0;
background: #000;
}
/*
li:hover{
cursor: url("../icons/hand.cur"), pointer;
}
*/
li{
height: 30px;
width: 100px;
background: #ccc;
color: #fff;
margin: 10px;
text-align: center;
list-style: none;
}
_x000D_
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
_x000D_
I have used Dropbox as my Prive or protected svn. Try the link below. http://foyzulkarim.blogspot.com/2012/12/dropbox-as-svn-repository.html
We also faced this issue recently. If the issue is related to mapper memory, couple of things I would like to suggest that needs to be checked are.
Like tomash said before: There's no easy way.
You might want to take a look at my answer here.
It explains how to realize a sliding (dimension changing) view.
In this case it was a left and right view: Left expanding, right disappearing.
It's might not do exactly what you need but with inventive spirit you can make it work ;)
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).
See http://api.jquery.com/on/#direct-and-delegated-events
Change your code to
$(document.body).on('click', '.update' ,function(){
The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live
, the jQuery set elements must exist when you execute the code.
As this answers receives a lot of attention, here are two supplementary advises :
1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.
That is, if you're adding an element of class b
to an existing element of id a
, then don't use
$(document.body).on('click', '#a .b', function(){
but use
$('#a').on('click', '.b', function(){
2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c"
would retrieve only one element with this id.
None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:
echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set MAX_TRIES=100
set P=%PATH%
for /L %%a in (1, 1, %MAX_TRIES%) do (
for /F "delims=;" %%g in ("!P!") do (
echo %%g
set P=!P:%%g;=!
if "!P!" == "%%g" goto :eof
)
)
Oh ! I hate batch file programming !!
Updated
Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution
echo off
setlocal enabledelayedexpansion
set NonBlankPath=%PATH: =#%
set TabbedPath=%NonBlankPath:;= %
for %%g in (%TabbedPath%) do (
set GG=%%g
echo !GG:#= !
)
This extension method works for me:
public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
try
{
enumerable.First();
return false;
}
catch (InvalidOperationException)
{
return true;
}
}
I found a short solution for it.
No extra code is needed just trigger the changeDate event. E.g.
$('.datepicker').datepicker().trigger('changeDate');
Add an app to run automatically at startup in Windows 10
Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.
Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.
Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.
Step 4: Copy and paste the shortcut to the app from the file location to the Startup folder.
You can use this command:
git branch --merged master | grep -v "\* master" | xargs -n 1 git branch -d
Git Clean: Delete Already-Merged Branches including break down of command
%s/\s*$/\*/g
this will do the trick, and ensure leading spaces are ignored.
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
This is an old question, but too many examples above are over-complicated.
Keep It Simple: (in Jupyter Notebook or Python 3.7.1 terminal on Windows 10)
import sys
print(sys.executable)```
# example output: >> `C:\Anaconda3\envs\quantecon\python.exe`
OR
```sys.base_prefix```
# Example output: >> 'C:\\Anaconda3\\envs\\quantecon'
Are you looking for something like this:
RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));
Also check User Identity
Use INDIRECT()
=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))
How about something like this.
Test the live example: http://jsfiddle.net/6hBZU/1/
It assumes that the string will always end with the extension:
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif':
alert('was jpg png gif'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
alert('was zip rar');
break;
case 'pdf':
alert('was pdf');
break;
default:
alert('who knows');
}
};
openFile("somestring.png");
EDIT: I mistakenly deleted part of the string in openFile("somestring.png");
. Corrected. Had it in the Live Example, though.
I found that in my case this is the only way working: (in my application I want to remove old log entries)
var filterDate = dtRemoveLogs.SelectedDate.Value.Date;
var loadOp = context.Load<ApplicationLog>(context.GetApplicationLogsQuery()
.Where(l => l.DateTime.Year <= filterDate.Year
&& l.DateTime.Month <= filterDate.Month
&& l.DateTime.Day <= filterDate.Day));
I don't understand why the Jon's solution is not working ....
I just had this issue and solved it by adding the following method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You might have misunderstood rstrip slightly, it strips not a string but any character in the string you specify.
Like this:
>>> text = "xxxxcbaabc"
>>> text.rstrip("abc")
'xxxx'
So instead, just use
text = text[:-3]
(after replacing whitespace with nothing)
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
just set position: fixed
to the footer element (instead of relative)
Note that you may need to also set a margin-bottom
to the main
element at least equal to the height of the footer element (e.g. margin-bottom: 1.5em;
) otherwise, in some circustances, the bottom area of the main content could be partially overlapped by your footer
I would recommend that you have a look at SUDS
"Suds is a lightweight SOAP python client for consuming Web Services."
I have another variant which may be useful for someone:
$('<img src="http://example.com/someresource.jpg">').load(function() {
$('#login').submit();
}).appendTo("body");
- each side with the same color
:root{
--color: #f0f;
}
div {
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;
box-sizing: border-box;
margin: 50px auto;
width: 200px;
height: 100px;
background: #ccc;
}
.four-sides-with-same-color {
box-shadow: 0px 0px 10px 5px var(--color);
}
_x000D_
<div class="four-sides-with-same-color"></div>
_x000D_
- each side with a different color
:root{
--color1: #00ff4e;
--color2: #ff004e;
--color3: #b716e6;
--color4: #FF5722;
}
div {
display: flex;
flex-flow: row nowrap;
align-items: center;
justify-content: center;
box-sizing: border-box;
margin: 50px auto;
width: 200px;
height: 100px;
background-color: rgba(255,255,0,0.7);
}
.four-sides-with-different-color {
box-shadow:
10px 0px 5px 0px var(--color1),
0px 10px 5px 0px var(--color2),
-10px 0px 5px 0px var(--color3),
0px -10px 5px 0px var(--color4);
}
_x000D_
<div class="four-sides-with-different-color"></div>
_x000D_
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
List<Long> actual = Arrays.asList(1L, 2L);
List<Long> expected = Arrays.asList(2L, 1L);
assertThat(actual, containsInAnyOrder(expected.toArray()));
Shorter version of @Joe's answer without redundant parameters.
If you add helper fields to the coordinates table, you can improve response time of the query.
Like this:
CREATE TABLE `Coordinates` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'id for the object',
`type` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'type',
`sin_lat` FLOAT NOT NULL COMMENT 'sin(lat) in radians',
`cos_cos` FLOAT NOT NULL COMMENT 'cos(lat)*cos(lon) in radians',
`cos_sin` FLOAT NOT NULL COMMENT 'cos(lat)*sin(lon) in radians',
`lat` FLOAT NOT NULL COMMENT 'latitude in degrees',
`lon` FLOAT NOT NULL COMMENT 'longitude in degrees',
INDEX `lat_lon_idx` (`lat`, `lon`)
)
If you're using TokuDB, you'll get even better performance if you add clustering indexes on either of the predicates, for example, like this:
alter table Coordinates add clustering index c_lat(lat);
alter table Coordinates add clustering index c_lon(lon);
You'll need the basic lat and lon in degrees as well as sin(lat) in radians, cos(lat)*cos(lon) in radians and cos(lat)*sin(lon) in radians for each point. Then you create a mysql function, smth like this:
CREATE FUNCTION `geodistance`(`sin_lat1` FLOAT,
`cos_cos1` FLOAT, `cos_sin1` FLOAT,
`sin_lat2` FLOAT,
`cos_cos2` FLOAT, `cos_sin2` FLOAT)
RETURNS float
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY INVOKER
BEGIN
RETURN acos(sin_lat1*sin_lat2 + cos_cos1*cos_cos2 + cos_sin1*cos_sin2);
END
This gives you the distance.
Don't forget to add an index on lat/lon so the bounding boxing can help the search instead of slowing it down (the index is already added in the CREATE TABLE query above).
INDEX `lat_lon_idx` (`lat`, `lon`)
Given an old table with only lat/lon coordinates, you can set up a script to update it like this: (php using meekrodb)
$users = DB::query('SELECT id,lat,lon FROM Old_Coordinates');
foreach ($users as $user)
{
$lat_rad = deg2rad($user['lat']);
$lon_rad = deg2rad($user['lon']);
DB::replace('Coordinates', array(
'object_id' => $user['id'],
'object_type' => 0,
'sin_lat' => sin($lat_rad),
'cos_cos' => cos($lat_rad)*cos($lon_rad),
'cos_sin' => cos($lat_rad)*sin($lon_rad),
'lat' => $user['lat'],
'lon' => $user['lon']
));
}
Then you optimize the actual query to only do the distance calculation when really needed, for example by bounding the circle (well, oval) from inside and outside. For that, you'll need to precalculate several metrics for the query itself:
// assuming the search center coordinates are $lat and $lon in degrees
// and radius in km is given in $distance
$lat_rad = deg2rad($lat);
$lon_rad = deg2rad($lon);
$R = 6371; // earth's radius, km
$distance_rad = $distance/$R;
$distance_rad_plus = $distance_rad * 1.06; // ovality error for outer bounding box
$dist_deg_lat = rad2deg($distance_rad_plus); //outer bounding box
$dist_deg_lon = rad2deg($distance_rad_plus/cos(deg2rad($lat)));
$dist_deg_lat_small = rad2deg($distance_rad/sqrt(2)); //inner bounding box
$dist_deg_lon_small = rad2deg($distance_rad/cos(deg2rad($lat))/sqrt(2));
Given those preparations, the query goes something like this (php):
$neighbors = DB::query("SELECT id, type, lat, lon,
geodistance(sin_lat,cos_cos,cos_sin,%d,%d,%d) as distance
FROM Coordinates WHERE
lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d
HAVING (lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d) OR distance <= %d",
// center radian values: sin_lat, cos_cos, cos_sin
sin($lat_rad),cos($lat_rad)*cos($lon_rad),cos($lat_rad)*sin($lon_rad),
// min_lat, max_lat, min_lon, max_lon for the outside box
$lat-$dist_deg_lat,$lat+$dist_deg_lat,
$lon-$dist_deg_lon,$lon+$dist_deg_lon,
// min_lat, max_lat, min_lon, max_lon for the inside box
$lat-$dist_deg_lat_small,$lat+$dist_deg_lat_small,
$lon-$dist_deg_lon_small,$lon+$dist_deg_lon_small,
// distance in radians
$distance_rad);
EXPLAIN on the above query might say that it's not using index unless there's enough results to trigger such. The index will be used when there's enough data in the coordinates table. You can add FORCE INDEX (lat_lon_idx) to the SELECT to make it use the index with no regards to the table size, so you can verify with EXPLAIN that it is working correctly.
With the above code samples you should have a working and scalable implementation of object search by distance with minimal error.
With multiple phones and beacons at the same location, it's going to be difficult to measure proximity with any high degree of accuracy. Try using the Android "b and l bluetooth le scanner" app, to visualize the signal strengths (distance) variations, for multiple beacons, and you'll quickly discover that complex, adaptive algorithms may be required to provide any form of consistent proximity measurement.
You're going to see lots of solutions simply instructing the user to "please hold your phone here", to reduce customer frustration.
Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.
Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].
There are advantages and disadvantages in each method:
Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.
Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.
Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
var url = window.location;_x000D_
$('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
$('ul.nav a').filter(function () {_x000D_
return this.href == url;_x000D_
}).parent().addClass('active').parent().parent().addClass('active');_x000D_
});_x000D_
_x000D_
This works perfectly
_x000D_
I don't know that much about batch files but couldn't you have a pre-made batch file copied from the home directory to the path you have that would return a list of the names of the files then use that name?
Here is a link I think might be helpful in making the pre-made batch file.
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
Do you really need an object? What about:
$myArray[] = array("name" => "my name");
Just use a two-dimensional array.
Output (var_dump):
array(1) {
[0]=>
array(1) {
["name"]=>
string(7) "my name"
}
}
You could access your last entry like this:
echo $myArray[count($myArray) - 1]["name"];
I ended up placing my at ~/sdks/android-sdk-mac_x86. I like to keep all of my SDKs in one place and for me an sdk folder under my home directory makes the most sense.
I was looking for fast way to do the subject, so I made some experiments with suggested ways. And I was surprised by results, so I want to share it with you.
Experiments were done using pythonbenchmark tool and with
a = range(1,50000) # Source list
b = range(1,15000) # Items to remove
Results:
def comprehension(a, b):
return [x for x in a if x not in b]
5 tries, average time 12.8 sec
def filter_function(a, b):
return filter(lambda x: x not in b, a)
5 tries, average time 12.6 sec
def modification(a,b):
for x in b:
try:
a.remove(x)
except ValueError:
pass
return a
5 tries, average time 0.27 sec
def set_approach(a,b):
return list(set(a)-set(b))
5 tries, average time 0.0057 sec
Also I made another measurement with bigger inputs size for the last two functions
a = range(1,500000)
b = range(1,100000)
And the results:
For modification (remove method) - average time is 252 seconds For set approach - average time is 0.75 seconds
So you can see that approach with sets is significantly faster than others. Yes, it doesn't keep similar items, but if you don't need it - it's for you. And there is almost no difference between list comprehension and using filter function. Using 'remove' is ~50 times faster, but it modifies source list. And the best choice is using sets - it's more than 1000 times faster than list comprehension!
You can use the JsonTextReader
to read the JSON and iterate over the tokens:
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
Console.WriteLine("{0} - {1} - {2}",
reader.TokenType, reader.ValueType, reader.Value);
}
}
In latest version of JDK, 31 is still used. https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html#hashCode()
The purpose of hash string is
^
in hashcode calculation document, it help unique)31 is max value can put in 8 bit (= 1 byte) register, is largest prime number can put in 1 byte register, is odd number.
Multiply 31 is <<5 then subtract itself, therefore need cheap resources.
For most it is a breeze, however like you I had a difficult time installing jq
The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/
However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system
What worked for me was removing all previous installs then pip install jq
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
As a general rule, you can’t just set the color of a horizontal line with CSS like you would anything else. First of all, Internet Explorer needs the color in your CSS to read like this:
“color: #123455”
But Opera and Mozilla needs the color in your CSS to read like this:
“background-color: #123455”
So, you will need to add both options to your CSS.
Next, you will need to give the horizontal line some dimensions or it will default to the standard height, width and color set by your browser. Here is a sample code of what your CSS should look like to get the blue horizontal line.
hr {
border: 0;
width: 100%;
color: #123455;
background-color: #123455;
height: 5px;
}
Or you could just add the style to your HTML page directly when you insert a horizontal line, like this:
<hr style="background:#123455" />
Hope this helps.
In a nutshell: it's by far the most memory-efficient.
A std::string
comes with a pointer, a length, and a "short-string-optimization" buffer. But my situation is I need to store a string that is almost always empty, in a structure that I have hundreds of thousands of. In C, I would just use char *
, and it would be null most of the time. Which works for C++, too, except that a char *
has no destructor, and doesn't know to delete itself. By contrast, a std::unique_ptr<char[]>
will delete itself when it goes out of scope. An empty std::string
takes up 32 bytes, but an empty std::unique_ptr<char[]>
takes up 8 bytes, that is, exactly the size of its pointer.
The biggest downside is, every time I want to know the length of the string, I have to call strlen
on it.
A bit more along the same lines
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <- d
}
f(20)
print(attrs.a)
will print "1"
attrs <- {}
attrs.a <- 1
f <- function(d) {
attrs.a <<- d
}
f(20)
print(attrs.a)
Will print "20"
Just restart SQL Server (MSSQLSERVER) service.
You can use the following if you want to specify tricky formats:
df['date_col'] = pd.to_datetime(df['date_col'], format='%d/%m/%Y')
More details on format
here:
Casting or converting to VARCHAR(MAX)
or anything else did not work for me using large integers (in float fields) such as 167382981, which always came out '1.67383e+008'.
What did work was STR()
.
From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections
is the value of maxThreads
unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads
.
In python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b))
.
They are both different. SelectedValue
property gives you the actual value of the item in selection whereas SelectedItem.Text
gives you the display text. For example: you drop down may have an itme like
<asp:ListItem Text="German" Value="de"></asp:ListItem>
So, in this case SelectedValue
would be de
and SelectedItem.Text
would give 'German'
EDIT:
In that case, they aare both same ... Cause SelectedValue
will give you the value stored for current selected item in your dropdown and SelectedItem.Value
will be Value of the currently selected item.
So they both would give you the same result.
In Jupyter Notebook,
SHIFT+ TAB(to move left) and TAB(to move right) movement is perfectly working.
Rotating a vector 90 degrees is particularily simple.
(x, y)
rotated 90 degrees around (0, 0)
is (-y, x)
.
If you want to rotate clockwise, you simply do it the other way around, getting (y, -x)
.
Just use the PHP magic constant __FILE__
to get the current filename.
But it seems you want the part without .php
. So...
basename(__FILE__, '.php');
A more generic file extension remover would look like this...
function chopExtension($filename) {
return pathinfo($filename, PATHINFO_FILENAME);
}
var_dump(chopExtension('bob.php')); // string(3) "bob"
var_dump(chopExtension('bob.i.have.dots.zip')); // string(15) "bob.i.have.dots"
Using standard string library functions is much quicker, as you'd expect.
function chopExtension($filename) {
return substr($filename, 0, strrpos($filename, '.'));
}
I have to add that bundles are used by activities to pass data to themselves in the future.
When the screen rotates, or when another activity is started, the method protected void onSaveInstanceState(Bundle outState)
is invoked, and the activity is destroyed. Later, another instance of the activity is created, and public void onCreate(Bundle savedInstanceState)
is called. When the first instance of activity is created, the bundle is null; and if the bundle is not null, the activity continues some business started by its predecessor.
Android automatically saves the text in text fields, but it does not save everything, and subtle bugs sometimes appear.
The most common anti-pattern, though, is assuming that onCreate()
does just initialization. It is wrong, because it also must restore the state.
There is an option to disable this "re-create activity on rotation" behavior, but it will not prevent restart-related bugs, it will just make them more difficult to mention.
Note also that the only method whose call is guaranteed when the activity is going to be destroyed is onPause()
. (See the activity life cycle graph in the docs.)
That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).
To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).
Add the following somewhere in this section.
body {
font-size: 16px;
}
The font size above is 16 pt font. You can change the number to whatever you want.
In my case it was a view (highly nested, view in view) insertion causing the error in mysql-5.6:
CREATE TABLE tablename AS
SELECT * FROM highly_nested_viewname
;
The workaround we ended up doing was simulating a materialized view (which is really a table) and periodically insert/update it using stored procedures.
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
Don't use ==
use .equals
.
try this instead (IIRC, ZipCode needs to implement Comparable
for this to work.
boolean unique;
Set<ZipCode> s = new TreeSet<ZipCode>();
for( ZipCode zc : zipcodelist )
unique||=s.add(zc);
duplicates = !unique;
Not sure if this counts as an answer - but here is YouTube Video From Google's Course (Developing Android Apps with Kotlin) that explains the difference.
If you have a module defined as an android library project you'll get .aar files for all build flavors (debug and release by default) in the build/outputs/aar/
directory of that project.
your-library-project
|- build
|- outputs
|- aar
|- appframework-debug.aar
- appframework-release.aar
If these files don't exist start a build with
gradlew assemble
for macOS users
./gradlew assemble
A library project has a build.gradle
file containing apply plugin: com.android.library
. For reference of this library packaged as an .aar
file you'll have to define some properties like package and version.
Example build.gradle
file for library (this example includes obfuscation in release):
apply plugin: 'com.android.library'
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
minSdkVersion 9
targetSdkVersion 21
versionCode 1
versionName "0.1.0"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
In your app project you can drop this .aar
file in the libs
folder and update the build.gradle
file to reference this library using the below example:
apply plugin: 'com.android.application'
repositories {
mavenCentral()
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
android {
compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 14
targetSdkVersion 20
versionCode 4
versionName "0.4.0"
applicationId "yourdomain.yourpackage"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
}
}
}
dependencies {
compile 'be.hcpl.android.appframework:appframework:0.1.0@aar'
}
Alternative options for referencing local dependency files in gradle can be found at: http://kevinpelgrims.com/blog/2014/05/18/reference-a-local-aar-in-your-android-project
If you need to share these .aar
files within your organization check out maven. A nice write up on this topic can be found at: https://web.archive.org/web/20141002122437/http://blog.glassdiary.com/post/67134169807/how-to-share-android-archive-library-aar-across
An aar file is just a .zip
with an alternative extension and specific content. For details check this link about the aar format.
Just complementing what Devart said, the below code is not ordering according to the question:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;
Regards,
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
Strlen command is working for me . You can try following code.
// char *s
unsigned int strLength=strlen(s);
I think some of the above may work but using the get_the_category function seems tricky and may give unexpected results.
I think the most direct and simple way to access the cat ID in a category page is:
$wp_query->query_vars['cat']
Cheers
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);
More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
Imagine you've got an HTML element like below:
<a class="toc-item"
href="/books/n/ukhta2333/s5/"
id="book-link-29"
>
Chapter 5. Conclusions and recommendations
</a>
One way you can get all attributes of it is to convert them into an array:
const el = document.getElementById("book-link-29")
const attrArray = Array.from(el.attributes)
// Now you can iterate all the attributes and do whatever you need.
const attributes = attrArray.reduce((attrs, attr) => {
attrs !== '' && (attrs += ' ')
attrs += `${attr.nodeName}="${attr.nodeValue}"`
return attrs
}, '')
console.log(attributes)
And below is the string that what you'll get (from the example), which includes all attributes:
class="toc-item" href="/books/n/ukhta2333/s5/" id="book-link-29"
for example, if you want to close a windows form when an action is performed there are two methods to do it
1.To close it directly
Form1 f=new Form1();
f.close(); //u can use below comment also
//this.close();
2.We can also hide form without closing it
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
Form2 f2 = new Form2();
int flag = 0;
string u, p;
u = textBox1.Text;
p = textBox2.Text;
if(u=="username" && p=="pasword")
{
flag = 1;
}
else
{
MessageBox.Show("enter correct details");
}
if(flag==1)
{
f2.Show();
this.Hide();
}
}
I use the following which will check if package is installed and if dependencies are updated, then loads the package.
p<-c('ggplot2','Rcpp')
install_package<-function(pack)
{if(!(pack %in% row.names(installed.packages())))
{
update.packages(ask=F)
install.packages(pack,dependencies=T)
}
require(pack,character.only=TRUE)
}
for(pack in p) {install_package(pack)}
completeFun <- function(data, desiredCols) {
completeVec <- complete.cases(data[, desiredCols])
return(data[completeVec, ])
}
You don't need to use setAttribute for that - This code works (IE8 also)
<div id="something" >Hello</div>
<script type="text/javascript" >
(function() {
document.getElementById("something").onclick = function() {
alert('hello');
};
})();
</script>
@Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
When I encountered the problem, the changes.xml
document was malformed (missing an end tag). The fix was to edit the XML to make it well formed.
So checking that the XML is well formed can be important, especially when the release plugin does not complain about it.
Just access the Priority
property of the object returned from the pipeline:
$var = (Get-WSManInstance -enumerate wmicimv2/win32_process).Priority
(This won't work if Get-WSManInstance
returns multiple objects.2)
For the second question: to get two properties there are several options, problably the simplest is to have have one variable* containing an object with two separate properties:
$var = (Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
and then use, assuming only one process:
$var.Priority
and
$var.ProcessID
If there are multiple processes $var
will be an array which you can index, so to get the properties of the first process (using the array literal syntax @(...)
so it is always a collection1):
$var = @(Get-WSManInstance -enumerate wmicimv2/win32_process | select -first 1 Priority, ProcessID)
and then use:
$var[0].Priority
$var[0].ProcessID
1 PowerShell helpfully for the command line, but not so helpfully in scripts has some extra logic when assigning the result of a pipeline to a variable: if no objects are returned then set $null
, if one is returned then that object is assigned, otherwise an array is assigned. Forcing an array returns an array with zero, one or more (respectively) elements.
2 This changes in PowerShell V3 (at the time of writing in Release Candidate), using a member property on an array of objects will return an array of the value of those properties.
This works for me in Ansible 2.9:
variable1 = www.example.com.
variable2 = www.example.org.
when: ".com" in variable1
and for not:
when: not ".com" in variable2
If you run mysql --verbose --help | less
it will tell you about line 11 which .cnf
files it will look for.
You can also do mysql --print-defaults
to show you how the configuration values it will use. This can also be useful in identifying just which config file it is loading.
The reason enums work easily with == is because each defined instance is also a singleton. So identity comparison using == will always work.
But using == because it works with enums means all your code is tightly coupled with usage of that enum.
For example: Enums can implement an interface. Suppose you are currently using an enum which implements Interface1. If later on, someone changes it or introduces a new class Impl1 as an implementation of same interface. Then, if you start using instances of Impl1, you'll have a lot of code to change and test because of previous usage of ==.
Hence, it's best to follow what is deemed a good practice unless there is any justifiable gain.
This worked for me on Ubuntu (latest version dated Oct/2020)
I had to first get code from the bash source:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
This got the latest version of node which updated my libraries and got rid of the 'semver' error.
One can issue the SQL*Plus command SET TIMING ON
to get wall-clock times, but one can't take, for example, fetch time out of that trivially.
The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY
will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.
Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".
Check out this question / answer. It's more concise than @Geoff's, and also uses the builtin fputcsv function.
$result = $db_con->query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
You can use pd.DataFrame constructor, giving a numpy array (data) and a list of the names of the columns (columns). To have everything in one DataFrame, you can concatenate the features and the target into one numpy array with np.c_[...] (note the square brackets and not parenthesis). Also, you can have some trouble if you don't convert the feature names (iris['feature_names']) to a list before concatenation:
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= list(iris['feature_names']) + ['target'])
JDK 9 has added InputStream#transferTo(OutputStream out)
for this functionality.
Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***
You can also do it this way.
Create the following named ranges:
nList = the list of original values
nRow = ROW(nList)-ROW(OFFSET(nList,0,0,1,1))+1
nUnique = IF(COUNTIF(OFFSET(nList,nRow,0),nList)=0,COUNTIF(nList, "<"&nList),"")
With these 3 named ranges you can generate the ordered list of unique values with the formula below. It will be sorted in ascending order.
IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-?),nUnique,0)),"")
You will need to substitute the row number of the cell just above the first element of your unique ordered list for the '?' character.
eg. If your unique ordered list begins in cell B5 then the formula will be:
IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-4),nUnique,0)),"")
on windows invoke "cmd /k start http://www.example.com" Infact you can always invoke "default" programs using the start command. For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.
If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.
So try something like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Width="311">
<TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
<TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</Grid>
You could even make this work with a ScrollViewer
Solution using str_pad:
str_pad($digit,2,'0',STR_PAD_LEFT);
Benchmark on php 5.3
Result str_pad : 0.286863088608
Result sprintf : 0.234171152115
Code:
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
str_pad(9,2,'0',STR_PAD_LEFT);
str_pad(15,2,'0',STR_PAD_LEFT);
str_pad(100,2,'0',STR_PAD_LEFT);
}
$end = microtime(true);
echo "Result str_pad : ",($end-$start),"\n";
$start = microtime(true);
for ($i=0;$i<100000;$i++) {
sprintf("%02d", 9);
sprintf("%02d", 15);
sprintf("%02d", 100);
}
$end = microtime(true);
echo "Result sprintf : ",($end-$start),"\n";
It's an asynchronous request, meaning once it's sent it's out there.
In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.
Otherwise, simply ignore the AJAX response.
Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.
Connect as PCT account in the database, then grant the account you are using select access for the table.
grant select on pi_int to Account_used_to_connect
Here's the markup that should work, both locally and remotely - copied from html-5-tutorial.com:
<div id="google_translate_element"></div>
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{pageLanguage: 'en'},
'google_translate_element'
);
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.
Therefore, the following is incorrect as a test to see if obj
is an array of any kind:
// INCORRECT!
public boolean isArray(final Object obj) {
return obj instanceof Object[];
}
Specifically, it doesn't work if obj
is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object
. But it is moot in this case.)
I use Google GWT so I am not allowed to use reflection :(
The best solution (to the isArray
array part of the question) depends on what counts as "using reflection".
In GWT, calling obj.getClass().isArray()
does not count as using reflection1, so that is the best solution.
Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof
expressions.
public boolean isArray(final Object obj) {
return obj instanceof Object[] || obj instanceof boolean[] ||
obj instanceof byte[] || obj instanceof short[] ||
obj instanceof char[] || obj instanceof int[] ||
obj instanceof long[] || obj instanceof float[] ||
obj instanceof double[];
}
You could also try messing around with the name of the object's class as follows, but the call to obj.getClass()
is bordering on reflection.
public boolean isArray(final Object obj) {
return obj.getClass().toString().charAt(0) == '[';
}
1 - More precisely, the Class.isArray
method is listed as supported by GWT in this page.
Have a look at the Requests exception docs. In short:
In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a
ConnectionError
exception.In the event of the rare invalid HTTP response, Requests will raise an
HTTPError
exception.If a request times out, a
Timeout
exception is raised.If a request exceeds the configured number of maximum redirections, a
TooManyRedirects
exception is raised.All exceptions that Requests explicitly raises inherit from
requests.exceptions.RequestException
.
To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.
What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit
).
You can either catch the base-class exception, which will handle all cases:
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e: # This is the correct syntax
raise SystemExit(e)
Or you can catch them separately and do different things.
try:
r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
# Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
# Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
# catastrophic error. bail.
raise SystemExit(e)
As Christian pointed out:
If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call
Response.raise_for_status
. That will raise anHTTPError
, if the response was an http error.
An example:
try:
r = requests.get('http://www.google.com/nothere')
r.raise_for_status()
except requests.exceptions.HTTPError as err:
raise SystemExit(err)
Will print:
404 Client Error: Not Found for url: http://www.google.com/nothere
In the Coursera course, an Introduction to R Programming, this skill was tested. They gave all the students 332 separate csv files and asked them to programmatically combined several of the files to calculate the mean value of the pollutant.
This was my solution:
# create your empty dataframe so you can append to it.
combined_df <- data.frame(Date=as.Date(character()),
Sulfate=double(),
Nitrate=double(),
ID=integer())
# for loop for the range of documents to combine
for(i in min(id): max(id)) {
# using sprintf to add on leading zeros as the file names had leading zeros
read <- read.csv(paste(getwd(),"/",directory, "/",sprintf("%03d", i),".csv", sep=""))
# in your loop, add the files that you read to the combined_df
combined_df <- rbind(combined_df, read)
}
You can use this.getClass().getSimpleName()
, like so:
import java.lang.reflect.Field;
public class Test {
int x;
int y;
public void getClassName() {
String className = this.getClass().getSimpleName();
System.out.println("Name:" + className);
}
public void getAttributes() {
Field[] attributes = this.getClass().getDeclaredFields();
for(int i = 0; i < attributes.length; i++) {
System.out.println("Declared Fields" + attributes[i]);
}
}
public static void main(String args[]) {
Test t = new Test();
t.getClassName();
t.getAttributes();
}
}
Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here
> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop
C:\Users\myname\Desktop is the ouput folder you can change that to your preference
http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL
Try following code will Add one day to current date
select DateAdd(day, 1, GetDate())
And in the same way can use Year, Month, Hour, Second etc. instead of day in the same function
This solution is not good every time. But i have only two columns and I want second column to take all the remaining space. This worked for me
<tr>
<td class="text-nowrap">A</td>
<td class="w-100">B</td>
</tr>
As other answer mentioned depcheck
is good for check unused dependecies in your porject. Use npm outdated
command to check the outdated library.
You could create a YAML file and read it in using PyYaml.
Step 1: Create a YAML file, "employment.yml":
new jersey:
mercer county:
pumbers: 3
programmers: 81
middlesex county:
salesmen: 62
programmers: 81
new york:
queens county:
plumbers: 9
salesmen: 36
Step 2: Read it in Python
import yaml
file_handle = open("employment.yml")
my_shnazzy_dictionary = yaml.safe_load(file_handle)
file_handle.close()
and now my_shnazzy_dictionary
has all your values. If you needed to do this on the fly, you can create the YAML as a string and feed that into yaml.safe_load(...)
.
Continuing from my comment. toString
is not the solution. Some good soul has written whole code for serialization and deserialization of an object in Java. See here: http://www.javabeginner.com/uncategorized/java-serialization
Suggested read:
There is this extensions that adds an event listener to attribute changes.
Usage:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
Bind attrchange handler function to selected elements
$(selector).attrchange({
trackValues: true, /* Default to false, if set to true the event object is
updated with old and new value.*/
callback: function (event) {
//event - event object
//event.attributeName - Name of the attribute modified
//event.oldValue - Previous value of the modified attribute
//event.newValue - New value of the modified attribute
//Triggered when the selected elements attribute is added/updated/removed
}
});
Just copy and paste this code and you can experiment with two modals. Second modal is open after closing the first one:
<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- The Modal 2 -->
<div class="modal" id="myModal2">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Second modal</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
Modal body..
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$('#myModal').on('hidden.bs.modal', function () {
$('#myModal2').modal('show')
})
</script>
Cheers!
Because this is still the top Google hit for this problem, let me add a possible cause. If you're editing your database structure and haven't committed the changes, the database is locked until you commit or revert.
(Probably uncommon, but I'm developing an app so the code and database are both being developed at the same time)
Stop from navigating this code works!
$(document).on("keydown", function (event) {
if (event.keyCode === 8) {
event.preventDefault();
}
});
But for not to restricting text fields but others
$(document).on("keydown", function (event) {
if (event.which === 8 && !$(event.target).is("input, textarea")) {
event.preventDefault();
}
});
To prevent it for specific field simply use
$('#myOtherField').on("keydown", function (event) {
if (event.keyCode === 8 || event.which === 8) {
event.preventDefault();
}
});
Referring to this one below!
Prevent BACKSPACE from navigating back with jQuery (Like Google's Homepage)
int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
System.out.println(g); // Print out the gun
if (i == 2) { // If you're at the third gun
ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
for (Bullet b : bullets) { // Then print every bullet
System.out.println(b);
}
i++; // Don't forget to increment your counter so you know you're at the next gun
}
The following code will reduce the problem to check the protocol. The $_SERVER['APP_URL'] will display the domain name with the protocol
$_SERVER['APP_URL'] will return protocol://domain ( eg:-http://localhost)
$_SERVER['REQUEST_URI'] for remaining parts of the url such as /directory/subdirectory/something/else
$url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];
The output would be like this
History from Learn Python the Hard Way:
Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.
They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.
Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object
class or from another class that inherited from object
:
class NewStyle(object):
pass
Another example is:
class AnotherExampleOfNewStyle(NewStyle):
pass
While an old-style base class looks like this:
class OldStyle():
pass
And an old-style child class looks like this:
class OldStyleSubclass(OldStyle):
pass
You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2
You likely don't have a CA signed certificate installed in your SQL VM's trusted root store.
If you have Encrypt=True
in the connection string, either set that to off (not recommended), or add the following in the connection string:
TrustServerCertificate=True
SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.
Long term, I'd recommend leveraging Let's Encrypt to get a CA signed certificate from a known trusted CA for free, and install it on the VM. Don't forget to set it up to automatically refresh. You can read more on this topic in SQL Server books online under the topic of "Encryption Hierarchy", and "Using Encryption Without Validation".
You can also create the application.properties file manually.
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations). (From the Spring boot features external configuration doc page)
So just go ahead and create it
var swap = function () {
var divs = document.getElementsByTagName('div');
var div1 = divs[0];
var div2 = divs[1];
var div3 = divs[2];
div3.parentNode.insertBefore(div1, div3);
div1.parentNode.insertBefore(div3, div2);
};
This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.
What standards peculiarities does it rely on?
insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.
Although I have not worked C++ at a professional level, in my opinion, it is OK to throw exceptions from the constructors. I do that(if needed) in .Net. Check out this and this link. It might be of your interest.
var arr = Array.prototype.slice.call( htmlCollection )
will have the same effect using "native" code.
Edit
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:
var arr = [].slice.call(htmlCollection);
But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.
Edit
Since ECMAScript 2015 (ES 6) there is also Array.from:
var arr = Array.from(htmlCollection);
Edit
ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from
(although note that Array.from
supports a mapping function as the second argument).
var arr = [...htmlCollection];
I've confirmed that both of the above work on NodeList
.
A performance comparison for the mentioned methods: http://jsben.ch/h2IFA
There's a :data()
filter plugin that does just this :)
Some examples based on your question:
$('a:data("category=music")')
$('a:data("user.name.first=Tom")');
$('a:data("category=music"):data("artist.name=Madonna")');
//jQuery supports multiple of any selector to restrict further,
//just chain with no space in-between for this effect
The performance isn't going to be extremely great compared to what's possible, selecting from $._cache
and grabbing the corresponding elements is by far the fastest, but a lot more round-about and not very "jQuery-ey" in terms of how you get to stuff (you usually come in from the element side). Of th top of my head, I'm not sure this is fastest anyway since the process of going from unique Id to element is convoluted in itself, in terms of performance.
The comparison selector you mentioned will be best to do in a .filter()
, there's no built-in support for this in the plugin, though you could add it in without a lot of trouble.
Options -Indexes
I have to try create .htaccess file that current directory that i want to disallow directory index listing. But, sorry i don't know about recursive in .htaccess code.
Try it.
I implemented it in the following way. I wanted a generic MakeRequest
method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string>
object to house the content to be submitted, and then set the HttpRequestMessage
Content
property with it:
Generic method to call the API:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
Call the method:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
I would suggest via Bitmap:
public void SaveImage(string base64)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save("SavingPath" + "ImageName.jpg");
}
}
}
you can do the next "\"Value3 Line1 Value3 Line2\""
. It works for me generating a csv file in java
For sending data to a service you can use:
Intent intent = new Intent(getApplicationContext(), YourService.class);
intent.putExtra("SomeData","ItValue");
startService(intent);
And after in service in onStartCommand() get data from intent.
For sending data or event from a service to an application (for one or more activities):
private void sendBroadcastMessage(String intentFilterName, int arg1, String extraKey) {
Intent intent = new Intent(intentFilterName);
if (arg1 != -1 && extraKey != null) {
intent.putExtra(extraKey, arg1);
}
sendBroadcast(intent);
}
This method is calling from your service. You can simply send data for your Activity.
private void someTaskInYourService(){
//For example you downloading from server 1000 files
for(int i = 0; i < 1000; i++) {
Thread.sleep(5000) // 5 seconds. Catch in try-catch block
sendBroadCastMessage(Events.UPDATE_DOWNLOADING_PROGRESSBAR, i,0,"up_download_progress");
}
For receiving an event with data, create and register method registerBroadcastReceivers() in your activity:
private void registerBroadcastReceivers(){
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int arg1 = intent.getIntExtra("up_download_progress",0);
progressBar.setProgress(arg1);
}
};
IntentFilter progressfilter = new IntentFilter(Events.UPDATE_DOWNLOADING_PROGRESS);
registerReceiver(broadcastReceiver,progressfilter);
For sending more data, you can modify method sendBroadcastMessage();
. Remember: you must register broadcasts in onResume() & unregister in onStop() methods!
UPDATE
Please don't use my type of communication between Activity & Service. This is the wrong way. For a better experience please use special libs, such us:
1) EventBus from greenrobot
2) Otto from Square Inc
P.S. I'm only using EventBus from greenrobot in my projects,
Because the people who designed the library format didn't want to "waste" space for rarely used information like C preprocessor macros and function declarations.
Since you need that info to tell your compiler "this function is available later when the linker is doing its job", they had to come up with a second file where this shared information could be stored.
Most languages after C/C++ store this information in the output (Java bytecode, for example) or they don't use a precompiled format at all, get always distributed in source form and compile on the fly (Python, Perl).
There is no such thing like a DateTime
without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime
including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan
or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
Here is a quick example of a binary insert:
class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.l_child is None:
root.l_child = node
else:
binary_insert(root.l_child, node)
else:
if root.r_child is None:
root.r_child = node
else:
binary_insert(root.r_child, node)
def in_order_print(root):
if not root:
return
in_order_print(root.l_child)
print root.data
in_order_print(root.r_child)
def pre_order_print(root):
if not root:
return
print root.data
pre_order_print(root.l_child)
pre_order_print(root.r_child)
r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))
3
/ \
1 7
/
5
print "in order:"
in_order_print(r)
print "pre order"
pre_order_print(r)
in order:
1
3
5
7
pre order
3
1
7
5
Change your selector to
val = j$("#select_2 option:selected").text();
You're selecting the <select>
instead of the <option>
Simple way to show some text:
Snackbar.make(view, "Sample Text", Snackbar.LENGTH_SHORT).show();
and to show text with button:
Snackbar.make(view, "Sample Text", Snackbar.LENGTH_SHORT).setAction("Ok", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
}).show();
yourList = ["a", "b", "a", "c", "c", "a", "c"]
expected outputs {a: 3, b: 1,c:3}
duplicateFrequencies = {}
for i in set(yourList):
duplicateFrequencies[i] = yourList.count(i)
Cheers!! Reference
You can't link to file:///
from an HTML document that is not itself a file:///
for security reasons.
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
Use the code
x = seq(0,100,5) #this means (starting number, ending number, interval)
the output will be
[1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
[17] 80 85 90 95 100
It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.
Though any optimizer would most likely optimize it out anyway...
To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.
If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.
JsonReader.jsonToMaps(String json)
where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.
JsonReader.jsonToJava(String json)
will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by
JsonWriter.objectToJson(MyClass foo).
You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.
But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:
preventDefault
method)First, you'll have to cancel the form submit action like so:
$("#myform").submit(function(event) {
// Cancels the form's submit action.
event.preventDefault();
});
And then, grab the value of the data. Let's just assume you have one text box.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
});
And then fire off a request. Let's just assume it's a POST request.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
// I like to use defers :)
deferred = $.post("http://somewhere.com", { val: val });
deferred.success(function () {
// Do your stuff.
});
deferred.error(function () {
// Handle any errors here.
});
});
And this should about do it.
Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.
Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.
$.post("http://somewhere.com", { val: val }, function () {
// Start partying here.
}, function () {
// Handle the bad news here.
});
You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):
using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
File.Copy(@"\\server\read\file", @"\\server2\write\file");
}
I know there is already an answer to this but I just found a better solution using the variableWidth parameter, just set it to true in the settings of each breakpoint, like this:
$('#featured-articles').slick({
arrows: true,
autoplay: true,
autoplaySpeed: 3000,
dots: true,
draggable: false,
fade: true,
infinite: false,
responsive: [
{
breakpoint: 620,
settings: {
arrows: true,
variableWidth: true
}
},
{
breakpoint: 345,
settings: {
arrows: true,
variableWidth: true
}
}
]
});